SLF4J with Log4j example

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

This example shows how to use SLF4J with log4j.

Dependencies

pom.xml

<dependency>
   <groupId>org.slf4j</groupId>
   <artifactId>slf4j-log4j12</artifactId>
   <version>1.8.0-alpha2</version>
</dependency>

log4j configuration

src/main/resources/log4j.properties

log4j.rootCategory=INFO, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yy-MM-dd HH:mm:ss:SSS} %5p %t %c{2}:%L - %m%n

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-08-03 16:21:36:828  INFO com.logicbig.example.ExampleMain.main() example.MyClass:11 - a test message

Example Project

Dependencies and Technologies Used :

  • slf4j-log4j12 1.8.0-alpha2: SLF4J LOG4J-12 Binding.
  • JDK 1.8
  • Maven 3.3.9

SLF4J with Log4J Example Select All Download
  • slf4j-log4j-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
        • resources

See Also