问题
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