Skip to content

Commit

Permalink
Reset StatusLogger fallback listener stream on initialization
Browse files Browse the repository at this point in the history
Update `Log4J2LoggingSystem` so that the `StatusLogger` fallback
listener has its print stream reset on each initialization. This
allows output capture to work with the status listener.

Fixes gh-43578

Co-authored-by: Phillip Webb <[email protected]>
  • Loading branch information
nosan and philwebb committed Jan 7, 2025
1 parent ec75474 commit b6b9237
Show file tree
Hide file tree
Showing 5 changed files with 62 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,8 @@
@Target(ElementType.TYPE)
@Documented
@ClassPathExclusions("log4j-to-slf4j-*.jar")
@ClassPathOverrides({ "org.apache.logging.log4j:log4j-core:2.19.0",
"org.apache.logging.log4j:log4j-slf4j-impl:2.19.0" })
@ClassPathOverrides({ "org.apache.logging.log4j:log4j-core:2.24.3",
"org.apache.logging.log4j:log4j-slf4j-impl:2.24.3" })
public @interface ConfigureClasspathToPreferLog4j2 {

}
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2012-2024 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -47,6 +47,7 @@
import org.apache.logging.log4j.core.util.AuthorizationProvider;
import org.apache.logging.log4j.core.util.NameUtil;
import org.apache.logging.log4j.jul.Log4jBridgeHandler;
import org.apache.logging.log4j.status.StatusLogger;
import org.apache.logging.log4j.util.PropertiesUtil;

import org.springframework.boot.context.properties.bind.BindResult;
Expand Down Expand Up @@ -213,6 +214,7 @@ public void initialize(LoggingInitializationContext initializationContext, Strin
if (isAlreadyInitialized(loggerContext)) {
return;
}
resetFallbackListenerStream(StatusLogger.getLogger());
Environment environment = initializationContext.getEnvironment();
if (environment != null) {
getLoggerContext().putObject(ENVIRONMENT_KEY, environment);
Expand All @@ -224,6 +226,21 @@ public void initialize(LoggingInitializationContext initializationContext, Strin
markAsInitialized(loggerContext);
}

/**
* Reset the stream used by the fallback listener to the current system out. This
* allows the fallback lister to work with any captured output streams in a similar
* way to the {@code follow} attribute of the {@code literal Console} appender.
* @param statusLogger the status logger to update
*/
private void resetFallbackListenerStream(StatusLogger statusLogger) {
try {
statusLogger.getFallbackListener().setStream(System.out);
}
catch (NoSuchMethodError ex) {
// Ignore for older versions of Log4J
}
}

@Override
protected void loadDefaults(LoggingInitializationContext initializationContext, LogFile logFile) {
String location = getPackagedConfigFile((logFile != null) ? "log4j2-file.xml" : "log4j2.xml");
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/*
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package smoketest.structuredlogging.log4j2;

import java.util.Objects;

import org.springframework.boot.json.JsonWriter.Members;
import org.springframework.boot.logging.structured.StructuredLoggingJsonMembersCustomizer;

public class DuplicateJsonMembersCustomizer implements StructuredLoggingJsonMembersCustomizer<Object> {

@Override
public void customize(Members<Object> members) {
members.add("test").as(Objects::toString);
members.add("test").as(Objects::toString);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,6 @@ logging.structured.format.console=ecs
#---
spring.config.activate.on-profile=custom
logging.structured.format.console=smoketest.structuredlogging.log4j2.CustomStructuredLogFormatter
#---
spring.config.activate.on-profile=on-error
logging.structured.json.customizer=smoketest.structuredlogging.log4j2.DuplicateJsonMembersCustomizer
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2012-2024 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -62,4 +62,10 @@ void custom(CapturedOutput output) {
assertThat(output).contains("epoch=").contains("msg=\"Starting SampleLog4j2StructuredLoggingApplication");
}

@Test
void shouldCaptureCustomizerError(CapturedOutput output) {
SampleLog4j2StructuredLoggingApplication.main(new String[] { "--spring.profiles.active=on-error" });
assertThat(output).contains("The name 'test' has already been written");
}

}

0 comments on commit b6b9237

Please sign in to comment.