While LogJj will self-initialize if it finds a file called log4j.properties or log4j.xml in the classpath, it will only read the file once at application startup.
I’ve often had the need to be able to change the logging level in a long-running application, such as a web application, so that I can switch logging to debug level as needed without requiring a restart.
Log4J provides configurator classes that will monitor a configuration file for changes and reload the configuration when the file changes. The implementation appears to spawn a background thread that sleeps for a specified interval, then wakes up and checks the configuration file for changes.
You can use this method by calling PropertyConfigurator.contigureAndWatch() or DOMConfigurator.configureAndWatch() methods. The challenge is that you should only call these methods once when your application starts up as each call to the above methods will result in a new thread to monitor the configuration file.
In many applications, it is a simple matter to call these methods only once. The question often comes up as to where to make the call to a ConfigureAndWatch method from within a web application. A collegue of mine once accidentally put this call in the main execution path of a high-traffic web application and brought the site down as the web application container couldn’t manage all the resulting threads.
I’ve seen several methods of ensuring that the ConfigureAndWatch method is only called once from within a web application, but I think the cleanest and simplest is to create a Context Listener to initialize Log4J.
The following example creates a ServletContextListener which will initialize Log4J when the application is loaded by the container, and will shut down logging for the application when it is unloaded. Continue reading Initialize Log4J in a web application with a ServletContextListener