I want to load Log4j2 XML configuration file programmatically from my application.
Tried this:
ConfigurationSource source = new ConfigurationSource();
source.setLocation(logConfigurationFile);
Configurator.initialize(null, source);
and this:
ConfigurationSource source = new ConfigurationSource();
source.setLocation(logConfigurationFile);
ConfigurationFactory factory = (ConfigurationFactory) XMLConfigurationFactory.getInstance().getConfiguration(source);
ConfigurationFactory.setConfigurationFactory(factory);
But nothing works yet.
If you are using a Servlet 3.0 Web Application you can use the Log4jServletContextListener and do the following:
Write a custom
LogContextListener
which extends fromLog4jServletContextListener
, set it up in yourweb.xml
and disable auto initialization:In your custom
LogContextListener
overwritecontextInitialized
and set the config locationThe advantage over configuring the location directly in the
web.xml
is that you can compute the path based on some additional information and access the log4j2.xml even if its outside of your classpath.If you have a single main entry point, this code snippet might save you some trouble. The set property call must fire before any loggers are created. This approach works with files on the classpath.
Found the answer myself. Someone might find it useful.
For the newest version of log4j, here is what should work for loading an external
log4j2.xml
:Below worked for me, Log4j2 with SLF4J wrapper:
Solution 1:
Solution 2:
Need
toURI()
to follow File URI Scheme format, else it throwsMalformedURLException
.Sources: