gpt4 book ai didi

java - 我们可以在运行时更改 log4j 的日志记录级别吗

转载 作者:太空狗 更新时间:2023-10-29 23:02:50 24 4
gpt4 key购买 nike

我有一个问题,我想在运行时更改 log4j 的日志记录级别,我用 log4j.properties 文件尝试了很多事情,我还尝试编写一段代码,在特定时间后再次读取属性文件配置记录器。

但问题是,我想将一个 API 调用的日志记录级别更改为 DEBUG,然后当该调用完成时,记录器应再次更改为之前的值。

请帮忙..

最佳答案

调用 Logger.setLevel 方法与所需的 Level 可以改变 Logger运行时的输出电平。

下面是一个演示其用法的例子:

Logger logger = Logger.getLogger("myLogger");
logger.addAppender(new ConsoleAppender(new SimpleLayout()));

System.out.println("*** The current level will be INFO");

logger.setLevel(Level.INFO);
logger.warn("Only INFO and higher will appear");
logger.info("Only INFO and higher will appear");
logger.debug("Only INFO and higher will appear");

System.out.println("*** Changing level to DEBUG");

// remember the previous level
Level previousLevel = logger.getLevel();

logger.setLevel(Level.DEBUG);
logger.warn("DEBUG and higher will appear");
logger.info("DEBUG and higher will appear");
logger.debug("DEBUG and higher will appear");

System.out.println("*** Changing level back to previous level");

// revert to previous level
logger.setLevel(previousLevel);
logger.warn("Only INFO and higher will appear");
logger.info("Only INFO and higher will appear");
logger.debug("Only INFO and higher will appear");

以上输出:

*** The current level will be INFO
WARN - Only INFO and higher will appear
INFO - Only INFO and higher will appear
*** Changing level to DEBUG
WARN - DEBUG and higher will appear
INFO - DEBUG and higher will appear
DEBUG - DEBUG and higher will appear
*** Changing level back to previous level
WARN - Only INFO and higher will appear
INFO - Only INFO and higher will appear

上面演示了如何改变一个Logger的级别名为 myLogger , 但如果当前存储库中所有记录器的级别都应该更改,那么 setLevel通过 Logger.getRootLogger 获得的根记录器 上的方法应调用以更改所有子记录器的级别。

关于java - 我们可以在运行时更改 log4j 的日志记录级别吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4415467/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com