views:

358

answers:

2

Is there an appender for log4j that only stores a list of the logging events (to be used in unit tests, to verify no error logs were written) ?

+1  A: 

I don't believe there is. You can write your own easily, though. Here's a suitable tutorial.

Brian Agnew
I did already, thanks.
ripper234
+2  A: 

There is a MemoryAppender, but it's not part of the standard log4j library.

You could easily write your own, But if you are only using them for unit tests I would probably mock the Logger and assert no calls are made to it. Override the getLogger() method in the target class or set the mock Logger directly on the type.

Using Jmock (example from memory, sorry for any errors):

public void testDoFoo() {
    Mockery mockery = new Mockery();
    Logger mockLogger = mockery.mock(Logger.class);

    Foo foo = new Foo();

    foo.setLogger(mockLogger);

    mockery.checking(new Expectations() {
        {
            never(mockLogger).debug(with(any(String.class));
        }
    };

    ...
    //do the actual test.

    //assert the mock type has never been called.
    mockery.assertIsSatisfied();
}
Rich Seller