简体   繁体   English

共用记录-Stdout / Stderr在JUnit4测试中不起作用

[英]Commons Logging - Stdout/Stderr doesn't work at JUnit4 tests

Problem: Logs doesn't echo anything in my unit tests. 问题:在我的单元测试中,日志没有回显任何内容。 Logging works well in my app, but when I move the same code to test package they stop working. 日志在我的应用程序中运行良好,但是当我移动相同的代码来test程序包时,它们将停止工作。 (see code below) (请参见下面的代码)

Question: How to get logs in my unit tests? 问题:如何在单元测试中获取日志?

Code: 码:

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class LogTest {

  private static final Log _LOG = LogFactory.getLog(TransformerServiceTest.class);

  @Test
  public void testLogs() {
    _LOG.info("!!!!!!!!!!!!!!!!!!"); // NEVER ECHOES TO STDOUT
  }
}

Update: Now only _LOG.error() works 更新:现在只有_LOG.error()起作用

After changing to DEBUG level, only ERROR level works 更改为DEBUG级别后,仅ERROR级别有效

log4j.properties log4j.properties

# Root logger option
log4j.rootLogger=DEBUG, stdout

# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

LogTest.class LogTest.class

public class LogTest {

    private static Log _LOG = LogFactory.getLog(LogTest.class);

    @Test
    public void test() {
        _LOG.error("Error works!"); //works
        _LOG.warn("Warn works!"); //doesn't work
        _LOG.info("Info works!"); // doesn't work
    }
}

You just need to add the log4j dependency into your classpath and all will work fine. 您只需要将log4j依赖项添加到类路径中,一切就可以正常工作。

If you are using Maven then just add this to the dependencies element in the pom.xml: 如果您使用的是Maven,则将其添加到pom.xml中的dependencies元素中:

...
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
...

If you have a simpler working env, just add it to your classpath 如果您的工作环境更简单,只需将其添加到类路径中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM