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

  • get a logger
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
MDC.put("userId", 128746);

Binding

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

  • NOP - slf4j-nop-1.7.28.jar NOP - Nothing (No Operation)
    • version 1.2: - slf4j-log4j12-1.7.28.jar + log4j.jar
    • version 2: log4j-slf4j-impl + log4j.jar
  • java.util.logging - slf4j-jdk14-1.7.28.jar
  • Simple - slf4j-simple-1.7.28.jar - Simple implementation for small app, outputs all events to System.err. Only messages of level INFO and higher are printed.
  • Jakarta Commons Logging - slf4j-jcl-1.7.28.jar
  • logback - logback-classic-1.2.3.jar (requires logback-core-1.2.3.jar)

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


Powered by ComboStrap