Thursday, May 26, 2005

Tweaking log4j

Despite the inclusion of logging APIs into the JDK since 1.4, I still continue to use log4j for my logging needs. Generally I'll also use the commons logging API on top of log4j so that if I should ever change my mind and want to use the "built-in" logging facilities it will be easy.

My recent foray into production deployment highlighted one of the problems with my standard configuation. I have the typical log4j.properties file in the root of my source directory, and log4j is quite happy to find it there. The problem is that it eventually gets buried inside a JAR (Java ARchive) which is inside a WAR (Web Archive) when I build my application and therefore it's not very easy to change the logging parameters once my application is deployed. Specifically, the location of the generated log files is now essentially hard coded, which sucks for deployment.

Fortunately there's a way out of this. If you specify the location of a log4j.properties file in a Java system property called log4j.configuration, log4j will use that file instead of the one buried in your classpath. The only trick is to specify the location as a URL:

java -Dlog4j.configuration=file:/e:/log4j.properties ...

If you're using a Windows Service for starting an instance of Tomcat you can add a system property to the registry value found in HKEY_LOCAL_MACHINE/SOFTWARE/Apache Software Foundation/Procrun 2.0/Node1/Paramaeters/Java/Options where Node1 in my example is the name of your instance of Tomcat.

Secondly, if you're want to define the location relative to a Tomcat installation you can use a dynamic location like this within your log4j.properties file:

log4j.rootLogger=error, R

log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=${catalina.base}/logs/MyApp.log
log4j.appender.R.MaxFileSize=200KB
log4j.appender.R.MaxBackupIndex=2
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=[%d{ISO8601}] %5p (%F:%L) - %m%n

Notice the ${catalina.base} expression. The nice thing about this in a clustered environment like I described yesterday is that you can use the same log4j.properties file for all the instances of Tomcat and can change the configuration for all of them all at once.

No comments: