Transilvania JUG

Sponsors

23
Sep
2011
0

Capturing Log4j logging output

Lets say that you need to verify that a certain logging message gets printed in a unit-test. Then the first step is to pause and ask yourself: do I really need to do this? Unit-tests involving text matching are particularly tricky and prone to breaking. But if you need to do it nevertheless, here is a simple appender you can use:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public final static class TestAppender extends WriterAppender {
	private static volatile Writer testWriter; 
 
	public TestAppender() { 
		testWriter = new StringWriter();
	}
 
	public TestAppender(Layout layout) {
		testWriter = new StringWriter();
		setLayout(layout);
		activateOptions();
	}
 
	public void activateOptions() {
		setWriter(testWriter);
		super.activateOptions();
	}
 
	public static String getLoggedMessages() {
		return testWriter.toString();
	}
}

Then you can configure your Log4J logging either trough code or trough a configuration file to use this appender and use TestAppender.getLoggedMessages() to access the captured message. One limitation of this naive solution is that it can’t be used if tests are running in parallel due to the static nature of testWriter. This could be worked around with ThreadLocals for example.

Leave a Reply

Your email address will not be published. Required fields are marked *

df