Wednesday, March 31, 2010

A middle-class man's conditional logging configuration

In an earlier post I described how one adapt a single configuration file for use in development as well as production environments. At those prehistoric times, that is January 2010, logback did not support conditional (if-then-else) configuration statements. So we made use of a default substitution value to do the the trick.

However, as of version 0.9.20 (to be released early April), logback supports conditional configuration statements. Thus, we can write:
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
<if condition='!isNull("catalina.home")'>
<then>
<File>${catalina.home}/logs/myApp.log</File>
</then>
<else>
<File>./logs/myApp.log</File>
</else>
</if>
...
</appender>
Thus, if the "catalina.home" system property is defined (non null), then the log file will be written to ${catalina.home}/logs/myApp.log, otherwise, we are in the development environment and the logs should be written to ./logs/myApp.log.

In this particular case, the if-then-else approach is more verbose than default variable substitution, i.e. simply writing ${catalina.home:-.}. However, it goes without saying that conditional configuration brings much needed flexibility to the table. Keep in mind that given the verbosity of XML, one could gradually end up with a configuration file containing many logical branches rendering the file ungrokable. In case you ask, nested if-then-else statements are supported. So please use conditionals with moderation so that complexity does not creep into your configuration files.

4 comments:

Juha said...

This is great news!

Btw, is 0.9.20 (and particularly this feature) going to be supported in JDK 1.3?

Juha said...

Whoops, I just realized that I mixed slf4j and logback ;)

So, presumably this is going to required JDK1.5?

Ceki said...

Logback requires JDK 1.5 already, this feature is no different.

Anonymous said...

Thanks! Will this also work with RollingFileFileAppenders? In other words, I want a conditional around a fileNamePattern. How will this work?