I want to load Log4j2 XML configuration file programmatically from my application.
Tried this:
ConfigurationSource source = new ConfigurationSource()
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 from Log4jServletContextListener, set it up in your web.xml and disable auto initialization:
<listener>
<listener-class>com.example.LogContextListener</listener-class>
</listener>
<context-param>
<param-name>isLog4jAutoInitializationDisabled</param-name>
<param-value>true</param-value>
</context-param>
In your custom LogContextListener overwrite contextInitialized and set the config location
public void contextInitialized(ServletContextEvent event) {
/* Some logic to calculate where the config file is saved. For
* example you can read an environment variable.
*/
String pathToConfigFile = ... + "/log4j2.xml";
Configurator.initialize(null, pathToConfigFile);
super.contextInitialized(event);
}
The 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.
Considering - https://logging.apache.org/log4j/2.x/log4j-core/apidocs/org/apache/logging/log4j/core/config/Configurator.html
Configurator.initialize(null, "classpath:conf/logger.xml");
or
Configurator.initialize(null, "/full_path/conf/logger.xml");
Be aware and does not use both at the same time.