Wednesday, 26 September 2012

Automatically reload log4j configuration

I have been using Log4j for a while and IMO it is one of the greatest libraries to trace your application behaviour. Yet, I used to have this recurring problem, when I wanted to change logger configuration, my application was running and I couldn't restart it to reload loggers. But then one day I have found a solution, which turned out to be very simple and provided out of the box with the library.

Here is an example of a simple class, which can be used at the very beginning of any Java application to setup Log4j configuration. Configuration may be located wherever we want and it doesn't need to be named as default "log4j.properties".

public abstract class LoggerSetup {

    private static Logger logger;
    // Period in [ms] between checking for logger properties change
    private static final long CHECK_PERIOD = 20000;

    /**
     * Set logger file properties
     * @param filename - path to log4j properties file
     */
    public static void setLogger(String filename) {
        File f = new File(filename);
        if (f.exists()) {
            PropertyConfigurator.configureAndWatch(filename, 20000);
        }
        logger = Logger.getLogger(LoggerSetup.class);
        logger.debug("Setup logger");
    }

}

As we can see, every 20 seconds, Log4j check whether properties file has changed. If so, it will reload logger setup. It means that during application execution you may change logger levels, appenders, formats etc. without the need
for application restart.

0 comments:

Post a Comment