Monday, 29 October 2012

Why SLF4j


SLF4J -   Simple Logging Framework for Java
SLF4j is a wrapper for various Logging Frameworks. The Users can plugin their logging framework for their environment without much changes.  This library is most useful when developing  frameworks for other applications to use.  The framework provides logging mechanism with slf4j enabled, then whomever uses the framework can plugin their logging framework of their choice without much hurdle.


How to plugin SLF4j using Maven
You need to add slf4j-api jar to the dependency. If you have no choice of logging framework to enable, just add  slf4j-simple jar which is  the Simple logging Implementation -  Only messages of level INFO and higher are printed. This binding may be useful in the context of small applications.


The SLF4j api dependency
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.6.6</version>
</dependency>

Simple implementation dependency
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.6.6</version>
</dependency>

Below is the sample code to test the logging

package test;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LoggerTest
{
    public static void main(String args[])
    {
        Logger logger = LoggerFactory.getLogger(LoggerTest.class);
        logger.info("Testing slf4j");
    }
}

Output when you run the above code
1 [main] INFO test.LoggerTest - Testing slf4j 
 
How is Logback Special to slf4j?
Logback has a direct implementation of Slf4j. If we want to plug this in,  a slf4j wrapper jar file is not needed.  Logback's ch.qos.logback.classic.Logger class is a direct implementation of SLF4J's org.slf4j.Logger interface. Thus, using SLF4J in conjunction with logback involves strictly zero memory and computational overhead. 
 
Famous slf4j binding dependencies
To bind the logging frameworks we may have to include the slf4j binding dependencies to plugin. If you have multiple plugins, the 1st in the order of compiler dependency is picked up.   The good thing about slf4j is, it resolvs the logging plugin  at compile time.  

Below are the slf4j wrappers fof different logger
slf4j-log4j12-1.7.2.jarLOG4j
slf4j-jdk14-1.7.2.jarUtil Logging
slf4j-simple-1.7.2.jarSIMPLE
slf4j-jcl-1.7.2.jarJCL
Diagram showing SLF4J binding and respecting jars
References:
FAQs:  http://slf4j.org/faq.html

No comments:

Post a Comment