[logback-user] Is there a Junit appender?

Ceki Gülcü ceki at qos.ch
Wed Apr 28 20:37:07 CEST 2010


As Robert mentioned, there is an appender called ListAppender located in 
the ch.qos.logback.core.read package.

Assuming the ListAppender was previously attached to the root logger 
under the name "LIST", the test pattern would be:

import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.Logger;
...

@Test
public void test() {
   Logger root =
       (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
   ListAppender la = root.getAppender("LIST");
   root.debug("hello");
   assertEquals(1, listAppender.list.size());
   assertEquals("hello", listAppender.list.get(0).getMessage());
}

You can also attach the ListAppender to the root logger in code. For 
example,

ListAppender<ILoggingEvent> listAppender =
                   new ListAppender<ILoggingEvent>();
listAppender.start();
root.addAppender(listAppender);
Logger logger = lc.getLogger(LoggerTest.class);
assertEquals(0, listAppender.list.size());
logger.debug("hello");
assertEquals(1, listAppender.list.size());


Logback uses ListAppender pretty extensively for its own unit testing. 
Check the logback source code for more examples.

HTH,

On 28/04/2010 8:22 PM, Robert Elliot wrote:
> Logback has a list appender that just stores all logging events in a
> list that you can query. That's what I use for unit testing logging.
>
>
>
> On 28 Apr 2010, at 19:16, "Chris Helck" <Chris.Helck at us.icap.com
> <mailto:Chris.Helck at us.icap.com>> wrote:
>
>> I want to unit test some objects and to check that the objects are
>> logging certain messages under certain cirmcumstances. Is this
>> possible? Is it easy?
>>
>> I am using slf4j. When I run the unit tests I use the NOP logger, in
>> production we use logback.
>>
>> I want something like:
>>
>> Logger logger = LoggerFactory.getLogger(MyStuff.class);
>> logger.info <http://logger.info>( "Hello World");
>>
>> assertTrue( logger.wasLoggedAsInfo( "Hello World"));
>>
>> Thanks,
>> C. Helck




More information about the Logback-user mailing list