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.