skiphoppy skiphoppy - 4 months ago 15
Java Question

How can you combine log4j default initialization with configureAndWatch()?

Some Log4j Configurators have a

configureAndWatch()
method, that starts a Thread to watch the file used for configuration (
XML
file or
properties
file) and trigger a reconfigure if the file changes.

However, if you rely on the
Log4j
default initialization procedure, you never get a chance to call
configureAndWatch()
. You don't even know the file that was used to configure with (it might not even be a file.)

Is there a good way to get
configureAndWatch()
style behavior, allowing changing of the log configuration on the fly, while still using the default initialization procedure? I am assuming that your configuration URL ultimately resolves to a file that can be watched, as a URL on another server would probably not be something you would want to pull every 60 seconds.

(I see that the
configureAndWatch()
method is not safe in a Java EE environment because of the separate thread, and I see that some app servers have their own mechanism for watching the
log4j
configuration file, but the program I am working on at the moment is not running in Java EE .)

Answer

I've scrapped everything in the answer before and started over now that I better understand what you want.

The following paragraph describes the real sequence that log4j uses to determine what the log4j config file name is. This code tries to follow those rules.

http://logging.apache.org/log4j/1.2/manual.html#defaultInit

It determines what log4j configuration file to use and then sets up the PropertyConfigurator using the file it found. This will only work if the file is located on the file system. It will not work if the file is inside a jar or at a remote HTTP URL.

    String prop = System.getProperty("log4j.configuration");
    if (prop == null) prop = "log4j.properties";
    URL log4jConfig = Loader.getResource(prop);
    if (log4jConfig.getProtocol().equalsIgnoreCase("file")) {
        PropertyConfigurator.configureAndWatch(log4jConfig.getFile().substring(1), 10000);
    }
    else {
        // cannot monitor if file changed because URL is not a file
    }
Comments