我正在尝试为我们的webapp设置可配置的log4j配置路径,因此默认情况下此设置适用:
<context-param>
<param-name>log4jConfiguration</param-name>
<param-value>/WEB-INF/log4j2.xml</param-value>
</context-param>
如果,假设定义了一些环境变量,则使用log4j2-test.xml。我能以某种方式实现这一目标吗 我已经尝试定义自己的监听器,它将负责这一点,如下所示: web.xml内容:
<context-param>
<param-name>log4jConfiguration</param-name>
<param-value>/WEB-INF/log4j2.xml</param-value>
</context-param>
<context-param>
<param-name>isLog4jAutoInitializationDisabled</param-name>
<param-value>true</param-value>
</context-param>
<listener>
<listener-class>com.bla.blob.listener.Log4j2InitListener</listener-class>
</listener>
听众类:
public class Log4j2InitListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
ServletContext ctx = sce.getServletContext();
if (System.getProperty("log4j.configurationFile") != null) { //override what is defined in web.xml
ctx.setInitParameter("log4jConfiguration", System.getProperty("log4j.configurationFile"));
}
ctx.addListener(new Log4jServletContextListener());
final FilterRegistration.Dynamic filter = ctx.addFilter("log4jServletFilter",
new Log4jServletFilter());
if (filter != null) {
filter.setAsyncSupported(true);
filter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), false, "/*");
}
}
@Override
public void contextDestroyed(ServletContextEvent sce) { }
}
但是由于一些奇怪的原因,这个解决方案不是tomcat兼容的(虽然适用于jetty) -
java.lang.IllegalArgumentException: Once the first ServletContextListener has been called, no more ServletContextListeners may be added.
at org.apache.catalina.core.ApplicationContext.addListener(ApplicationContext.java:1386)
at org.apache.catalina.core.ApplicationContextFacade.addListener(ApplicationContextFacade.java:659)
此外,apache将所有与webapp相关的内容移出核心,使所有内容都变为私有,因此您不能再自行编写类(但http://logging.apache.org/log4j/2.x/manual/webapp.html仍建议您可以使用Log4jWebLifeCycle)。 任何帮助将不胜感激。