How to capture log events in tests with Log4j 2

Sometimes you want to verify that your program actually logs what it is supposed to be logging.

When using Apache Log4j 2 as logging framework, it can be done like this:

  1. Include this dependency (for Maven, adjust appropriately for other build systems):
  2. Import some stuff:
    import org.apache.logging.log4j.core.Logger;
    import org.apache.logging.log4j.core.LoggerContext;
    import org.apache.logging.log4j.test.appender.ListAppender;
  3. Add a ListAppender to the logger you are interested in:
    var loggerContext = LoggerContext.getContext(false);
    var logger = (Logger) loggerContext.getLogger(MyClass.class);
    var appender = new ListAppender("List");
    loggerContext.getConfiguration().addLoggerAppender(logger, appender);
  4. Exercise your code which should be logging.
  5. Extract what was logged:
    List<String> loggedStrings = 
            appender.getEvents().stream().map(event -> event.getMessage().toString()).collect(Collectors.toList());
This entry was posted in Java. Bookmark the permalink.