使用 log4j 2.10.0 Java 9 System.Logger

Using log4j 2.10.0 with Java 9 System.Logger

如何设置 Java 9 以便 System.Logger 实例写入 log4j 2.10.0,而不是写入 JUL?

这是您引用的段落:

This release contains the first support of Java 9 as well as bugfixes and minor enhancements. The Log4j API was modified to use java.util.ServiceLoader to locate Log4j implementations, although the former binding mechanism is still supported. The Log4j jar is now a multi-release jar to provide implementations of the Java 9 specific classes.

它没有提到 System.LoggerFinder 并且确实是 the repo (of version 2.10) didn't turn up any mention of "LoggerFinder" and nothing promising for "java.lang.System". I'm hence sure that Log4J 2.10 does not yet integrate with JEP 264: Platform Logging API and Service.

的全文搜索

发行说明似乎指的是 Log4J 现在在寻找 它自己的 [=35] 的实现时使用 ServiceLoader API =].

自己动手

如果您真的 need/want Log4J 记录这些消息,您可以推出自己的适配器 as I did here for SLF4J。您所需要的只是用于 System.LoggerSystem.LoggerFinder 的 Log4J 适配器(如果您略过一些细节,两者都可以直接实现)和一个 META-INF/services 文件或如下所示的模块声明:

module org.slf4j.platform {
    // put the right module name here
    requires log4j;
    provides java.lang.System.LoggerFinder
        // put the right class name here
        with org.log4J.Log4JSystemLoggerFinder;
}

使用该工件启动您的应用程序将导致 Log4J 获取平台日志消息。

为什么不简单地使用 Log4j2 的 Java util logging adapter 将所有 JUL 日志记录路由到 Log4j2?

要启用此功能,请将系统 属性 java.util.logging.manager 设置为 org.apache.logging.log4j.jul.LogManager 并将 log4j-jul 添加到您的依赖项中。

Log4j 2 支持 JDK 平台日志记录 since version 2.13.2。如果要使用 System.Logger 和 Log4j 2 作为后端,则需要使用 log4j-jpl 适配器:

<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-api</artifactId>
    <version>${replace.with.right.version}</version>
    <scope>runtime</scope>
</dependency>
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>${replace.with.right.version}</version>
    <scope>runtime</scope>
</dependency>
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-jpl</artifactId>
    <version>${replace.with.right.version}</version>
    <scope>runtime</scope>
</dependency>

之后,您的 System.Logger 会将日志重定向到 Log4j:

public final class Main {
    private static final Logger LOGGER = System.getLogger("");

    public static void main(String[] args) {
        LOGGER.log(Level.ERROR, "Hello, {}!", "user");
    }
}

输出:

11:02:44.736 [main] ERROR  - Hello, user!