如何以编程方式更改log4j2中的AppenderRef级别?

时间:2017-03-08 21:37:56

标签: java log4j2

如何更改log4j2中的AppenderRef Level

有一个stackoverflow question(有答案),这是非编程解决的。我想要相同但以编程方式。 AppenderRef中只有一个get方法可以检索Level,但没有方法可以设置它。

那么,有没有办法以编程方式在log4j2中设置Level中的AppenderRef

1 个答案:

答案 0 :(得分:5)

你必须通过删除appender然后再添加所需的级别来完成它。

示例log4j2.xml:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <Appenders>
        <File name="logFile" fileName="log.txt" immediateFlush="false"
            append="true">
            <PatternLayout
                pattern="%d{yyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
        </File>
    </Appenders>

    <Loggers>
        <Root level="trace">
            <AppenderRef ref="logFile" level="info" />
        </Root>
    </Loggers>
</Configuration>

示例代码:

package example;

import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.LoggerConfig;

public class Log4j2SetAppenderRefLvlMain {
    private static final Logger log = LogManager.getLogger();

    public static void main(String[] args) {
        final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
        final Configuration config = ctx.getConfiguration();


        log.info("Before altering the appender!");

        LoggerConfig rootLoggerConfig = config.getLoggers().get("");
        rootLoggerConfig.removeAppender("logFile");
        rootLoggerConfig.addAppender(config.getAppender("logFile"), Level.WARN, null);
        ctx.updateLoggers();

        log.info("After altering the appender!");
        log.warn("After altering the appender!");
    }

}

输出:

2017-04-13 21:04:20.892 [main] INFO  example.Log4j2SetAppenderRefLvlMain - Before altering the appender!
2017-04-13 21:04:20.895 [main] WARN  example.Log4j2SetAppenderRefLvlMain - After altering the appender!

注意在将appender级别更改为WARN后,如何仅将WARN级别消息打印到日志中。这证明它有效。