How to add log4j logging framework to your java project

1. Add the log4j jars

If you are using maven, add the following dependency


    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.16</version>
    </dependency>

At the time of writing, 1.2.16 was the latest version. You should change it to the latest stable version.

2. Add a log4j.properties configuration file

Add this to the top level classpath. The following will log INFO and higher messages to console / stdout.

log4j.rootLogger=INFO, stdout

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

log4j.appender.stdout.layout.ConversionPattern=%d %p %t %C - %m%n

You can start tweaking the pattern layout to suit your needs.

3. Add to spring webapp

If your project is a Spring webapp, you can add the following listener to web.xml.


  <listener>
    <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
  </listener>

If you are using org.springframework.web.context.ContextLoaderListener, add the Log4jConfigListener above it.

4. Specifying the log4j.properties file

Instead of using the default log4j.properties file, you can specify its location as a URL using the system property "log4j.configuration". e.g.


-Dlog4j.configuration=file:///c:/work/webapp_log4j.properties