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

如何更改log4j2中的AppenderRef级别?

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

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

解决方法:

您必须通过删除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级别消息打印到日志中.这证明它有效.

上一篇:Mybatis-第N篇配置log4j1、log4j2打印执行的sql语句


下一篇:java – Log4j2找不到Sprint Boot的日志记录实现