Quantcast
Channel: Baeldung
Viewing all articles
Browse latest Browse all 4536

Introduction to SLF4J

$
0
0

The Master Class of "Learn Spring Security" is live:

>> CHECK OUT THE COURSE

 1. Overview

Simple Logging Facade for Java (abbreviated SLF4J) – acts as a facade for different logging frameworks (e.g. java.util.logging, logback, Log4j). It offers a generic API making the logging independent of the actual implementation.

This allows for different logging frameworks to coexist. It also helps migrate from one framework to another. Finally, apart from standardized API, it also offers some “syntactic sugar”.

This article will discuss the dependencies and configuration needed to integrate SLF4J with Log4j2, Logback, Log4J2 and Jakarta Commons Logging. More about each of this implementations you can read in article Introduction to Java Logging.

2. The Log4j2 Setup

To use SLF4J with Log4j2 you should add the following libraries to pom.xml:

<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-api</artifactId>
    <version>2.7</version>
</dependency>
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.7</version>
</dependency>
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-slf4j-impl</artifactId>
    <version>2.7</version>
</dependency>

The latest version can be found here: log4j-api, log4j-core, log4j-slf4j-impl.

The actual logging configuration is adhering to native Log4j 2 configuration. Let’s see how the Logger instance is created:

public class SLF4JExample {

    private static Logger logger = LoggerFactory.getLogger(SLF4JExample.class);

    public static void main(String[] args) {
        logger.debug("Debug log message");
        logger.info("Info log message");
        logger.error("Error log message");
    }
}

Note that the Logger and LoggerFactory belong to the org.slf4j package. An example of a project, running with the explained configuration is available here.

3. The Logback Setup

To use SLF4J with Logback you don’t need to add SLF4J to your classpath. Logback is already using SLF4J. It’s considered as the reference implementation. We need only to include the Logback library:

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

The latest version can be found here: logback-classic.

The configuration is Logback-specific but works seamlessly with SLF4J. With the proper dependencies and configuration in place, the same code from previous sections can be used to handle the logging.

 4. The Log4j Setup

In the previous sections, we covered a use-case where SLF4J “sits” on top of the particular logging implementation. Used like this, it completely abstracts away the underlying framework.

There are cases when an existing logging solution cannot be replaced e.g. due to third-party requirements. This, however, does not mean that the project is “sentenced” only to the already used framework.

SLF4J can be configured as a bridge, where the calls to an existing framework are redirected to it. Let’s add the necessary dependencies to create a bridge for Log4j:

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>log4j-over-slf4j</artifactId>
    <version>1.7.21</version>
</dependency>

With the dependency in place (check for latest at log4j-over-slf4j), all the calls to Log4j will be redirected to SLF4J. Consider the official documentation to learn more about bridging existing frameworks.

Just as with the other frameworks Log4j can serve as an underlying implementation. Let’s add the necessary dependencies:

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.7.21</version>
</dependency>
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>

Latest version could be found here for slf4j-log4j12 and log4j. An exemplary project, configured in the manner explained is available here.

5. JCL Bridge Setup

In the previous sections, we showed how the same code base can be used to support logging using different implementations. While this is the main promise and strength of SLF4J, it is also the goal behind JCL (Jakarta Commons Logging or Apache Commons Logging).

JCL is, by its intentions, a framework similar to SLF4J. The major difference is that JCL resolves the underlying implementation during execution-time through a class loading system. This approach is perceived problematic in cases where there are custom classloaders at play.

SLF4J resolves its bindings at compile-time. It’s perceived simpler yet powerful enough.

Luckily, two frameworks can work together in the bridge mode:

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>jcl-over-slf4j</artifactId>
    <version>1.7.21</version>
</dependency>

The latest dependency version can be found here jcl-over-slf4j.

As with the other cases, the same code-base will run just fine. An example of a complete project running this setup is available here.

6. Further SLF4J Goodness

SLF4J provides additional that can make logging more efficient and code more readable. For example, SLF4J provides a very useful interface for working with parameters:

String variable = "Hello John";
logger.debug("Printing variable value: {}", variable);

Here is the code example of Log4j that doing the same thing:

String variable = "Hello John";
logger.debug("Printing variable value: " + variable);

As you can see, Log4j will concatenate Strings regardless of debug level being enabled or not. In high-load applications, this may cause performance issues. SLF4J will concatenate Strings only when the debug level is enabled. To do the same with Log4J you need to add extra if block which will check if debug level is enabled or not:

String variable = "Hello John";
if (logger.isDebugEnabled()) {
    logger.debug("Printing variable value: " + variable);
}

SLF4J standardized the logging levels which are different for the particular implementations. The FATAL logging level got dropped (it was introduced in Log4j) based on the premise that in a logging framework, we should not decide when an application should be terminated.

The logging levels used are ERROR, WARN, INFO, DEBUG, TRACE. You can read more about using them in the Introduction to Java Logging article.

7. Conclusion

SLF4J helps with the silent switching between logging frameworks. It is simple, yet flexible, and allows for readability and performance improvements.

As usual, the code can be found over on GitHub. In addition, we’re referencing two other projects dedicated to different articles, but containing discussed log configurations, here and here.

I just released the Master Class of "Learn Spring Security" Course:

>> CHECK OUT THE COURSE


Viewing all articles
Browse latest Browse all 4536

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>