PropertyConfigurator in log4j2

隐身守侯 提交于 2019-12-21 12:28:53

问题


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 take care of what the PropertyConfigurator did before?


回答1:


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



回答2:


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.




回答3:


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

    }


来源:https://stackoverflow.com/questions/32043770/propertyconfigurator-in-log4j2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!