简体   繁体   中英

How to load log4j2 configuration file from JNDI

I am migrating some web applications from Log4j 1.12 to Log4j2. Due to company policies our log4j.xml file locations are configured as URLs in the application server and applications have to get them with JNDI. We implemented a ServletContextListener that allowed us to initialize the log4j infraestructure that way:

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();
}

However, with the log4j2 API changes this can no longer be used. Log4j2 provides the lo4j2-web.jar module which uses Log4jServletContainerInitializer to initialize the library. This ends up calling Log4jWebInitializerImpl.getConfigURI() , responsible of getting the URI of the config file.

Is there any way to customize Log4jWebInitializerImpl's behaviour to make it resolve the xml file from a JNDI name?

How about something like:

...
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);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM