java 如何在运行时使用 log4j2 api 将日志级别从 INFO 设置为 ERROR?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17186195/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 01:14:34  来源:igfitidea点击:

how to set loglevel from INFO to ERROR using log4j2 api at runtime?

javalog4j2

提问by Nandan

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

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

回答by amcintosh

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

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

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

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

As an example:

举个例子:

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");
}

Yields:

产量:

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

回答by dimo414

Credit to amcintosh, I wrapped their answerin a function:

感谢 amcintosh,我将他们的答案封装在一个函数中:

/** Override the logging level of a given logger, return the previous level */
public static Level setLevel(Logger log, Level level) {
  LoggerContext ctx = (LoggerContext)LogManager.getContext(false);
  Configuration conf = ctx.getConfiguration();
  LoggerConfig lconf = conf.getLoggerConfig(log.getName());
  Level oldLevel = lconf.getLevel();
  lconf.setLevel(level);
  ctx.updateLoggers(conf);
  return oldLevel;
}

Despite amoe's comment, this seems to be working correctly for me using Log4J 2.5.

尽管 amoe 发表了评论,但这似乎对我使用 Log4J 2.5 正常工作。

回答by SRG

On my side, i had to use this code in order to have this working fine (based on previous answers).

在我这边,我必须使用此代码才能正常工作(基于先前的答案)。

import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.config.AbstractConfiguration;

...

public static void changeLoggerLevel(final String module, final Level level) {
  String moduleRenamed = module.replaceAll("/", ".");
  LoggerContext ctx = (LoggerContext)LogManager.getContext(false);
  AbstractConfiguration configuration = (AbstractConfiguration) ctx
        .getConfiguration();
  if (configuration.getLogger(moduleRenamed) != null) {
    LoggerConfig loggerConfig = configuration.getLoggerConfig(moduleRenamed);
    loggerConfig.setLevel(level);
  } else {
    LoggerConfig loggerConfig = new LoggerConfig(moduleRenamed, level, true);
    configuration.addLogger(moduleRenamed, loggerConfig);
  }
  ctx.updateLoggers(configuration);
}

The problem was with the getLoggerConfig()call; if the module you are trying to give a new level is not yet registered, this method returns the root logger (or any intermediate sub path registered), and thus instead of altering the level for com.mycompanyyou will alter rootor comlevel. That's why you have to add a new LoggerConfigin case the module to alter is not yet registered.

问题出在getLoggerConfig()电话上;如果您尝试提供新级别的模块尚未注册,则此方法返回根记录器(或任何已注册的中间子路径),因此不会为com.mycompany您更改级别,而是更改rootcom级别。这就是为什么您必须添加一个新LoggerConfig模块,以防要更改的模块尚未注册。

回答by Sudeep Shakya

Gary Gregory is correct.

加里·格雷戈里是对的。

Also the answer to this question is right there on the FAQ page in log4j2's site

此问题的答案也位于 log4j2 站点的常见问题解答页面上

https://logging.apache.org/log4j/2.x/faq.html#reconfig_level_from_code

https://logging.apache.org/log4j/2.x/faq.html#reconfig_level_from_code

Sample Code below:

示例代码如下:

Configurator.setLevel(logger.getName(), Level.INFO);