javalog4jin-memoryappender

In memory 'list appender' for log4j


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) ?


Solution

  • 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();
    }