Explore Courses Blog Tutorials Interview Questions
0 votes
in Java by (10.2k points)

I have some code-under-test that calls on a Java logger to report its status. In the JUnit test code, I would like to verify that the correct log entry was made in this logger. Something along the following lines:

methodUnderTest(bool x){

    if(x)"x happened")


@Test tester(){

    // perhaps setup a logger first.




I suppose that this could be done with a specially adapted logger (or handler, or formatter), but I would prefer to re-use a solution that already exists. (And, to be honest, it is not clear to me how to get at the logRecord from a logger, but suppose that that's possible.)

1 Answer

0 votes
by (46k points)

I've needed this several times as well. I've put together a small sample below, which you'd want to adjust to your needs. Basically, you create your own Appender and add it to the logger you want. If you'd want to collect everything, the root logger is a good place to start, but you can use a more specific if you'd like. Don't forget to remove the Appender when you're done, otherwise you might create a memory leak. Below I've done it within the test, but setUp or @Before and tearDown or @After might be better places, depending on your needs.

Also, the implementation below collects everything in a List in memory. If you're logging a lot you might consider adding a filter to drop boring entries, or to write the log to a temporary file on disk (Hint: LoggingEvent is Serializable, so you should be able to just serialize the event objects, if your log message is.)

import org.apache.log4j.AppenderSkeleton;

import org.apache.log4j.Level;

import org.apache.log4j.Logger;

import org.apache.log4j.spi.LoggingEvent;

import org.junit.Test;

import java.util.ArrayList;

import java.util.List;

import static;

import static org.junit.Assert.assertThat;

public class MyTest {


    public void test() {

        final TestAppender appender = new TestAppender();

        final Logger logger = Logger.getRootLogger();


        try {



        finally {



        final List<LoggingEvent> log = appender.getLog();

        final LoggingEvent firstLogEntry = log.get(0);

        assertThat(firstLogEntry.getLevel(), is(Level.INFO));

        assertThat((String) firstLogEntry.getMessage(), is("Test"));

        assertThat(firstLogEntry.getLoggerName(), is("MyTest"));



class TestAppender extends AppenderSkeleton {

    private final List<LoggingEvent> log = new ArrayList<LoggingEvent>();


    public boolean requiresLayout() {

        return false;



    protected void append(final LoggingEvent loggingEvent) {




    public void close() {


    public List<LoggingEvent> getLog() {

        return new ArrayList<LoggingEvent>(log);



Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers


94.7k users

Browse Categories