Slf4j或Logback:关闭1单元测试(或1个线程)的日志记录

时间:2015-03-02 10:29:53

标签: java logging slf4j logback

我想关闭1单元测试的日志记录(不会失败),因此堆栈跟踪不会显示在日志中。堆栈跟踪应该在生产运行中存在,因为它是一个故障测试测试。

生产代码如下所示:

boolean failed = false;
for (int i = 0; i < 10; i++) {
    try {
        // Possible submits on Executor to run on other thread (not that it matters)
        runTask(i); 
    } catch (RuntimeException e) {
        // In the unit test, this pollutes the test log // BAD, MY PROBLEM
        // In production, it shows up in the log immediately, before other tasks run // GOOD
        logger.warn("Task failed. Stacktrace:", e);
        failed = true;
    }
}
if (failed) {
    // The unit test checks if this exception is thrown,
    // (it doesn't pollute the test log)
    throw new IllegalStateException("at least 1 failed");
    // In the real implementation, this also chains the first exception, to avoid eating the stacktrace
}

我有一个单元测试,如果提交给它的10个任务中至少有1个失败,它会测试执行者是否会抛出异常。因为执行器在发生内部异常时不会失败,所以它在抛出外部异常之前首先运行其他任务。因此,当它捕获内部异常时,它会记录它,在日志中给出一个堆栈跟踪。对于QA,这是误导性的,因为测试日志显示堆栈跟踪,尽管所有测试都成功。我想摆脱测试日志中的堆栈跟踪(jira)。

2 个答案:

答案 0 :(得分:3)

我认为没有slf4j的解决方案,因为受支持的框架可能不支持此功能。

如果你使用带有log4j绑定的slf4j,你可以实现它。

// get the logger you want to suppress
Logger log4j = Logger.getLogger("sub.optimal.package");

// keep the current level
Level previousLogLevel = log4j.getLevel();

// set the level to suppress your stacktrace respectively
log4j.setLevel(Level.WARN);

在下面找到如何在方法级别配置记录器的示例。您需要配置不同的记录器,以便在生产和测试环境中更改日志记录级别。

假设以下目录结构和文件

./Main.java
./slf4j-api-1.7.10.jar
./slf4j-log4j12-1.7.10.jar
./log4j-1.2.17.jar
./prod/log4j.properties
./testing/log4j.properties
./bin/

<强> Main.java

package sub.optimal;

import java.io.File;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Main {
    Logger logger;
    Logger loggerSuppressible;

    {
        logger = LoggerFactory.getLogger(this.getClass());
        loggerSuppressible = LoggerFactory.getLogger("loggerSuppressible");
    }

    public void doSomeFoo() {
        logger.info("logging from doSomeFoo");  
    }

    public void doSomeStacktrace() {
        try {
           new File("..").renameTo(null);
        } catch (NullPointerException npe) {
            loggerSuppressible.error("something went wrong", npe);
        }
    }

    public static void main(String[] args) {
        Main main = new Main();

        main.doSomeFoo();
        main.doSomeStacktrace();
    }
}

<强> ./刺/ log4j.properties

log4j.rootCategory=info, console
# production setting
log4j.category.loggerSuppressible=info, console
log4j.additivity.loggerSuppressible=false

log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.Threshold=info
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%d [%t] %-5p %c %x - %m%n

<强> ./测试/ log4j.properties

log4j.rootCategory=info, console
# testing setting
log4j.category.loggerSuppressible=fatal, console
log4j.additivity.loggerSuppressible=false

log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.Threshold=info
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%d [%t] %-5p %c %x - %m%n

<强>编译

javac -cp ${classpath_logger} -d bin/ Main.java

**投入生产**

java -cp bin/:prod/:${classpath_logger} sub.optimal.Main

**在测试中运行**

java -cp bin/:testing/:${classpath_logger} sub.optimal.Main

输出产量

2015-03-05 14:09:50,707 [main] INFO  sub.optimal.Main  - logging from doSomeFoo
2015-03-05 14:09:50,707 [main] ERROR loggerSuppressible  - something went wrong
java.lang.NullPointerException
        at java.io.File.renameTo(File.java:1386)
        at sub.optimal.Main.doSomeStacktrace(Main.java:22)
        at sub.optimal.Main.main(Main.java:32)

输出测试

2015-03-05 14:09:50,847 [main] INFO  sub.optimal.Main  - logging from doSomeFoo

答案 1 :(得分:1)

这可能听起来微不足道,但您是否考虑过将日志调用放入if-then块?

我非常确定您以某种方式将环境标识符传递给您的应用程序(例如,作为环境变量)。现在,使用静态方法创建一个实用程序类只需要几分钟,该方法可以决定当前环境是否为测试环境。

假设您可以将环境标识符作为环境变量访问,我会使用类似的东西:

public class EnvironmentInfo {

     private static final ENVIRONMENT_IDENTIFIER_PARAMETER = "env";
     private static final Set<String> TEST_ENVIRONMENTS = ImmutableSet.of("test"); // this requires Guava

     public static boolean isTestEnvironment() {
         return TEST_ENVIRONMENTS.contains(System.getProperty(ENVIRONMENT_IDENTIFIER_PARAMETER));
     }

}

当您登录时,您只需使用:

if (!EnvironmentInfo.isTestEnvironment()) {
    logger.warn("Task failed. Stacktrace:", e);
}