log4j-slf4j-impl / log4j v2 - setting custom log4j.xml destination

At runtime in my application, I'd like to specify the location of the log4j configuration file dynamically.

This is so that rather than this being a resource bundled in the JAR, it's an actual file on disk that can be edited if there is a problem to increase logging levels.

When using log4j v1.2, you can use DOMConfigurator.configure(URL) to do this.

But now I've upgraded to log4j-slf4j-impl / log4j v2, this method no longer exists.

I can see how to configure log4j directly, but I want to use the existing slf4j compatible XML file without having to change it.

Can anyone help?


  • Log4j 2.x uses a ConfigurationFactory to parse a configuration file. There is a factory for each format and a default factory. The default factory tries to guess the correct format from the file extension of the file: unfortunately both the old Log4j 1.2 and the new Log4j 2.x formats have an .xml extension, so additional configuration is needed.

    In order to parse the Log4j 1.2 XML format you need to add the log4j-1.2.api artifact and replace the default factory:

    import org.apache.log4j.xml.XmlConfigurationFactory;
    import org.apache.logging.log4j.core.config.ConfigurationFactory;
    ConfigurationFactory.setConfigurationFactory(new XmlConfigurationFactory());

    After this is set a simple:

    Configurator.reconfigure(new URI("URI of your file"));

    will apply your configuration to the appropriate LoggerContext.