gpt4 book ai didi

java.util.logging.LogManager.getLogger() 返回 null

转载 作者:行者123 更新时间:2023-11-30 07:11:23 26 4
gpt4 key购买 nike

我遇到了一个让我非常困惑的问题。我想尝试使用 JUL 日志记录(JDK 日志记录)做一些事情。我从以下简单程序开始:

package biz.ple;

import java.util.logging.LogManager;
import java.util.logging.Logger;

public class Application {

public static void main(String[] args)
{
Logger logA = LogManager.getLogManager().getLogger("LoggerA");
Logger logB = LogManager.getLogManager().getLogger("LoggerB");
if (logA == null) {
System.out.println("LoggerA is null!");
}
if (logB == null) {
System.out.println("LoggerB is null!");
}

String normalMsg = "Message without cookie prefix.";
String cookieMsg = "[Cookie] Message with a cookie prefix.";

logA.info(normalMsg);
logA.info(cookieMsg);
logB.info(normalMsg);
logB.info(cookieMsg);
}
}

令人惊讶的是,记录器 logA 和 logB 总是为空。我在文档中读到,应用程序对其没有强引用的记录器随时会被 GC 处理,但在我看来,变量 logA 和 logB 确实是强引用,不是吗?

我真的不明白这一点,希望得到任何帮助。

最佳答案

我的理解是,这只会获取现有的记录器,而不会创建一个新的同名记录器。要创建新的记录器,您需要使用静态 Logger.getLogger("myLogger"); 命令

public static void main(String[] args){
Logger log=Logger.getLogger("myLogger");

Logger logA = LogManager.getLogManager().getLogger("myLogger"); //exists
Logger logB = LogManager.getLogManager().getLogger("nonExistantLogger"); //is null

}

Logger.getLogger("myLogger") javadoc:

Find or create a logger for a named subsystem. If a logger has alreadybeen created with the given name it is returned. Otherwise a newlogger is created.

If a new logger is created its log level will be configured based onthe LogManager configuration and it will configured to also sendlogging output to its parent's Handlers. It will be registered inthe LogManager global namespace.

Note: The LogManager may only retain a weak reference to the newlycreated Logger. It is important to understand that a previouslycreated Logger with the given name may be garbage collected at anytime if there is no strong reference to the Logger. In particular,this means that two back-to-back calls likegetLogger("MyLogger").log(...) may use different Logger objects named"MyLogger" if there is no strong reference to the Logger named"MyLogger" elsewhere in the program.

LogManager.getLogManager().getLogger("myLogger") javadoc

Method to find a named logger.

Note that since untrusted code may create loggers with arbitrary namesthis method should not be relied on to find Loggers for securitysensitive logging. It is also important to note that the Loggerassociated with the String name may be garbage collected at any timeif there is no strong reference to the Logger. The caller of thismethod must check the return value for null in order to properlyhandle the case where the Logger has been garbage collected.

关于java.util.logging.LogManager.getLogger() 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21306807/

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