Close

Redirecting Java Util Logging (JUL) to SLF4j + Log4j2 with jul-to-slf4j bridge

[Updated: Sep 21, 2017, Created: Sep 21, 2017]

This example shows how to redirect logs from Java Util Logging (JUL) to SLF4J layer, which in turn uses Log4j2 to output logs.

Dependencies

pom.xml

<dependency>
   <groupId>org.slf4j</groupId>
   <artifactId>jul-to-slf4j</artifactId>
   <version>1.7.25</version>
</dependency>
<dependency>
   <groupId>org.apache.logging.log4j</groupId>
   <artifactId>log4j-slf4j-impl</artifactId>
   <version>2.9.1</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/log4j2.properties

appenders=xyz

appender.xyz.type = Console
appender.xyz.name = myOutput
appender.xyz.layout.type = PatternLayout
appender.xyz.layout.pattern = [%d{yy-MMM-dd HH:mm:ss:SSS}] [%p] [%c{1}:%L] - %m%n

rootLogger.level = info

rootLogger.appenderRefs = abc

rootLogger.appenderRef.abc.ref = myOutput

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();
  }
}

Output

[17-Sep-21 13:04:42:283] [INFO] [MyClass:10] - a test message

SLF4JBridgeHandler is an implementation of java.util.logging.Handler which is needed to install the bridge.

Example Project

Dependencies and Technologies Used:

  • jul-to-slf4j 1.7.25: JUL to SLF4J bridge.
  • log4j-slf4j-impl 2.9.1: The Apache Log4j SLF4J API binding to Log4j 2 Core.
  • JDK 1.8
  • Maven 3.3.9

JUL to SLF4J + Log4j2 Example Select All Download
  • jul-to-slf4j-log4j2-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
        • resources

See Also