SLF4J with Logback example

[Updated: Oct 23, 2017, Created: Sep 10, 2017]

This example shows how to use SLF4J with Logback.

Dependencies

pom.xml

<dependency>
   <groupId>ch.qos.logback</groupId>
   <artifactId>logback-classic</artifactId>
   <version>1.2.3</version>
</dependency>

Logback configuration

src\main\resources\logback.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss:SSS} %5p %t %c{2}:%L - %m%n</pattern>
        </encoder>
    </appender>
    <root level="INFO">
        <appender-ref ref="stdout"/>
    </root>
</configuration>

Check out Logback log formatting specification here

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

2017-09-10 15:05:54:704  INFO com.logicbig.example.ExampleMain.main() c.l.e.MyClass:11 - a test message

Example Project

Dependencies and Technologies Used :

  • logback-classic 1.2.3: logback-classic module.
  • JDK 1.8
  • Maven 3.3.9

SLF4J with Logback Example Select All Download
  • logback-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
        • resources

See Also