5

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.

Flyhard
  • 544
  • 5
  • 26

1 Answers1

0

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
TedTrippin
  • 3,525
  • 5
  • 28
  • 46
  • Since you can't turn on logging after you've already logged you're going to have to replace your logger with a custom logger or override the logging so that it writes to a "custom container" that can dump its contents upon request. – TedTrippin Sep 24 '14 at 13:15
  • 1
    I was thinking of making my own appender that forwards to the real one - after it got a "clear" signal by the rule. I am just hoping that someone has done that or something better already. – Flyhard Sep 24 '14 at 13:23
  • I know what you mean, it would be nice, but in my experience most people are happy to troll though logs. Or they use a tool for looking at logs. – TedTrippin Sep 24 '14 at 13:25