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

Difference between Logger.getGlobal() and Logger.getAnonymousLogger()?

这是我的示例代码:

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.

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