Log4j appender for debug output if test fails

╄→гoц情女王★ 提交于 2021-02-19 01:35:15

问题


I would like to set up my test-logging so that log output is mainly suppressed - unless a test fails. then I would like to have the debug output.

I know the manual solution of just modifying the log4j.properties in the test classpath or just having debug logging always active for tests - but I don't want to spam the console with unnessesary output for green tests.

For failing tests I want the automatic build to give me the debug output in case there are some weired environment issues going on.

I have been thinking there should be an appender that could be combined with a junit rule that supresses output until the result of the test is known and then only deferes logging to another appender if the test has failed.

I could probably make this myself, but I wonder if anyone has tried this before or if there are better solutions to the problem.


回答1:


You can add a watcher which logs to a separate logger.

public class MyUnitTest {

  private static Logger errorLog = Logger.getLogger("ErrorLogger");

  @Rule
  public TestWatcher testWatcher = new TestWatcher() {
    @Override
    protected void failed(Throwable e, Description description) {
        errorLog.debug(description.toString(), e);
        super.failed(e, description);
    }
  };

}

Then just add ErrorLogger to your log4j properties

log4j.logger.ErrorLogger=debug, someAppender


来源:https://stackoverflow.com/questions/26015004/log4j-appender-for-debug-output-if-test-fails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!