gpt4 book ai didi

java - Logger.getGlobal() 和 Logger.getAnonymousLogger() 之间的区别?

转载 作者:行者123 更新时间:2023-12-02 12:06:19 32 4
gpt4 key购买 nike

这是我的示例代码:

public class Logs {
private static Logs logHandler;

public static Logs handler() {
if (null == logHandler) {
logHandler = new Logs();
}
return logHandler;
}

public void logError(String message) {
Logger.getGlobal().log(Level.SEVERE, message);
}
}

我不太明白这两者之间的区别,因为它们提供完全相同的输出:

Logger.getGlobal.log(Level.SEVERE, message);

和:

Logger.getAnonymousLogger.log(Level.SEVERE, message);

有人可以告诉我它们的区别,以便我知道应该使用哪个吗?

提前谢谢您!

最佳答案

匿名记录器没有名称,这意味着您不能将记录器名称用作 formatter pattern 。匿名记录器不执行安全检查,这意味着任何代码都可以更改匿名记录器的设置。

全局记录器就是System.out,可以说是日志记录API。它是一个命名记录器,如果代码尝试修改设置,它会执行安全检查。

文档建议您使用 named loggers如果可能的话。

来自GLOBAL_LOGGER_NAME文档:

The "global" Logger object is provided as a convenience to developers who are making casual use of the Logging package. Developers who are making serious use of the logging package (for example in products) should create and use their own Logger objects, with appropriate names, so that logging can be controlled on a suitable per-Logger granularity. Developers also need to keep a strong reference to their Logger objects to prevent them from being garbage collected.

来自getAnonymousLogger​()文档:

Create an anonymous Logger. The newly created Logger is not registered in the LogManager namespace. There will be no access checks on updates to the logger.

This factory method is primarily intended for use from applets. Because the resulting Logger is anonymous it can be kept private by the creating class. This removes the need for normal security checks, which in turn allows untrusted applet code to update the control state of the Logger. For example an applet can do a setLevel or an addHandler on an anonymous Logger.

Even although the new logger is anonymous, it is configured to have the root logger ("") as its parent. This means that by default it inherits its effective level and handlers from the root logger. Changing its parent via the setParent method will still require the security permission specified by that method.

此外,如果您要保留示例类,请确保通过创建静态最终字段来保留对全局记录器的强引用。

关于java - Logger.getGlobal() 和 Logger.getAnonymousLogger() 之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46888178/

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