Load Log4j2 configuration file programmatically

后端 未结 8 1502
-上瘾入骨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:

    <listener>
        <listener-class>com.example.LogContextListener</listener-class>
    </listener>
    <context-param>
        <param-name>isLog4jAutoInitializationDisabled</param-name>
        <param-value>true</param-value>
    </context-param>
    

    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.

    0 讨论(0)
  • 2020-12-14 15:40

    Considering - https://logging.apache.org/log4j/2.x/log4j-core/apidocs/org/apache/logging/log4j/core/config/Configurator.html

    Configurator.initialize(null, "classpath:conf/logger.xml");
    or
    Configurator.initialize(null, "/full_path/conf/logger.xml");
    

    Be aware and does not use both at the same time.

    0 讨论(0)
提交回复
热议问题