SLF4J Binding to JDK Loger Example


How to use SLF4J API with JDK Logger?

✍: Guest


If you want to use SLF4J API with JDK Logger, you need specify slf4j-api-*.jar and slf4j-jdk14-*.jar in Java classpath as shown in this tutorial.

1. Write a simple Java program,, to use SLF4J API:

// Copyright (c)
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Hello {
  private static final Logger log = LoggerFactory.getLogger("fyiLog");
  public static void main(String[] args) {
    System.out.println("Log class: "+log.getClass().getName());
    log.error("Hello - error");
    log.warn("Hello - warn");"Hello - info");
    log.debug("Hello - debug");
    log.trace("Hello - trace");

2. Run with slf4j-api-1.7.31.jar and slf4j-jdk14-1.7.31.jar.

$ java -version 
java version "15" 2020-09-15

$ java -cp slf4j-api-1.7.31.jar:slf4j-jdk14-1.7.31.jar

Log class: org.slf4j.impl.JDK14LoggerAdapter

Jul 04, 2021 6:04:27 PM Hello main
SEVERE: Hello - error
Jul 04, 2021 6:04:27 PM Hello main
WARNING: Hello - warn
Jul 04, 2021 6:04:27 PM Hello main
INFO: Hello - info

3. Review the output:

  • The SLF4J API finds the SLF4J-to-JDK Logger bridge library in the classpath.
  • The SLF4J API binds the SLF4J-to-JDK Logger bridge library automatically.
  • The SLF4J-to-JDK Logger bridge is implemented in org.slf4j.impl.JDK14LoggerAdapter class.
  • The SLF4J-to-JDK Logger bridge actually calls the JDK logger class, JDK java.util.logging, to get logginng done.


SLF4J Binding to Log4J Loger Example

SLF4J Binding to Simple Logger Example

Using slf4j-*.jar in Java Programs

⇑⇑ SLF4J - Simple Logging Facade for Java

2021-12-23, 579🔥, 0💬