SLF4J is an abstract layer for logging APIs. The principle is roughly the same as Jakarta Commons Logging. The advantages of the use of such a layer enable to be completely independant of the logging implementation. So it’s possible to easily change the logging implementation without modifying the existing code. You only have to change the configuration of the implementation. And finally in the case of the conception of a library, this leaves the user to choose the logging system.
You gonna tell me : if Commons Logging makes already that, why an other framework of logging abstraction ? Simply, because Commons Logging as his defaults. The first one concern the loading of the logging implementation. Indeed, the search is made dynamically at the execution through a classloader system. And this method can be problematic in several situations by example when the application use custom classloaders or when using OSGi. And finally the implementation of the Commons Logging can cause some memory leaks.
Furthermore, Commons Logging constrain the user to test if a loging level is enabled or not before making logging containing heavy concatenation.
We will see than SLF4J solve this problems in an efficient way.
You can download the official distribution on the SLFJ4J website.
2. Select the logging implementation
Unlike of Commons Logging, SLF4J doesn’t resolve the logging implementation at execution, but directly at the compilation with a bridging API. So more than the JAR of SLF4J you need the following JARs : the bridging JAR and the JAR of the implementation. Here is what you get with Log4J :
All that is made only by adding a JAR to the classpath. No need to configure nothing else than the implementation. You just have to be careful to call only the interface of SLF4J otherwise there is no more interest to use an abstract layer
3. Redirect calls from others implementations
More than offer a logging abstraction, SLF4J give the user the possibility to redirect calls for an implementation to SLF4J who will himself redirect them to the used implementation.
For that, you just have to replace the Jar of the xxx implementation by the xxx-to-slf4j.jar file who will intercept the calls and redirect them to the SLF4J implementation.
The following diagram show exactly how the calls are redirected :
Warning : Of course, you mustn’t add the implementation and the jar of redirection in the classpath at the same time. And more important, you must never use the jar of redirection of the used SLF4J implementation. This creates an infinite circle that will be make your application crashes.