How to capture log events in tests with Log4j 2
By Mikael Ståldal
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:
- Include this dependency (for Maven, adjust appropriately for other build systems):
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<type>test-jar</type>
<scope>test</scope>
</dependency>
- 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;
- 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");
appender.start();
loggerContext.getConfiguration().addLoggerAppender(logger, appender);
- Exercise your code which should be logging.
- Extract what was logged:
List<String> loggedStrings =
appender.getEvents().stream().map(event -> event.getMessage().toString()).collect(Collectors.toList());
Update:
Starting with Log4j 2.20.0, this has changed to
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core-test</artifactId>
<scope>test</scope>
</dependency>
and
import org.apache.logging.log4j.core.test.appender.ListAppender;