Thursday, April 12, 2007

Loading Log4j Properties in Webapps on Tomcat

Log4j is a well established and widely used logging framework for the Java platform. At the core of Log4j lies a configuration file that allows to finely configure the logging requirements for an application. Currently, the configuration file is either a XML or Java properties file. The documentation states that this configuration file should be present in the classpath of the application. This works fine for most situations however causes problems within webapps on Tomcat.

The Log4j FAQ describes this due the way in which JavaEE and Servlet containers utilize Java's class loading system.

The problem can be overcome by using Log4j's PropertyConfigurator. PropertyConfigurator enables to statically load the configuration from an external file. Using the configure(String configFilename) method we can manually specify the path to the properties file within the webapp. We can tie this code into a ServletContextListener's contextInitialized(ServletContextEvent sce) event to force the properties file to be loaded at webapp startup.
Our ServletContextListener implementation is listed below:

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.log4j.PropertyConfigurator;

public class ServletContextListenerImpl implements ServletContextListener {
    public void contextDestroyed(ServletContextEvent sce) {

    }

    public void contextInitialized(ServletContextEvent sce) {
        String path="WEB-INF/classes/log4j.properties";
        ServletContext context = sce.getServletContext();
        PropertyConfigurator.configure(context.getRealPath(path));
    }
}

Our Log4j properties file should now be successfully loaded when the webapp is initialized.

No comments: