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

标签 java logging java.util.logging

这是我的示例代码:

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/

相关文章:

java - 如何判断一个字符串是 IP 还是主机名

logging - 如何在非 Akka 部件调度的日志事件中提供可用的 sourceThread 和 akkaTimestamp 值?

Java - 配置自定义记录器以供使用

java - Hibernate - 如何使用生成器为引用表创建主键?

java - Mockito 问题 - Stubber 中的 when(java.lang.Void) 无法应用于 void

android - android 记录器是否在主线程上运行?

java - MDC(映射诊断上下文)支持 JUL(Java.util.Logging)

java - 在 Java 中登录

javascript - Guacamole VNC 文件传输

Python 字符串格式 - 限制字符串长度,但修剪字符串开头