SLF4J setup

The SLF4J acronym stands for Simple Logging Facade for Java. It is very similar to Apache Commons Logging (also known as JCL), of which it is kind of a successor.

SLF4J makes the Java code that uses it almost independent to the actual underlying log framework. In a tiny project this is usually not an issue, but especially when developing a library, or same other kind of modular code, that is meant be used by possibly unknown clients, this independence from the actual logging tool (Standard JDK, log4j, backlog, ...) could easily be a key factor.

Let's start form scratch, first step is downloading the library. You can find it on slf4j.org. At the time of writing this post, 1.6.4 is the latest available version.

SLF4J is provided as a compressed file, download it and expand it in some location available to your developer workspace. Then add the slf4j-api-1.6.4.jar (version number may vary) to the Java Build Path of your project.

Finally you can create, compile, and even run (with probably unexpected results) a simple SLF4J-based application:
// ...
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HelloWorld {
    private static final Logger log = LoggerFactory.getLogger(HelloWorld.class);
    // ...

    public static void main(String[] args) {
        log.info("Hello World");

        // ...
    }
}
If you expected to get somewhere (on the standard output or error console would be a good guess) an hello message, well, you would be disappointed, because what you get is 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.
Thinking better we should admit that SLF4J is right. It doesn't know which logging framework to use, it doesn't even know if we would like to see any feedback or that would be terribly embarrassing. So it assumes it is better to be silent, and uses a default no-op implementation (slf4j-nop-1.6.4.jar) that simply eats up any log we send to it.

If we want to have a basic feedback, so that we could see if anything is working as expected, we can use a simple logger provided by SLF4J. We just have to add the library slf4j-simple-1.6.4.jar to our application Java Build Path. Now we should get from our application a better output:
0 [main] INFO HelloWorld - Hello World
That's it. SLF4J is up and running. As we have seen, it is very easy to switch to a different logging framework, just change a jar in the build path. Removing the SLF4J native simple logging framework and adding slf4j-jdk14-1.6.4.jar (native SLF4J plugin to the standard JDK logger, also known as JUL: java.util.logging) it is all we need to make our application ready to run and producing a JDK log:
06.12.2011 18:48:30 HelloWorld main
INFO: Hello World

No comments:

Post a Comment