Skip to content

Instantly share code, notes, and snippets.

@david-bakin-sl
Last active March 4, 2023 02:37
Show Gist options
  • Save david-bakin-sl/a8288bb0842baa93417aa89d929f8676 to your computer and use it in GitHub Desktop.
Save david-bakin-sl/a8288bb0842baa93417aa89d929f8676 to your computer and use it in GitHub Desktop.
Capturing log4j messages for a unit test
@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");
}
@david-bakin-sl
Copy link
Author

This is for log4j 2.17.2.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment