为什么在 System.Logger 中使用 log(DEBUG, msg) 而不是 debug(msg)?

Why in System.Logger is log(DEBUG, msg) used instead of debug(msg)?

我正在阅读 System.Logger API 中介绍的 Java 9。我不明白为什么他们会发展成这样 strange API:

System.Logger {
  public default void log(Level level, String msg){...}
}

我称它为strange,因为所有流行的日志记录框架(我知道)都不把级别作为参数,而是用级别名称命名调用方法。例如:

//Log4j
logger.error("This is error : " + parameter);
//SLF4J
logger.debug("Printing variable value: {}", variable);
//apache.commons.logging
log.debug(Object message);
//and even sun.util.logging.PlatformLogger
logger.warning(String msg)

怎么解释?

关于开发者意图的问题本来就很难回答,除非你是开发者。

也就是说,我们确实可以访问此功能的原始提案 - JEP 264

总结:

Define a minimal logging API which platform classes can use to log messages, together with a service interface for consumers of those messages. A library or application can provide an implementation of this service in order to route platform log messages to the logging framework of its choice. If no implementation is provided then a default implementation based upon the java.util.logging API is used.

来自目标:

Be easily adoptable by applications which use external logging framework, such as SLF4J or Log4J.

来自非目标:

It is not a goal to define a general-purpose interface for logging. The service interface contains only the minimal set of methods that the JDK needs for its own usage.

所以我们这里有的不是 "Yet another logging framework" SLF4J、Log4J 等。我们有一个接口,允许您告诉 JVM 使用您用于 classes 在你的应用程序中,用于记录它自己的东西。

典型的使用场景是在 SLF4J 中进行复杂设置的应用程序,记录到控制台、文件、数据库或向手机发送文本。您希望 JVM classes 使用相同的系统。因此,您使用 SLF4J 设置编写了一个适配器 - class 实现了 System.Logger 接口。

这并不是说您不能使用当前系统记录器进行记录——您可以——但这不是创建它的目的。它是为您创建的,用于实施和设置系统记录器,以便它调用您选择的日志记录框架。

以目前的形式,当你实现时,你只需要实现四个方法:

  • getName()
  • isLoggable(System.Logger.Level)
  • log(System.Logger.Level, ResourceBundle, String, Object...)
  • log​(System.Logger.Level, ResourceBundle, String, Throwable)

现在,System.Logger.Level 有七个级别。想象一下,如果您不必实现两种日志记录方法,而是必须实现 14 种日志记录方法,会怎样?通常情况下,这些实现看起来完全一样,只是名称稍有变化。这是不明智的。

就目前而言,几乎每个现有的日志框架都有一个 log(level,...) 方法,然后 System.Loggerlog(...) 的实现通常可以简单地通过从 System.Logger.Level 到你的框架的 Level 定义。


如果您想记录消息?

好吧,如果您使用的是复杂的日志记录平台,您可以直接在那里记录消息,不需要通过系统记录器。如果您坚持使用它 - 您将需要使用级别作为参数或编写自己的包装器。这根本不是开发人员考虑的用例。