Configuring Apache Log4j and Commons Logging

There are several good guides on configuring Log4j and Commons Logging, so this post will be nothing new. Hopefully it will help someone using IntelliJ IDEA in Linux quickly get past any initial setup issues they might have getting both to work in sync.

The back story on my using Apache Commons Logging with Log4j is that I added JCS to my Java app. JCS is the Apache Commons Java Caching System. I’ll blog on JCS later, but the point is that JCS requires Apache Commons Logging so I added it. The Commons Logging Component is an ultra-thin bridge between different logging implementations, so I quickly realized I needed more control of how JCS was logging its processes and needed a full logging implementation. I went with Log4j since it’s probably the most popular Java logging library out there.

First the project structure in IntelliJ IDEA. At bottom you see the Apache Commons Logging and Log4j Libraries. Highighted in yellow in the project’s classpath are the two .properties files needed for the two logging libraries. Notice their location in the classpath root.

The Properties Files

Here is the one-line contents of the commons-logging.properties file used by Apache Commons Logger with the singular task of specifying which Logging implementation it will use.

org.apache.commons.logging.Log=org.apache.commons.logging.impl.Log4jLogger

The log4j.properties file gives us the ability to configure how much info log4j will output to the console and/or to a file. Here is a sample of our log4j.properties file, which writes to the standard output console.

log4j.rootLogger=DEBUG, stdout

# stdout is set to be a ConsoleAppender.
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%-4r [%t] %-5p %c %x – %m%n

Here’s the excellent Apache guide on Log4j for more detail. Dated, but still valuable.

Using Logging

Here’s a quick sample of using the Log4j Library and its standard output.

As a footnote, keep in mind that using the configuration described in the post will also enable you to control the output of other libraries which use Apache Commons Logging like the Java Caching System.