While working on #43575 I noticed that Log4j2 Smoke Tests does not contain a test to verify that DefaultErrorHandler prints an error into the console if StructuredLogLayout throws an Exception.
I added a test to check DefaultErrorHandler prints errors but unfortunately, it did not work since Log42J StatusLogger keeps the reference to the outdated PrintStreamCapture.
Reproducer: https://github.com/spring-projects/spring-boot/compare/main...nosan:spring-boot:log4j2-status-logger
If you run a single test shouldCaptureCustomizerError in SampleLog4j2StructuredLoggingApplicationTests everything will be fine, but if you run all tests in SampleLog4j2StructuredLoggingApplicationTests, the CapturedOutput will be empty and shouldCaptureCustomizerError test will fail.
Possible fix https://github.com/spring-projects/spring-boot/compare/main...nosan:spring-boot:log4j2-status-logger-fix but I am not sure this is the right way.
Comment From: philwebb
Thanks @nosan, I've taken your test and a slightly different fix. I hope that's OK. Let me know if you see any potential issues.
Comment From: nosan
Thanks, @philwebb.
I am worried about what happens if someone replaces fallbackListener with their own PrintStream. In that scenario, Log4J2LoggingSystem would overwrite it with System.out.
Maybe reset fallbackListener's stream should be applied only in the smoke-test.
Comment From: philwebb
I did a bit of manual testing for that and I think Log4J2LoggingSystem sets the stream before the configuration is applied. In other words, I think it sets the stream to System.out and then the user configuration kicks in and changes it to whatever they want.
Comment From: violetagg
@nosan @philwebb I would like to point to an issue in BlockHound (https://github.com/reactor/BlockHound/issues/469), caused by this issue and the corresponding changes. IMO there is an issue with org.apache.logging.log4j.status.StatusConsoleListener#closeNonSystemStream
Comment From: wilkinsona
Thanks for tracking down the root cause, @violetagg. I've re-opened https://github.com/spring-projects/spring-boot/issues/43963.