Log4J 2.8.1使用PropertiesConfigurationBuilder从字符串加载属性

时间:2017-04-24 14:19:56

标签: log4j2

我正在寻找一种方法来准备配置并从硬编码属性字符串初始化记录器上下文;不是来自属性文件。以下是似乎正在运行的代码;它根据日志级别记录我期望的行。然而,我无法弄清楚的事情很少。我已经在代码本身中将它们作为内联问题提出来了;欣赏相同的投入。

提前致谢。

-WinCPP

public static void main(String[] args) {

        Properties properties = new Properties();

        properties.setProperty("status", "TRACE");

        properties.setProperty("appenders", "CONSOLE");

        properties.setProperty("appender.CONSOLE.name", "ConsoleAppender");
        properties.setProperty("appender.CONSOLE.type", "Console");
        properties.setProperty("appender.CONSOLE.layout.type", "PatternLayout");
        properties.setProperty("appender.CONSOLE.layout.pattern", "%r [%t] %p %c %notEmpty{%x }- %m%n");

        properties.setProperty("rootLogger.level", "ALL");
        properties.setProperty("rootLogger.appenderRefs", "theConsoleRef");
        properties.setProperty("rootLogger.appenderRef.theConsoleRef.ref", "ConsoleAppender");

        PropertiesConfigurationBuilder pcb = new PropertiesConfigurationBuilder();

        // Q1: Is it correct to call setConfigurationSource with 'null'?
        pcb.setConfigurationSource(null).setRootProperties(properties);
        PropertiesConfiguration config = pcb.build();
        Configurator.initialize(config);

        /* Q2: How do I do the setStatusLevel e.g. the 2nd line in commented
           code below, when I am using property route to initialize the logger? Even
           if I set rootLogger.level to 'ALL' (above code), I still do not see
           Log4j 2.x internal messages. I can see those if I use ConfigurationBuilder, though.

        ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory.newConfigurationBuilder();
        builder.setStatusLevel(Level.TRACE);

        EDIT: Add "properties.setProperty("status", "TRACE");"

        */

        Logger logger = LogManager.getRootLogger();

        logger.error("This is error message");
        logger.info("This is info message");
        logger.trace("This is trace message");
}

0 个答案:

没有答案