SLF4J

Slf4j Configuration File Example

In this example, we are going to see how to configure Slf4j with some popular logging frameworks. SLF4J is a facade or an abstraction layer over various logging frameworks. Ok, what does that mean?

Also known as Simple logging Facade for Java is not actually a logging implementation, instead, it’s an abstraction layer. It allows you to use any logging library with it. Now if you would ask why SLF4J when we already have so many logging frameworks. The answer is, you can write your piece of pluggable code using SLF4J for logging without worrying about the underlying implementation. Now whatever the application which will use your pluggable piece, can use the logging implementation of it’s own choice.

You can say SLF4J is to logging what JPA is to ORM. This is just an analogy; if you don’t know JPA, it’s fine.

For this example, we use the following tools on a Windows 10 platform:

  • Eclipse IDE
  • Apache Maven
  • JDK 1.8
  • Slf4j 1.7.25

Let’s get started with the example.

1. Create a Maven Project

We will create a bare minimum Maven project. Once you have the Maven installed and running on your machine, issue the following command from the command line.

mvn archetype:generate -DgroupId=com.javacodegeeks -DartifactId=slf4jconfig-log4j -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

This will create a App.java by default in a default project structure with a pom.xml. Later on we will add SLF4J dependencies to it. In our example, Maven will manage dependencies for us and we don’t need to download any jars explicitly.

2. Steps to Configure SLF4J in your project

2.1. Add SLF4J (facade) API

Add the dependency to the latest slf4j-api.jar to your class path. With this you will be able to log to an abstract logging layer.

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.javacodegeeks</groupId>
  <artifactId>slf4jconfig-log4j</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>slf4jconfig-log4j</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
    	<groupId>org.slf4j</groupId>
    	<artifactId>slf4j-api</artifactId>
    	<version>1.7.25</version>
    </dependency>
  </dependencies>
</project>

You can code without an actual logging implementation and still able to use all the features in your code that any logging implementation provides. Rename App.java to HelloLog4J.java. Create an instance of Logger (in this case SLF4J Logger) and let’s just output an info for our example.

HelloLog4J.java

package com.javacodegeeks.slf4jconfig_log4j;

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

/**
 * HelloLog4J!
 *
 */
public class HelloLog4J 
{
    public static void main( String[] args )
    {
    	Logger logger = LoggerFactory.getLogger(HelloLog4J.class);
        logger.info("This is how you configure Log4J with SLF4J");
    }
}

Note: At this point we haven’t provided any logging implementation in which case SLF4J silently discards all logging (SLF4J in this case binds to NOPLogger). At this point if you run the program, it will give an output like this:

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.

2.2. Add desired logging framework and corresponding SLF4J binding

During deployment, it is necessary to provide the actual logging implementation otherwise SLF4J will ignore all the log messages. The SLF4J API talks to the actual logging implementation via a SLF4J binding. Also, the SLF4J binding is specific to the logging framework you want to use in your project. In the absence of  the correct SLF4J binding, SLF4J API won’t recognize the logging framework.

NOTE: When using Maven, adding just the binding is enough. It will automatically resolve the underlying logging implementation though our examples include the underlying depenency as well.

2.2.1. SLF4J with Log4J

The binding for log4j is added to pom.xml.

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.javacodegeeks</groupId>
  <artifactId>slf4jconfig-log4j</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>slf4jconfig-log4j</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
    	<groupId>org.slf4j</groupId>
    	<artifactId>slf4j-api</artifactId>
    	<version>1.7.25</version>
    </dependency>
    <dependency>
    	<groupId>org.slf4j</groupId>
    	<artifactId>slf4j-log4j12</artifactId>
    	<version>1.7.25</version>
    </dependency>
    <dependency>
    	<groupId>log4j</groupId>
    	<artifactId>log4j</artifactId>
    	<version>1.2.17</version>
    </dependency>
  </dependencies>
</project>

Now we must add a log4j configuration file for log4j to work and place it at the root of the applications’ classpath.

# Root logger option
log4j.rootLogger=INFO, stdout

# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1} - %m%n

Run the code you created in Step 1. You will see an output like this.

2017-03-21 23:31:13 INFO  HelloLog4J - This is how you configure Log4J with SLF4J

2.2.2. SLF4J with Logback

Add the binding for logback in pom.xml.

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

Run the code you created in Step 1. You will see an output like this.

00:21:47.468 [main] INFO  c.j.slf4jconfig_logback.HelloLogback - This is how you configure Logback with SLF4J

2.2.3. SLF4J with Java Logging

Add the binding for java logging in pom.xml.

<dependency>
	<groupId>org.slf4j</groupId>
	<artifactId>slf4j-jdk14</artifactId>
	<version>1.7.25</version>
</dependency>

Run the code you created in Step 1. You will see an output like this.

Mar 22, 2017 12:29:17 AM com.javacodegeeks.slf4jconfig_javalogging.HelloJavaLogging main
INFO: This is how you configure Java Logging with SLF4J

3. Summary

SLF4J is not a logging framework.

If you noticed in the examples above, you don’t need to change anything in your code while changing the logging framework; just the binding jar and the underlying logging implementation (this is the reason why SLF4J is called an abstraction layer and what makes it different from logging frameworks). That’s the beauty of SLF4J and comes in real handy when you write pluggable pieces of code.

NOTE:

  1. SLF4J can be used with one and only one logging implementation of your choice. So, while configuring a new binding and logging implementation, remove the previous one.
  2. The binding with the underlying logging framework has to be provided at the deployment time.

4. Download The Source Code

You can download the full source code of this example here: slf4jconfig-example.zip

Mayank Gupta

Senior JEE developer with experience in large scale IT projects, especially in the telecommunications and financial services sectors. Mayank has been designing and building J2EE applications since 2007. Fascinated by all forms of software development; keen to explore upcoming areas of technology like AI, machine learning, blockchain development and AR. Lover of gadgets, apps, technology and gaming.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Elijah
Elijah
7 years ago

To clarify what you’re saying then if I want to use a logger other than log4j then I would implement the examples of 2.2.2. SLF4J with Logback by replacing in the POM the dependency blocks on lines 23 and 28 with the ones for Logback?

Back to top button