Table of Contents

Java - Slf4j

About

slf4j 1)) is a façade for loggers.

To use a specific logger, add one of the binding logger package.

Dependency

Library should declare a runtime dependency only on on slf4j-api and not on any SLF4J binding but only

dependencies {
  runtime 'org.slf4j:slf4j-api:1.7.25'
}

Disable

To disable SLF4J when you have it as transitive dependency, add the NOP binding as runtime dependency.

Example with Gradle

dependencies {
  implementation 'org.slf4j:slf4j-nop:1.7.30'
}

Usage

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

Concept

Marker sqlMarker = MarkerFactory.getMarker("SQL");
// This is a sql message
logger.debug(sqlMarker ,"SELECT * FROM {}", table);
MDC.put("userId", 128746);

Binding

To switch of logging frameworks, just replace the below jar bindings as dependencies (in the classpath)

How To

How to suppress the error message when you are not using SLF4J

Even if you don't use SLF4J as a logging system, you may have it in your application as transitive dependency (a dependency of your dependency) and you will get this error when starting your application.

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.

To suppress this message, if you don't want to use SLF4, add the NOP binding as a dependency.

Example with Gradle

dependencies {
  runtime 'org.slf4j:slf4j-nop:1.7.30'
}

How to suppress any log

Because slf4j is just a façade (a wrapper), you need to set the log level on your chosen logger.

For instance, with the JDK logger, if you want to disable the log from a library such as thymeleaf because you know that may get an error, you would do it this way:

Logger logger = Logger.getLogger(org.thymeleaf.TemplateEngine.class.getName());
logger.setLevel(Level.OFF);

Just check which implementation you have chosen to show slf4j logs.

Documentation / Reference