logo

SLF4J

Last Updated: 2021-11-19

In POM

In pom, only depend on slf4j-log4j12, it will grab slf4j-api and log4j

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

In Java

In Java, declare as private static final and use all capital letters LOG to comply with Java coding convention.

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

public class HelloWorld {

    private static final Logger LOG = LoggerFactory.getLogger(HelloWorld.class);

    public static void main(String[] args) {
        LOG.info("Hello World");
    }
}

Deployment

The code is simple, not depending on classloader, so cannot specify which binding to load.

In exchange for that simplicity, it is the responsibility of person who deploy the package to make sure there is ONE AND ONLY ONE binding jar in CLASSPATH.

"Select logging framework at deployment time", not by configuration but by putting the correct jar in CLASSPATH.

Error

Error:

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.

Reason:

Jars of slf4j cannot be found in CLASSPATH.

Solution:

Add the path to CLASSPATH, e.g. in ~/.bashrc

CLASSPATH=$CLASSPATH:/path/to/slf4j-log4j12-<version>.jar