MemeStorm

Exploring the Spring Framework and Application Development

Refreshable log4j configuration files

Posted in All by Jon on the February 4th, 2006

Sometimes its nice to have a log4j configuration that you can change, particularly during development: when you find an error, you can change the error level without redeploying.

How to do it

Modify your web.xml to introduce a listener together with a few parameters like so:

<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/WEB-INF/log4j.properties</param-value>
</context-param>
<context-param>
<param-name>log4jRefreshInterval</param-name>
<param-value>1000</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>

Now, put your log4j.properties file under WEB-INF/, not under WEB-INF/classes. That’s it. Now when you modify the properties file, it will automatically be picked up (well, at 1000 millisecond intervals) and reloaded.

Notes

  • You may not want to do this in a production server. An extra thread is spawned to do this work, which hangs around until the VM dies. I don’t think is serious, but your mileage may vary.
  • You’ll need to use an exploded WAR.

How it works

The listener is a standard ServletContextListener, which eventually delegates to org.apache.log4j.PropertyConfigurator#configureAndWatch, which is where the action happens. So Spring makes it easy to set it all up, but the actual polling etc. takes place in log4j.

Advanced

By default you can use the system property ${webapp.root} within your log4j property file (for example, to point to a log file location relative to the web application root). This is set in the listener.


Print This Post Print This Post « Previous Page