Skip to content

Commit 493777d

Browse files
committed
Include the application name on each log line when it is available
Update Logback and Log4J2 so that they include the application name on each log line. If `spring.application.name` had not been set, or if `logging.include-application-name` is `false` then the name is not logged. Closes gh-35593
1 parent c1b295f commit 493777d

File tree

15 files changed

+95
-10
lines changed

15 files changed

+95
-10
lines changed

spring-boot-project/spring-boot-docs/build.gradle

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -293,7 +293,7 @@ task runSpringApplicationExample(type: org.springframework.boot.build.docs.Appli
293293
task runLoggingFormatExample(type: org.springframework.boot.build.docs.ApplicationRunner) {
294294
classpath = configurations.springApplicationExample + sourceSets.main.output
295295
mainClass = "org.springframework.boot.docs.features.springapplication.MyApplication"
296-
args = ["--spring.main.banner-mode=off", "--server.port=0"]
296+
args = ["--spring.main.banner-mode=off", "--server.port=0", "--spring.application.name=myapp"]
297297
output = file("$buildDir/example-output/logging-format.txt")
298298
expectedLogging = "Started MyApplication in "
299299
normalizeTomcatPort()

spring-boot-project/spring-boot-docs/src/docs/asciidoc/features/logging.adoc

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ The following items are output:
3131
* Log Level: `ERROR`, `WARN`, `INFO`, `DEBUG`, or `TRACE`.
3232
* Process ID.
3333
* A `---` separator to distinguish the start of actual log messages.
34+
* Application name: Enclosed in square brackets (logged by default only if configprop:spring.application.name[] is set)
3435
* Thread name: Enclosed in square brackets (may be truncated for console output).
3536
* Correlation ID: If tracing is enabled (not shown in the sample above)
3637
* Logger name: This is usually the source class name (often abbreviated).
@@ -39,6 +40,7 @@ The following items are output:
3940
NOTE: Logback does not have a `FATAL` level.
4041
It is mapped to `ERROR`.
4142

43+
TIP: If you have a configprop:spring.application.name[] property but don't want it logged you can set configprop:logging.include-application-name[] to `false`.
4244

4345

4446
[[features.logging.console-output]]

spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/LoggingSystemProperties.java

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
import org.springframework.core.env.PropertyResolver;
2828
import org.springframework.core.env.PropertySourcesPropertyResolver;
2929
import org.springframework.util.Assert;
30+
import org.springframework.util.StringUtils;
3031

3132
/**
3233
* Utility to set system properties that can later be used by log configuration files.
@@ -227,6 +228,7 @@ private PropertyResolver getPropertyResolver() {
227228

228229
protected void apply(LogFile logFile, PropertyResolver resolver) {
229230
String defaultCharsetName = getDefaultCharset().name();
231+
setApplicationNameSystemProperty(resolver);
230232
setSystemProperty(LoggingSystemProperty.PID, new ApplicationPid().toString());
231233
setSystemProperty(LoggingSystemProperty.CONSOLE_CHARSET, resolver, defaultCharsetName);
232234
setSystemProperty(LoggingSystemProperty.FILE_CHARSET, resolver, defaultCharsetName);
@@ -243,6 +245,16 @@ protected void apply(LogFile logFile, PropertyResolver resolver) {
243245
}
244246
}
245247

248+
private void setApplicationNameSystemProperty(PropertyResolver resolver) {
249+
if (resolver.getProperty("logging.include-application-name", Boolean.class, Boolean.TRUE)) {
250+
String applicationName = resolver.getProperty("spring.application.name");
251+
if (StringUtils.hasText(applicationName)) {
252+
setSystemProperty(LoggingSystemProperty.APPLICATION_NAME.getEnvironmentVariableName(),
253+
"[%s] ".formatted(applicationName));
254+
}
255+
}
256+
}
257+
246258
private void setSystemProperty(LoggingSystemProperty property, PropertyResolver resolver) {
247259
setSystemProperty(property, resolver, null);
248260
}

spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/LoggingSystemProperty.java

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,11 @@
2525
*/
2626
public enum LoggingSystemProperty {
2727

28+
/**
29+
* Logging system property for the application name that should be logged.
30+
*/
31+
APPLICATION_NAME("LOGGED_APPLICATION_NAME"),
32+
2833
/**
2934
* Logging system property for the process ID.
3035
*/

spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/DefaultLogbackConfiguration.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ private void defaults(LogbackConfigurator config) {
7575
config.getContext()
7676
.putProperty("CONSOLE_LOG_PATTERN", resolve(config, "${CONSOLE_LOG_PATTERN:-"
7777
+ "%clr(%d{${LOG_DATEFORMAT_PATTERN:-yyyy-MM-dd'T'HH:mm:ss.SSSXXX}}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) "
78-
+ "%clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} "
78+
+ "%clr(${PID:- }){magenta} %clr(---){faint} %clr(${LOGGED_APPLICATION_NAME:-}[%15.15t]){faint} "
7979
+ "%clr(${LOG_CORRELATION_PATTERN:-}){faint}%clr(%-40.40logger{39}){cyan} "
8080
+ "%clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}"));
8181
String defaultCharset = Charset.defaultCharset().name();
@@ -84,7 +84,7 @@ private void defaults(LogbackConfigurator config) {
8484
config.getContext().putProperty("CONSOLE_LOG_THRESHOLD", resolve(config, "${CONSOLE_LOG_THRESHOLD:-TRACE}"));
8585
config.getContext()
8686
.putProperty("FILE_LOG_PATTERN", resolve(config, "${FILE_LOG_PATTERN:-"
87-
+ "%d{${LOG_DATEFORMAT_PATTERN:-yyyy-MM-dd'T'HH:mm:ss.SSSXXX}} ${LOG_LEVEL_PATTERN:-%5p} ${PID:- } --- [%t] "
87+
+ "%d{${LOG_DATEFORMAT_PATTERN:-yyyy-MM-dd'T'HH:mm:ss.SSSXXX}} ${LOG_LEVEL_PATTERN:-%5p} ${PID:- } --- ${LOGGED_APPLICATION_NAME:-}[%t] "
8888
+ "${LOG_CORRELATION_PATTERN:-}"
8989
+ "%-40.40logger{39} : %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}"));
9090
config.getContext()

spring-boot-project/spring-boot/src/main/resources/META-INF/additional-spring-configuration-metadata.json

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,13 @@
103103
"description": "Log groups to quickly change multiple loggers at the same time. For instance, `logging.group.db=org.hibernate,org.springframework.jdbc`.",
104104
"sourceType": "org.springframework.boot.context.logging.LoggingApplicationListener"
105105
},
106+
{
107+
"name": "logging.include-application-name",
108+
"type": "java.lang.String>",
109+
"description": "Whether to include the application name in the logs.",
110+
"sourceType": "org.springframework.boot.context.logging.LoggingApplicationListener",
111+
"defaultValue": true
112+
},
106113
{
107114
"name": "logging.level",
108115
"type": "java.util.Map<java.lang.String,java.lang.String>",

spring-boot-project/spring-boot/src/main/resources/org/springframework/boot/logging/log4j2/log4j2-file.xml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,8 @@
44
<Property name="LOG_EXCEPTION_CONVERSION_WORD">%xwEx</Property>
55
<Property name="LOG_LEVEL_PATTERN">%5p</Property>
66
<Property name="LOG_DATEFORMAT_PATTERN">yyyy-MM-dd'T'HH:mm:ss.SSSXXX</Property>
7-
<Property name="CONSOLE_LOG_PATTERN">%clr{%d{${sys:LOG_DATEFORMAT_PATTERN}}}{faint} %clr{${sys:LOG_LEVEL_PATTERN}} %clr{%pid}{magenta} %clr{---}{faint} %clr{[%15.15t]}{faint} %clr{${sys:LOG_CORRELATION_PATTERN:-}}{faint}%clr{%-40.40c{1.}}{cyan} %clr{:}{faint} %m%n${sys:LOG_EXCEPTION_CONVERSION_WORD}</Property>
8-
<Property name="FILE_LOG_PATTERN">%d{${sys:LOG_DATEFORMAT_PATTERN}} ${sys:LOG_LEVEL_PATTERN} %pid --- [%t] ${sys:LOG_CORRELATION_PATTERN:-}%-40.40c{1.} : %m%n${sys:LOG_EXCEPTION_CONVERSION_WORD}</Property>
7+
<Property name="CONSOLE_LOG_PATTERN">%clr{%d{${sys:LOG_DATEFORMAT_PATTERN}}}{faint} %clr{${sys:LOG_LEVEL_PATTERN}} %clr{%pid}{magenta} %clr{---}{faint} %clr{${sys:LOGGED_APPLICATION_NAME:-}[%15.15t]}{faint} %clr{${sys:LOG_CORRELATION_PATTERN:-}}{faint}%clr{%-40.40c{1.}}{cyan} %clr{:}{faint} %m%n${sys:LOG_EXCEPTION_CONVERSION_WORD}</Property>
8+
<Property name="FILE_LOG_PATTERN">%d{${sys:LOG_DATEFORMAT_PATTERN}} ${sys:LOG_LEVEL_PATTERN} %pid --- ${sys:LOGGED_APPLICATION_NAME}[%t] ${sys:LOG_CORRELATION_PATTERN:-}%-40.40c{1.} : %m%n${sys:LOG_EXCEPTION_CONVERSION_WORD}</Property>
99
</Properties>
1010
<Appenders>
1111
<Console name="Console" target="SYSTEM_OUT" follow="true">

spring-boot-project/spring-boot/src/main/resources/org/springframework/boot/logging/log4j2/log4j2.xml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,8 @@
44
<Property name="LOG_EXCEPTION_CONVERSION_WORD">%xwEx</Property>
55
<Property name="LOG_LEVEL_PATTERN">%5p</Property>
66
<Property name="LOG_DATEFORMAT_PATTERN">yyyy-MM-dd'T'HH:mm:ss.SSSXXX</Property>
7-
<Property name="CONSOLE_LOG_PATTERN">%clr{%d{${sys:LOG_DATEFORMAT_PATTERN}}}{faint} %clr{${sys:LOG_LEVEL_PATTERN}} %clr{%pid}{magenta} %clr{---}{faint} %clr{[%15.15t]}{faint} %clr{${sys:LOG_CORRELATION_PATTERN:-}}{faint}%clr{%-40.40c{1.}}{cyan} %clr{:}{faint} %m%n${sys:LOG_EXCEPTION_CONVERSION_WORD}</Property>
8-
<Property name="FILE_LOG_PATTERN">%d{${sys:LOG_DATEFORMAT_PATTERN}} ${sys:LOG_LEVEL_PATTERN} %pid --- [%t] ${sys:LOG_CORRELATION_PATTERN:-}%-40.40c{1.} : %m%n${sys:LOG_EXCEPTION_CONVERSION_WORD}</Property>
7+
<Property name="CONSOLE_LOG_PATTERN">%clr{%d{${sys:LOG_DATEFORMAT_PATTERN}}}{faint} %clr{${sys:LOG_LEVEL_PATTERN}} %clr{%pid}{magenta} %clr{---}{faint} %clr{${sys:LOGGED_APPLICATION_NAME}[%15.15t]}{faint} %clr{${sys:LOG_CORRELATION_PATTERN:-}}{faint}%clr{%-40.40c{1.}}{cyan} %clr{:}{faint} %m%n${sys:LOG_EXCEPTION_CONVERSION_WORD}</Property>
8+
<Property name="FILE_LOG_PATTERN">%d{${sys:LOG_DATEFORMAT_PATTERN}} ${sys:LOG_LEVEL_PATTERN} %pid --- ${sys:LOGGED_APPLICATION_NAME}[%t] ${sys:LOG_CORRELATION_PATTERN:-}%-40.40c{1.} : %m%n${sys:LOG_EXCEPTION_CONVERSION_WORD}</Property>
99
</Properties>
1010
<Appenders>
1111
<Console name="Console" target="SYSTEM_OUT" follow="true">

spring-boot-project/spring-boot/src/main/resources/org/springframework/boot/logging/logback/defaults.xml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,10 @@ Default logback configuration provided for import
1010
<conversionRule conversionWord="wex" converterClass="org.springframework.boot.logging.logback.WhitespaceThrowableProxyConverter" />
1111
<conversionRule conversionWord="wEx" converterClass="org.springframework.boot.logging.logback.ExtendedWhitespaceThrowableProxyConverter" />
1212

13-
<property name="CONSOLE_LOG_PATTERN" value="${CONSOLE_LOG_PATTERN:-%clr(%d{${LOG_DATEFORMAT_PATTERN:-yyyy-MM-dd'T'HH:mm:ss.SSSXXX}}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(${LOG_CORRELATION_PATTERN:-}){faint}%clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}"/>
13+
<property name="CONSOLE_LOG_PATTERN" value="${CONSOLE_LOG_PATTERN:-%clr(%d{${LOG_DATEFORMAT_PATTERN:-yyyy-MM-dd'T'HH:mm:ss.SSSXXX}}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr(${LOGGED_APPLICATION_NAME:-}[%15.15t]){faint} %clr(${LOG_CORRELATION_PATTERN:-}){faint}%clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}"/>
1414
<property name="CONSOLE_LOG_CHARSET" value="${CONSOLE_LOG_CHARSET:-${file.encoding:-UTF-8}}"/>
1515
<property name="CONSOLE_LOG_THRESHOLD" value="${CONSOLE_LOG_THRESHOLD:-TRACE}"/>
16-
<property name="FILE_LOG_PATTERN" value="${FILE_LOG_PATTERN:-%d{${LOG_DATEFORMAT_PATTERN:-yyyy-MM-dd'T'HH:mm:ss.SSSXXX}} ${LOG_LEVEL_PATTERN:-%5p} ${PID:- } --- [%t] ${LOG_CORRELATION_PATTERN:-}%-40.40logger{39} : %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}"/>
16+
<property name="FILE_LOG_PATTERN" value="${FILE_LOG_PATTERN:-%d{${LOG_DATEFORMAT_PATTERN:-yyyy-MM-dd'T'HH:mm:ss.SSSXXX}} ${LOG_LEVEL_PATTERN:-%5p} ${PID:- } --- ${LOGGED_APPLICATION_NAME:-}[%t] ${LOG_CORRELATION_PATTERN:-}%-40.40logger{39} : %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}"/>
1717
<property name="FILE_LOG_CHARSET" value="${FILE_LOG_CHARSET:-${file.encoding:-UTF-8}}"/>
1818
<property name="FILE_LOG_THRESHOLD" value="${FILE_LOG_THRESHOLD:-TRACE}"/>
1919

spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/LoggingSystemPropertiesTests.java

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,25 @@ void defaultValueResolverIsUsed() {
136136
.isEqualTo("default correlation pattern");
137137
}
138138

139+
@Test
140+
void loggedApplicationNameWhenHasApplicationName() {
141+
new LoggingSystemProperties(new MockEnvironment().withProperty("spring.application.name", "test")).apply(null);
142+
assertThat(getSystemProperty(LoggingSystemProperty.APPLICATION_NAME)).isEqualTo("[test] ");
143+
}
144+
145+
@Test
146+
void loggedApplicationNameWhenHasNoApplicationName() {
147+
new LoggingSystemProperties(new MockEnvironment()).apply(null);
148+
assertThat(getSystemProperty(LoggingSystemProperty.APPLICATION_NAME)).isNull();
149+
}
150+
151+
@Test
152+
void loggedApplicationNameWhenApplicationNameLoggingDisabled() {
153+
new LoggingSystemProperties(new MockEnvironment().withProperty("spring.application.name", "test")
154+
.withProperty("logging.include-application-name", "false")).apply(null);
155+
assertThat(getSystemProperty(LoggingSystemProperty.APPLICATION_NAME)).isNull();
156+
}
157+
139158
private Environment environment(String key, Object value) {
140159
StandardEnvironment environment = new StandardEnvironment();
141160
environment.getPropertySources().addLast(new MapPropertySource("test", Collections.singletonMap(key, value)));

spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/Log4J2LoggingSystemTests.java

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -564,6 +564,27 @@ void correlationLoggingToConsoleWhenHasCorrelationPattern(CapturedOutput output)
564564
.contains(" [0123456789012345-01234567890123456789012345678901] ");
565565
}
566566

567+
@Test
568+
void applicationNameLoggingWhenHasApplicationName(CapturedOutput output) {
569+
this.environment.setProperty("spring.application.name", "myapp");
570+
this.loggingSystem.setStandardConfigLocations(false);
571+
this.loggingSystem.beforeInitialize();
572+
this.loggingSystem.initialize(this.initializationContext, null, null);
573+
this.logger.info("Hello world");
574+
assertThat(getLineWithText(output, "Hello world")).contains("[myapp] ");
575+
}
576+
577+
@Test
578+
void applicationNameLoggingWhenDisabled(CapturedOutput output) {
579+
this.environment.setProperty("spring.application.name", "myapp");
580+
this.environment.setProperty("logging.include-application-name", "false");
581+
this.loggingSystem.setStandardConfigLocations(false);
582+
this.loggingSystem.beforeInitialize();
583+
this.loggingSystem.initialize(this.initializationContext, null, null);
584+
this.logger.info("Hello world");
585+
assertThat(getLineWithText(output, "Hello world")).doesNotContain("myapp");
586+
}
587+
567588
private String getRelativeClasspathLocation(String fileName) {
568589
String defaultPath = ClassUtils.getPackageName(getClass());
569590
defaultPath = defaultPath.replace('.', '/');

spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/LogbackLoggingSystemTests.java

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -754,6 +754,23 @@ void correlationLoggingToConsoleWhenUsingFileConfiguration() {
754754
.contains(" [01234567890123456789012345678901-0123456789012345] ");
755755
}
756756

757+
@Test
758+
void applicationNameLoggingWhenHasApplicationName(CapturedOutput output) {
759+
this.environment.setProperty("spring.application.name", "myapp");
760+
initialize(this.initializationContext, null, null);
761+
this.logger.info("Hello world");
762+
assertThat(getLineWithText(output, "Hello world")).contains("[myapp] ");
763+
}
764+
765+
@Test
766+
void applicationNameLoggingWhenDisabled(CapturedOutput output) {
767+
this.environment.setProperty("spring.application.name", "myapp");
768+
this.environment.setProperty("logging.include-application-name", "false");
769+
initialize(this.initializationContext, null, null);
770+
this.logger.info("Hello world");
771+
assertThat(getLineWithText(output, "Hello world")).doesNotContain("myapp");
772+
}
773+
757774
private void initialize(LoggingInitializationContext context, String configLocation, LogFile logFile) {
758775
this.loggingSystem.getSystemProperties((ConfigurableEnvironment) context.getEnvironment()).apply(logFile);
759776
this.loggingSystem.beforeInitialize();

spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator-log4j2/src/main/resources/application.properties

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
spring.application.name=sample
12
spring.security.user.name=user
23
spring.security.user.password=password
34
management.endpoint.shutdown.enabled=true

spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator-log4j2/src/main/resources/log4j2.xml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
<Configuration status="WARN" monitorInterval="30">
33
<Properties>
44
<Property name="PID">????</Property>
5-
<Property name="LOG_PATTERN">%clr{%d{yyyy-MM-dd'T'HH:mm:ss.SSSXXX}}{faint} %clr{%5p} %clr{${sys:PID}}{magenta} %clr{---}{faint} %clr{[%15.15t]}{faint} %clr{%-40.40c{1.}}{cyan} %clr{:}{faint} %m%n%xwEx</Property>
5+
<Property name="LOG_PATTERN">%clr{%d{yyyy-MM-dd'T'HH:mm:ss.SSSXXX}}{faint} %clr{%5p} %clr{${sys:PID}}{magenta} %clr{---}{faint} %clr{${sys:LOGGED_APPLICATION_NAME:-}[%15.15t]}{faint} %clr{%-40.40c{1.}}{cyan} %clr{:}{faint} %m%n%xwEx</Property>
66
</Properties>
77
<Appenders>
88
<Console name="Console" target="SYSTEM_OUT" follow="true">

spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/main/resources/application.properties

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
spring.application.name=sample
12
service.name=Phil
23

34
spring.security.user.name=user

0 commit comments

Comments
 (0)