log4j2 java版本_java - 以编程方式更改Log4j2中的日志级别

默认情况下,大多数答案都假定日志记录必须是附加的。 但是,假设某些软件包生成了大量日志,并且您只想关闭该特定日志记录器的日志记录。 这是我用来使它工作的代码

public class LogConfigManager {

public void setLogLevel(String loggerName, String level) {

Level newLevel = Level.valueOf(level);

LoggerContext logContext = (LoggerContext) LogManager.getContext(false);

Configuration configuration = logContext.getConfiguration();

LoggerConfig loggerConfig = configuration.getLoggerConfig(loggerName);

// getLoggerConfig("a.b.c") could return logger for "a.b" if there is no logger for "a.b.c"

if (loggerConfig.getName().equalsIgnoreCase(loggerName)) {

loggerConfig.setLevel(newLevel);

log.info("Changed logger level for {} to {} ", loggerName, newLevel);

} else {

// create a new config.

loggerConfig = new LoggerConfig(loggerName, newLevel, false);

log.info("Adding config for: {} with level: {}", loggerConfig, newLevel);

configuration.addLogger(loggerName, loggerConfig);

LoggerConfig parentConfig = loggerConfig.getParent();

do {

for (Map.Entry entry : parentConfig.getAppenders().entrySet()) {

loggerConfig.addAppender(entry.getValue(), null, null);

}

parentConfig = parentConfig.getParent();

} while (null != parentConfig && parentConfig.isAdditive());

}

logContext.updateLoggers();

}

}

一个测试用例

public class LogConfigManagerTest {

@Test

public void testLogChange() throws IOException {

LogConfigManager logConfigManager = new LogConfigManager();

File file = new File("logs/server.log");

Files.write(file.toPath(), new byte[0], StandardOpenOption.TRUNCATE_EXISTING);

Logger logger = LoggerFactory.getLogger("a.b.c");

logger.debug("Marvel-1");

logConfigManager.setLogLevel("a.b.c", "debug");

logger.debug("DC-1");

// Parent logger level should remain same

LoggerFactory.getLogger("a.b").debug("Marvel-2");

logConfigManager.setLogLevel("a.b.c", "info");

logger.debug("Marvel-3");

// Flush everything

LogManager.shutdown();

String content = Files.readAllLines(file.toPath()).stream().reduce((s1, s2) -> s1 + "\t" + s2).orElse(null);

Assert.assertEquals(content, "DC-1");

}

}

假设后面的log4j2.xml在classpath中

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值