在 JUnit 测试中使用 Maven 时让 JUL 通过 log4j2 进行日志记录

时间:2021-07-28 14:53:01

标签: java maven logging log4j2 java.util.logging

我正在运行一个小测试项目,我希望我的 JUL 日志被重定向并显示为 log4j2 日志。 我正在使用以下 Maven 依赖项:

<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-api</artifactId>
    <version>5.8.0-M1</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-api</artifactId>
    <version>2.14.1</version>
</dependency>
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.14.1</version>
</dependency>
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-jul</artifactId>
    <version>2.13.3</version>
</dependency>

要使用 log4j-jul 适配器,我应该将系统属性 java.util.logging.manager 设置为 org.apache.logging.log4j.jul.LogManager。 当我在我的项目的主要方法中使用

System.setProperty("java.util.logging.manager", "org.apache.logging.log4j.jul.LogManager"); 

然后日志记录按需要工作。但是如果我使用一个 JUnit 测试(使用 mvn test 运行)来做同样的事情,比如

@Test
public void loggingJULTest() {
    System.setProperty("java.util.logging.manager", "org.apache.logging.log4j.jul.LogManager");
    java.util.logging.Logger julLogger = java.util.logging.Logger.getLogger(MainTest.class.getName());

    julLogger.info("Info Message from JUL");
    julLogger.severe("Severe message from JUL");
    julLogger.fine("Fine message from JUL");

}

然后日志以 JUL 样式显示。 我尝试在pom.xml中的Maven的Surefire Plugin中添加如下配置

<configuration>
   <systemPropertyVariables>
      <java.util.logging.manager>org.apache.logging.log4j.jul.LogManager</java.util.logging.manager>
      <buildDirectory>${project.build.directory}</buildDirectory>
   </systemPropertyVariables>
</configuration>

但是测试没有输出并显示警告

[WARNING] Corrupted STDOUT by directly writing to native stream in forked JVM 1. See FAQ web page and the dump file[..]

我对我应该在这里做什么感到困惑。

1 个答案:

答案 0 :(得分:0)

如果您使用的是 3.0.0-M5maven-surefire-plugin 版本,则需要将 <forkNode implementation="org.apache.maven.plugin.surefire.extensions.SurefireForkNodeFactory"/> 添加到 configuration

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>3.0.0-M5</version>
            <configuration>
                <forkNode implementation="org.apache.maven.plugin.surefire.extensions.SurefireForkNodeFactory"/>
                ...
            </configuration>
        </plugin>
    </plugins>
</build>

详情:According to the Jira issue SUREFIRE-1614


P.S.:以后有类似问题请补充Java和Maven的版本信息。