本文介绍了如何以编程方式更改log4j2中的AppenderRef级别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在log4j2中更改AppenderRef Level?

How can I change the AppenderRef Level in log4j2?

有一个 stackoverflow问题(带有答案),该问题可以通过非编程方式解决.我想要相同的内容,但以编程方式代替. AppenderRef中只有一个get方法可以检索Level,而没有方法可以对其进行设置.

There is a stackoverflow question (with answer) where this was solved non-programmatically. I want the same but programmatically instead. There is only a get method in AppenderRef to retrieve the Level but no method to set it.

那么,有什么方法可以通过编程方式在log4j2的AppenderRef中设置Level吗?

So, is there any way to set the Level in the AppenderRef in log4j2 programmatically?

推荐答案

您必须先删除附加器,然后再将其添加到所需级别,以完成此操作.

You have to do it by removing the appender and then adding it again with the desired level.

示例log4j2.xml:

Example 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!

请注意,在将附加程序级别更改为WARN之后,如何仅将WARN级别的消息打印到日志中.这证明它有效.

Notice how only the WARN level message is printed to the log after we changed the appender level to WARN. This proves that it works.

这篇关于如何以编程方式更改log4j2中的AppenderRef级别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 04:30