2 November 2022
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:
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.