This example shows how to bridge Java Util Logging (JUL) logs to SLF4J. We are going to use Log4J as SLF4J implementation provider. That means all log messages send via JUL API will redirect to SLF4J layer which will then use Log4J as implementation provider to output the messages.
Dependencies
pom.xml<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jul-to-slf4j</artifactId>
<version>1.8.0-alpha2</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.8.0-alpha2</version>
</dependency>
Using JUL API
package com.logicbig.example;
import java.util.logging.Logger;
public class MyClass {
private static Logger LOGGER = Logger.getLogger(MyClass.class.getName());
public static void doSomething() {
LOGGER.info("a test message");
}
}
Log4j configuration
src/main/resources/log4j.propertieslog4j.rootCategory=INFO, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MMMM-dd HH:mm:ss:SSS} %5p %t %c{2}:%L - %m%n
Enabling the bridge
package com.logicbig.example;
import org.slf4j.bridge.SLF4JBridgeHandler;
import java.util.logging.LogManager;
public class ExampleMain {
static {
LogManager.getLogManager().reset();
SLF4JBridgeHandler.install();
}
public static void main(String[] args) {
MyClass.doSomething();
}
}
Output2017-September-11 12:49:12:136 INFO com.logicbig.example.ExampleMain.main() example.MyClass:10 - a test message
In above main class we installed SLF4JBridgeHandler , which is an implementation of java.util.logging.Handler . Check out this tutorial to have an understanding of JUL Handler.
Example ProjectDependencies and Technologies Used: - jul-to-slf4j 1.8.0-alpha2: JUL to SLF4J bridge.
- slf4j-log4j12 1.8.0-alpha2: SLF4J LOG4J-12 Binding.
- JDK 1.8
- Maven 3.3.9
|