Close

SLF4J with Log4j2 example

[Last Updated: Sep 21, 2017]

This example shows how to use SLF4J with log4j2.

Dependencies

pom.xml

<dependency>
   <groupId>org.apache.logging.log4j</groupId>
   <artifactId>log4j-slf4j-impl</artifactId>
   <version>2.9.0</version>
</dependency>

log4j2 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

Using SLF4J API

package com.logicbig.example;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MyClass {

  private static Logger LOGGER = LoggerFactory.getLogger(MyClass.class);

  public static void doSomething() {
      LOGGER.info("a test message");
  }
}
package com.logicbig.example;

public class ExampleMain {

  public static void main(String[] args) {
      MyClass.doSomething();
  }
}

Output

[17-Sep-21 10:48:30:393] [INFO] [MyClass:11] - a test message

Example Project

Dependencies and Technologies Used:

  • log4j-slf4j-impl 2.9.0: The Apache Log4j SLF4J API binding to Log4j 2 Core.
  • JDK 1.8
  • Maven 3.3.9

SLF4J with Log4J2 Example Select All Download
  • slf4j-log4j2-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
        • resources
    • pom.xml

    See Also