Different Log4j configs for dev and prod

9/7/2014

It is often beneficial to use a different Log4j configuration in production than during development. For example, because of the amount of log output generated in production, you might configure daily rolling log files, which are compressed when they are rolled over, with this configuration (in the good old property file format):

log4j.rootLogger=INFO, daily

log4j.appender.daily=org.apache.log4j.rolling.RollingFileAppender
log4j.appender.daily.File=/srv/myproject/logs/myproject.log
log4j.appender.daily.RollingPolicy=org.apache.log4j.rolling.TimeBasedRollingPolicy
log4j.appender.daily.RollingPolicy.ActiveFileName =/srv/myproject/logs/myproject.log
log4j.appender.daily.RollingPolicy.FileNamePattern=/srv/myproject/logs/myproject.log.%d{yyyyMMdd}.gz
log4j.appender.daily.layout = org.apache.log4j.PatternLayout
log4j.appender.daily.layout.ConversionPattern=%d [%t] %-5p %c - %m%n

log4j.logger.com.myproject=INFO

During development, however, it usually makes sense to direct any log output to stdout, so they show up in the console of the IDE, possilby including debug output. There is little use for permanently stored logs, so it makes sense to skip the rolling log files. The configuration could look like this:

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 [%t] %-5p %c - %m%n

log4j.logger.com.myproject=DEBUG

Using the proper configuration depending on whether you are in development or not can be accomplished by putting the first file into your resource folder as log4j.properties (assuming Maven standard structure, src/main/resources/log4j.properties, and the second in the same place, but under a different filename, e.g. log4j-dev.properties.

This results in the production log4j.properties being used, except when you add a command line property instructing Log4j to look elsewhere for the configuration, like this: -Dlog4j.configuration=log4j-dev.properties.

If you use a Maven plugin to run your app in development, like the ubiquitous Jetty Maven plugin, this can be completely automated by adding a bit of configuration to your POM:

<plugin>
    <groupId>org.mortbay.jetty</groupId>
    <artifactId>jetty-maven-plugin</artifactId>
    <version>8.1.14.v20131031</version>
    <configuration>
        <systemProperties>
            <systemProperty>
                <name>log4j.configuration</name>
                <value>log4j-dev.properties</value>
            </systemProperty>
        </systemProperties>
    </configuration>
</plugin>

Now we have a console-only logging configuration for development, and a rolling file configuration for production, keeping the main log of the application server nice and tidy and the server storage from overflowing from a gigantic main log file.

Comments