Friday, January 22, 2010

A poor man's conditional logging configuration

It is often desirable to keep the same logging configuration file during development and production environments. (I use logback as my logging framework.)

Ideally, one would check whether the application was running on the production environment and enable parts of the configuration file accordingly. Unfortunately, logback does not support conditional (if-then-else) configuration statements.

However, it supports default substitution for variables which can be used to solve a variety of problems. For example, I would like to have a file FileAppender which logs under the logs/ folder of my Tomcat server. Here is the relevant configuration snippet:
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
<File>${catalina.home}/logs/myApp.log</File>
...
</appender>
As long as the catalina.home property is defined, the above works as expected. However, during development I use the jetty server which does not define the said property. I can still instruct logback to fallback to a reasonable value by specifying a default substitution value for ${catalina.home}. The current directory, symbolized by a dot, i.e. '.', is quite a reasonable default. The configuration snipped is thus modified as:
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
<File>${catalina.home:-.}/logs/myApp.log</File>
...
</appender>
This will have the log file of my application write to
./logs/myApp.log within my development environment. Easy as pie.

1 Comments:

Anonymous Anonymous said...

This is a really good tip. Somehow I've missed the relevant section in the manual while I've been reading it. Thanks Ceki!

5:06 PM  

Post a Comment

<< Home