Logging with SLF4J

Logging is important in software development. There are many famous frameworks to be used for logging: Log4j, Logback, java.util.logging… If we wanna change the logging framework without affecting Java code, SLF4J is the good choice.

This tutorial writes about SLF4J with example of how to apply SLF4J in some logging frameworks.

I. What is SLF4J

SLF4J, the Simple Logging Facade for Java, serves as a simple facade or abstraction for many logging frameworks above. The layer we apply logging is independent from logging implementation. We only have to choose the configuration of logging system.

slf4j-layer

To work with SLF4J, we add its dependency to our Maven Project pom file:

SLF4J API is easy to use, this is how we get a logger:

And this is a very simple example of using that Logger:

Run the project, the console window shows:

This warning is printed because no slf4j binding could be found on the class path. It lacks of logging implementation.

slf4j-layer-null

We can apply the native implementation of slf4j-api: slf4j-simple or slf4j-nop
slf4j-layer-simple-nop

For slf4j-nop, add this dependency after slf4j-api dependency:

Run the project, the console window shows only:

For slf4j-simple, add this dependency after slf4j-api dependency:

Run the project, the console window shows an additional simple logging:

Notice that, If we use more than one loggin implementation, SLF4J will emit a warning with listing the location of those bindings:

It is because SLF4J API is designed to bind with ONE and only ONE underlying logging framework at a time.

II. Supported Frameworks
1. Logback

slf4j-layerlogback
Add this dependency after slf4j-api dependency:

The Dependency Hierarchy after that is:
slf4j-dependency-logback
Run the project, the console window shows:

2. java.util.logging

slf4j-layer-jdk14
Add this dependency after slf4j-api dependency:

The Dependency Hierarchy after that is:
slf4j-dependency-jdk14
Run the project, the console window shows:

3. Log4j

slf4j-layer-log4j12
Add this dependency after slf4j-api dependency:

The Dependency Hierarchy after that is:
slf4j-dependency-log4j12
Run the project, the console window shows:

It is because we haven’t set configuration for Log4j.
To do this, we can look back to the post How to configure Apache Log4j2 with XML Configuration.
Or create a configuration file (reference from http://logging.apache.org/log4j/1.2/manual.html)

Run the project again, the console window shows:

III. Source code
1. Technology

– Java 1.8
– Maven 3.3.9
– Spring Tool Suite – Version 3.8.1.RELEASE (It’s OK if you use Eclipse)

2. Download Link

loggingslf4j

3. Check results

– Config maven build:
clean install
– Open pom.xml file and modify
– Run project with mode Java Application


Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*