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

Simple implementation 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);"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-jdk14-1.7.2.jarUtil Logging
Diagram showing SLF4J binding and respecting jars

1 comment: