skiphoppy skiphoppy - 3 months ago 13x
Java Question

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

Some Log4j Configurators have a

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

However, if you rely on the
default initialization procedure, you never get a chance to call
. 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
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
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
configuration file, but the program I am working on at the moment is not running in Java EE .)


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.

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 = "";
    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