gpt4 book ai didi

java.util.logging.Logger 与根 Logger 具有不同的级别

转载 作者:行者123 更新时间:2023-12-01 14:28:21 24 4
gpt4 key购买 nike

在我的应用程序中,有一次我将 java.util.logging 的根 Logger 及其所有处理程序设置为 Level.FINEST,如下所示:

Logger.getLogger("").setLevel(Level.FINEST);
for (Handler handler : Logger.getLogger("").getHandlers()) {
handler.setLevel(Level.FINEST);
}

稍后我将创建一个类 Logger,如下所示:

private static final Logger JAVA_LOG = Logger.getLogger(MyClass.class.getName());

现在这个记录器级别是 INFO(这似乎是 JUL 的默认值),而它的根记录器级别已正确设置为 FINEST。不应该为根记录器设置级别也为根记录器的所有子记录器设置级别吗?我在检索类 Logger 时做错了什么吗?

最佳答案

不应该为根 Logger 设置 Level 也为根 Logger 的所有子记录器设置 Level 吗?

不,显然您正在创建一个新的 Logger 对象。 Javadoc for getLogger状态:

If a new logger is created its log level will be configured based on the LogManager configuration and it will configured to also send logging output to its parent's Handlers.

请注意,即使之前有同名的 Logger 对象,您也不能依赖 getLogger 返回相同的对象,因为如果没有强对象,它可能已被垃圾回收对象的引用。

如果您的目标是在您的项目中创建具有相同日志级别的所有 Logger 对象,您不应该以编程方式而是通过配置来实现。这就是 java.util.logging 派上用场的地方。总体优势是您可以在不同的日志级别运行您的应用程序,甚至无需更改一行代码。

只需编辑您的配置文件(本质上就是上面提到的 LogManager 配置)。它称为 logging.properties 并且位于您的 JRE 目录中。您可以在那里编辑最后一段并配置项目范围或类缩小的日志级别:

############################################################
# Facility specific properties.
# Provides extra control for each logger.
############################################################

myProject.MyClass.level = FINE
myProject.MyOtherNotSoImportantClass.level = INFO
mySecondProject.MainClass.level = NONE

一个更好的解决方案是将 logging.properties 复制到您的项目目录并使用

调用您的应用程序
java -Djava.util.logging.config.file=./src/test/resources/logging.properties

关于java.util.logging.Logger 与根 Logger 具有不同的级别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54786116/

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