简体   繁体   English

无法在运行时更改日志级别(log4j2)

[英]Can't change log level at runtime (log4j2)

I'm using log4j2 and trying to change the log level at runtime. 我正在使用log4j2并尝试在运行时更改日志级别。 I've seen other similar posts here and here but still can't get it to work 我在这里这里看到过其他类似的帖子,但仍然无法正常工作

Here is my code: 这是我的代码:

public static void main(String[] args)
{
        Logger log = LogManager.getLogger(LogManager.getLogger(Main.class.getName()).getName());

        LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
        Configuration config = ctx.getConfiguration();
        LoggerConfig loggerConfig = config.getLoggerConfig(LogManager.getLogger(Main.class.getName()).getName()); 

        loggerConfig.setLevel(Level.DEBUG);
        ctx.updateLoggers(config);

        log.trace("trace");
        log.debug("debug");
        log.info("info");

        loggerConfig.setLevel(Level.TRACE);
        ctx.updateLoggers(config);

        log.trace("trace");
        log.debug("debug");
        log.info("info");
    }
}

The log level is set to INFO in the config file. 在配置文件中,日志级别设置为INFO The console output is: 控制台输出为:

info
info

UPDATE 更新

I've realised that the log level is successfully changing in the log file but not in the console. 我已经意识到,日志级别在日志文件中成功更改,但在控制台中未更改。

Here is a snippet from the config file in case it helps: 如果有帮助,请参考以下配置文件片段:

<Configuration status="info">
<Loggers>
    <Root level="debug">
        <AppenderRef ref="Console" level="INFO" />
        <AppenderRef ref="LogFile" />
    </Root>
</Loggers>

The attribute level on an appender is a filter for the appender : all log with lower levels are not considered by this appender, but it is not the level of the logger 附加器上的属性级别是该附加器的过滤器:此附加器不考虑所有较低级别的日志,但它不是记录器的级别

Remove the filter on console appender and keep only the level on the logger should work fine 删除控制台附加程序上的过滤器,仅保持记录器上的级别正常运行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM