本文介绍了如何在运行时使用log4j2 api将loglevel从INFO设置为ERROR?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

logger.setLevel()方法在log4j2 API中不可用。那么如何在运行时设置日志级别。

logger.setLevel() method is not available in log4j2 API. So how to set log level at run time.

推荐答案

我不确定这是不是最好的方法,但是你设置了 org.apache.logging.log4j.core.config.LoggerConfig 上的级别,您可以通过LogManager从LoggerContext获取该级别。

I'm not sure if this is the best way, but you set the level on org.apache.logging.log4j.core.config.LoggerConfig which you can get from the LoggerContext via the LogManager.

设置后,您可以使用新配置更新记录器。

Once set, you can update the loggers with the new configuration.

作为示例:

public static void main(String[] args) {
    Logger log = LogManager.getLogger(LogManager.ROOT_LOGGER_NAME);
    log.error("An error");
    log.debug("A debug");

    LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    Configuration conf = ctx.getConfiguration();
    conf.getLoggerConfig(LogManager.ROOT_LOGGER_NAME).setLevel(Level.DEBUG);
    ctx.updateLoggers(conf);

    log.error("Another error");
    log.debug("Another debug");
}

收益率:

14:03:41.346 [main] ERROR  - An error
14:03:41.348 [main] ERROR  - Another error
14:03:41.348 [main] DEBUG  - Another debug

这篇关于如何在运行时使用log4j2 api将loglevel从INFO设置为ERROR?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 04:29