2
我正在將一些Web應用程序從Log4j 1.12遷移到Log4j2。由於公司政策,我們的log4j.xml文件位置被配置爲應用程序服務器中的URL,應用程序必須使用JNDI獲取它們。我們實現了一個ServletContextListener
,使我們能夠初始化log4j的infraestructure這樣:如何從JNDI加載log4j2配置文件
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提供了使用Log4jServletContainerInitializer
初始化庫的lo4j2-web.jar模塊。最後調用Log4jWebInitializerImpl.getConfigURI()
,負責獲取配置文件的URI。
是否有任何方法來自定義Log4jWebInitializerImpl的行爲,使其從JNDI名稱解析XML文件?
喜史蒂夫,你的解決方案是確定的。不過,我有點擔心這裏說的是什麼https://logging.apache.org/log4j/2.x/manual/webapp.html Log4j資源無法通過常規方式清理。當Web應用程序部署並「關閉」時,Log4j必須「啓動」,並且在Web應用程序未啓用時「關閉」您是否確實知道您提出的建議會在Web環境中正確清理所有內容? – codependent 2015-04-06 08:26:22
上面的解決方案不使用log4j2 webapp軟件包。 'Configurator.shutdown(loggerContext)應該清理它自己的初始資源。 – 2015-04-07 01:10:32