Mar 312012
 

While working with logging of an application I found that the thing I wanted to test was the actual output from a logger. After digging around a bit I found a neat thing in log4j called AppenderSkeleton. It’s pretty straight forward, extend AppenderSkeleton to keep track of log events and add your new appender to the RootLogger.

First, create your TestAppender:

class TestAppender extends AppenderSkeleton {
    private final List<LoggingEvent> log = new ArrayList<LoggingEvent>();

    @Override
    public boolean requiresLayout() {
        return false;
    }

    @Override
    protected void append(final LoggingEvent loggingEvent) {
        log.add(loggingEvent);
    }

    @Override
    public void close() {
        // noop
    }

    public List<LoggingEvent> getLog() {
        return new ArrayList<LoggingEvent>(log);
    }
}

Then, when setting up your tests add this appender to the root appender.

private TestAppender testAppender;

@Before
public void doBeforeEachTest() {
    testAppender = new TestAppender();
    Logger.getRootLogger().addAppender(testAppender);
}

You can now for example use

testAppender.getLog().get(0).getMessage();

to get the first log message.

  2 Responses to “How Log4j and JUnit became friends”

  1. A really nice solution, used it today… and it work perfect!

  2. How do u get the other information associated with the log like class name, file name,line number, method name, level etc.

 Leave a Reply

(required)

(required)

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>