如何在运行时使用log4j2 api将loglevel从INFO设置为ERROR?

log4中没有logger.setLevel()方法。 那么如何在运行时设置日志级别。

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

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

举个例子:

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 

感谢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; } 

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

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

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

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

org.apache.logging.log4j.core.config.Configurator类中的以下API允许您更改级别:

  • setAllLevels(String,Level)
  • setLevel(图)
  • setLevel(String,Level)
  • setRootLevel(等级)

加里格雷戈里是对的。

此问题的答案就在log4j2网站的FAQ页面上

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

示例代码如下:

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