Last active
March 4, 2023 02:37
-
-
Save david-bakin-sl/a8288bb0842baa93417aa89d929f8676 to your computer and use it in GitHub Desktop.
Capturing log4j messages for a unit test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Test | |
void loggingCaptureTest() { | |
final var log = (org.apache.logging.log4j.core.Logger)LogManager.getLogger(Foobar.class); // whatever you use to get a logger | |
CharArrayWriter outContent = new CharArrayWriter(); | |
StringLayout layout = PatternLayout.newBuilder().withPattern("%-5level %msg").build(); | |
Appender appender = WriterAppender.newBuilder().setTarget(outContent).setLayout(layout).setName("TEST").build(); | |
appender.start(); | |
log.addAppender(appender); | |
log.setLevel(Level.DEBUG); | |
log.info("foo {}", "bar"); | |
log.removeAppender(appender); | |
var msg = outContent.toString(); | |
assertThat(msg).isEqualTo("INFO foo bar"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is for log4j 2.17.2.