我正在将一些Web应用程序从Log4j 1.12迁移到Log4j2。由于公司策略,我们的log4j.xml文件位置在应用程序服务器中配置为URL,应用程序必须使用JNDI获取它们。我们实现了一个ServletContextListener
,允许我们以这样的方式初始化log4j基础结构:
public void contextInitialized(ServletContextEvent servletContextEvent) {
...
urlLogConfig = (URL) context.lookup("java:comp/env/"+logLocation);
...
//urlLogConfig -> file:///somepath/log4j.xml
DOMConfigurator.configureAndWatch(urlLogConfig.getPath());
}
public void contextDestroyed(ServletContextEvent servletContextEvent) {
ServletContext servletContext = servletContextEvent.getServletContext();
servletContext.log("Log4jConfigurationListener - Shutting down log4j");
LogManager.shutdown();
}
但是,随着log4j2 API的更改,无法再使用它。 Log4j2提供了lo4j2-web.jar模块,该模块使用Log4jServletContainerInitializer
来初始化库。这最终会调用Log4jWebInitializerImpl.getConfigURI()
,负责获取配置文件的URI。
有没有办法自定义Log4jWebInitializerImpl的行为以使其从JNDI名称解析xml文件?
答案 0 :(得分:0)
如下:
...
import org.apache.logging.log4j.core.config.Configurator;
...
private LoggerContext loggerContext;
public void contextInitialized(ServletContextEvent servletContextEvent) {
...
urlLogConfig = (URL) context.lookup("java:comp/env/"+logLocation);
...
//urlLogConfig -> file:///somepath/log4j.xml
ServletContext servletContext = servletContextEvent.getServletContext();
String contextName = servletContext.getServletContextName();
Classloader classloader = this.getClass().getClassloader();
loggerContext = Configurator.initialize(contextName, classloader, urlLogConfig.toURI());
}
public void contextDestroyed(ServletContextEvent servletContextEvent) {
ServletContext servletContext = servletContextEvent.getServletContext();
servletContext.log("Log4jConfigurationListener - Shutting down log4j");
if (loggerContext != null)
Configurator.shutdown(loggerContext);
}