Load Log4j2 configuration file programmatically

后端 未结 8 1518
-上瘾入骨i
-上瘾入骨i 2020-12-14 14:51

I want to load Log4j2 XML configuration file programmatically from my application.

Tried this:

ConfigurationSource source = new ConfigurationSource()         


        
8条回答
  •  清歌不尽
    2020-12-14 15:40

    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:

    
        com.example.LogContextListener
    
    
        isLog4jAutoInitializationDisabled
        true
    
    

    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.

提交回复
热议问题