0

我正在尝试在使用 Cucumber-jvm 运行的 Grovvy 单元测试中启用日志记录。

在我的测试中,我导入了:

import groovy.util.logging.Slf4j

然后添加

@Slf4j

但是,当我运行以下任何命令时:

mvn test -Dgmaven.logging=DEBUG
mvn test -Dgmaven.logging=TRACE

此方法仅打印出 '[WARN] log.isWarnEnabled()'

void debugLogging(){
    println("~~~~~ debugLogging() ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
    if(log.isTraceEnabled()){
        println("log.isTraceEnabled()")
        log.trace("log.isTraceEnabled()")
    }
    if(log.isDebugEnabled()){
        println("log.isDebugEnabled()")
        log.debug("log.isDebugEnabled()")
    }
    if(log.isInfoEnabled()){
        println("log.isInfoEnabled()")
        log.info("log.isInfoEnabled()")
    }
    if(log.isWarnEnabled()){
        println("log.isWarnEnabled()")
        log.warn("log.isWarnEnabled()")
    }
}

这是我的 ./src/test/resources/logback.xml :

<configuration>
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>
                %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
            </pattern>
        </encoder>
    </appender>

    <!-- Use level="DEBUG" for more detailed logging -->
    <root level="debug">
        <appender-ref ref="STDOUT" />
    </root>

</configuration>

如何更改单元测试中的日志级别?

4

1 回答 1

1

我发现 GMaven 不使用 logback 的困难方式。该插件旨在利用 Sonatype 提供的默认 SLF4J,称为gossip(在 GMaven 高级配置中描述)

所以这可以解释为什么你的logback.xml文件被忽略了(虽然有人会认为 SLF4J 调用在从单元测试运行时会被重定向到配置的运行时提供程序)

要将gmaven.logging属性传递给您的单元测试,您可以尝试在surefire插件中设置它,如下所示:

  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.12.4</version>
    <configuration>
      <systemPropertyVariables>
        <gmaven.logging>DEBUG</gmaven.logging>
      </systemPropertyVariables>
    </configuration>
  </plugin>

希望这可以帮助。

更新

我在开发 Maven 插件时遇到了这个问题。我的挑战是捕获源自不使用 SLF4J 的库的日志记录调用......

为了解决这个问题,我在插件依赖项部分添加了一个桥接 API,如下所示:

  <plugin>
    ..
    ..
    <dependencies>
      <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>jcl-over-slf4j</artifactId>
        <version>1.5.10</version>
      </dependency>
    </dependencies>
  </plugin>

这会将公共日志记录调用重新路由到您的 SLF4J 实现,在 Maven 的情况下这将是八卦。

于 2012-11-14T23:06:00.740 回答