Tuesday, October 11, 2011

How to use SLF4J with Log4j


Today I will show you how to use SLF4J with Log4j on a simple example.

Let's start with Log4j. First, download log4j library and add log4j-1.2.16.jar into classpath.

Create log4j.properties file, which will contain log4j configuration and put it into project. It may look like this:

log4j.rootLogger=DEBUG, A1
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=[%c{1}][%p]: %m%n


Have a look at a simple program which prints 'Hello, World!!”:

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

public class HelloWorld {

    private final Logger logger = Logger.getLogger(getClass());

    public static void main(String[] args) {
        PropertyConfigurator.configure("log4j.properties");
        new HelloWorld().logger.info(“Hello, World!!”);
    }
}

The output is: [HelloWorld][INFO]: Hello, World!!


Now let's try to use SLF4J in above program. Download slf4j library and add:

- slf4j-api-1.6.1.jar
- slf4j-log4j12-1.6.1.jar 

into classpath, where log4j-1.2.16.jar has already been added. The program will change a little:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.log4j.PropertyConfigurator;

public class HelloWorld {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    public static void main(String[] args) {
        PropertyConfigurator.configure("log4j.properties");
        new HelloWorld().logger.info(“Hello, World!!”);
    }
}

The bold text displays changes.

The output is the same: [HelloWorld][INFO]: Hello, World!!

Using such abstraction like SLF4J allows users quickly and easily change a logging system used in their projects to the desired.

SLF4J FAQ: http://www.slf4j.org/faq.html#logging_performance

No comments:

Post a Comment