PropertyConfigurator in log4j2

前端 未结 3 1184
温柔的废话
温柔的废话 2021-02-13 14:28

I\'m migrating log4j 1.2.8 to log4j 2.3. Everything works fine, beside that I\'m not finding any any alternative for the PropertyConfigurator.

Is there another class to

相关标签:
3条回答
  • 2021-02-13 14:56

    Maybe this can help you?

    How do I reconfigure log4j2 in code with a specific configuration file? See the below example. Be aware that this LoggerContext class is not part of the public API so your code may break with any minor release.

    // import org.apache.logging.log4j.core.LoggerContext;
    
    LoggerContext context = (org.apache.logging.log4j.core.LoggerContext) LogManager.getContext(false);
    File file = new File("path/to/a/different/log4j2.xml");
    
    
    // this will force a reconfiguration
    context.setConfigLocation(file.toURI());**
    
    0 讨论(0)
  • 2021-02-13 15:07

    Log4j 2 currently supports configuration with XML, JSON or YAML. While properties files may also be supported in the near future the syntax will certainly be different from Log4j 1.

    0 讨论(0)
  • 2021-02-13 15:16

    Here my solution to the same problem:

    web.xml

    <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    
        <context-param>
            <param-name>isLog4jContextSelectorNamed</param-name>
            <param-value>false</param-value>
        </context-param>
    
        <!-- ... and so on -->
    
    </web-app>
    

    LoggerHelper.java

        import java.io.File;
        import org.apache.logging.log4j.LogManager;
        import org.apache.logging.log4j.core.LoggerContext;
        import org.slf4j.Logger;
        import org.slf4j.LoggerFactory;
    
        public final class LoggerHelper {
    
          public static Logger INSTANCE;
    
          public static void initialize() {    
            String        fileName = "<PATH>/log4j.xml";
            LoggerContext context  = (LoggerContext)LogManager.getContext(false);
    
            context.setConfigLocation(new File(fileName).toURI());
            INSTANCE = LoggerFactory.getLogger(LoggerHelper.class);
    
            String logMessage = String.format("Initialized (%s).", fileName);
            System.out.println(logMessage);
            INSTANCE.info(logMessage);
          }
    
        }
    
    0 讨论(0)
提交回复
热议问题