How to Log with SLF4J and log4j

1) Create the Slf4jSample.java file:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public final class Slf4jSample {

  public static void main(final String[] args) {
    final Logger logger = LoggerFactory.getLogger(Slf4jSample.class);

    logger.info("Hello World!");
  }

}

2) Create the log4j.properties file:

log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout

log4j.logger.Slf4jSample=INFO, A1

3) Compile the Slf4jSample.java file.

4) Add the slf4j-log4j.jar file to the class path.

5) Launch the Slf4jSample class.

2 thoughts on “How to Log with SLF4J and log4j

  1. How do you make this work if you have existing code that has references to org.apache.log4j.Logger? I really don’t want to change all of my classes so that they import org.slf4j.Logger and org.slf4j.LoggerFactory.

    How do I configure log4j if this overrides it? I want the applications logging statements to be written to a file called myapp.log. As for the Jetty container’s logging, it can go to /dev/null for all I care, I just want to have my application-specific logging back.

    How do I get both implementations to exist side by side? I’m using Jetty 6 which is dependent on slf4j, but my application that I’m serving in Jetty 6 uses pure log4j, at least it did before I had to deploy slf4 jar files to my jetty/lib directory.

    Any help you can provide will be greatly appreciated.

    Thanks for the help,
    James

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s