Add APPLICATION_NAME and APPLICATION_GROUP logging properties

Add `APPLICATION_NAME` and `APPLICATION_GROUP` properties that contain
verbatim values rather than formatted strings. Formatting of the values
is now handled by new `EnclosedInSquareBracketsConverter` classes for
both Logback and Log4J2.

The existing `LOGGED_APPLICATION_NAME` variable is now considered
deprecated. The `LOGGED_APPLICATION_GROUP` variable and related
logback converter have been removed since they never made it to a GA
release.

Closes gh-41444
This commit is contained in:
Phillip Webb
2024-07-10 21:22:19 -07:00
parent db5830a2e0
commit c3ad8b0521
18 changed files with 283 additions and 107 deletions

View File

@@ -117,8 +117,8 @@ public class LoggingSystemProperties {
protected void apply(LogFile logFile, PropertyResolver resolver) {
String defaultCharsetName = getDefaultCharset().name();
setApplicationNameSystemProperty(resolver);
setApplicationGroupSystemProperty(resolver);
setSystemProperty(LoggingSystemProperty.APPLICATION_NAME, resolver);
setSystemProperty(LoggingSystemProperty.APPLICATION_GROUP, resolver);
setSystemProperty(LoggingSystemProperty.PID, new ApplicationPid().toString());
setSystemProperty(LoggingSystemProperty.CONSOLE_CHARSET, resolver, defaultCharsetName);
setSystemProperty(LoggingSystemProperty.FILE_CHARSET, resolver, defaultCharsetName);
@@ -135,26 +135,6 @@ public class LoggingSystemProperties {
}
}
private void setApplicationNameSystemProperty(PropertyResolver resolver) {
if (resolver.getProperty("logging.include-application-name", Boolean.class, Boolean.TRUE)) {
String applicationName = resolver.getProperty("spring.application.name");
if (StringUtils.hasText(applicationName)) {
setSystemProperty(LoggingSystemProperty.APPLICATION_NAME.getEnvironmentVariableName(),
"[%s] ".formatted(applicationName));
}
}
}
private void setApplicationGroupSystemProperty(PropertyResolver resolver) {
if (resolver.getProperty("logging.include-application-group", Boolean.class, Boolean.TRUE)) {
String applicationGroup = resolver.getProperty("spring.application.group");
if (StringUtils.hasText(applicationGroup)) {
setSystemProperty(LoggingSystemProperty.APPLICATION_GROUP.getEnvironmentVariableName(),
"[%s] ".formatted(applicationGroup));
}
}
}
private void setSystemProperty(LoggingSystemProperty property, PropertyResolver resolver) {
setSystemProperty(property, resolver, Function.identity());
}
@@ -170,11 +150,21 @@ public class LoggingSystemProperties {
private void setSystemProperty(LoggingSystemProperty property, PropertyResolver resolver, String defaultValue,
Function<String, String> mapper) {
if (property.getIncludePropertyName() != null) {
if (!resolver.getProperty(property.getIncludePropertyName(), Boolean.class, Boolean.TRUE)) {
return;
}
}
String value = (property.getApplicationPropertyName() != null)
? resolver.getProperty(property.getApplicationPropertyName()) : null;
value = (value != null) ? value : this.defaultValueResolver.apply(property.getApplicationPropertyName());
value = (value != null) ? value : defaultValue;
setSystemProperty(property.getEnvironmentVariableName(), mapper.apply(value));
value = mapper.apply(value);
setSystemProperty(property.getEnvironmentVariableName(), value);
if (property == LoggingSystemProperty.APPLICATION_NAME && StringUtils.hasText(value)) {
// LOGGED_APPLICATION_NAME is deprecated for removal in 3.6.0
setSystemProperty("LOGGED_APPLICATION_NAME", "[%s] ".formatted(value));
}
}
private void setSystemProperty(LoggingSystemProperty property, String value) {

View File

@@ -28,12 +28,12 @@ public enum LoggingSystemProperty {
/**
* Logging system property for the application name that should be logged.
*/
APPLICATION_NAME("LOGGED_APPLICATION_NAME"),
APPLICATION_NAME("APPLICATION_NAME", "spring.application.name", "logging.include-application-name"),
/**
* Logging system property for the application group that should be logged.
*/
APPLICATION_GROUP("LOGGED_APPLICATION_GROUP"),
APPLICATION_GROUP("APPLICATION_GROUP", "spring.application.group", "logging.include-application-group"),
/**
* Logging system property for the process ID.
@@ -104,13 +104,20 @@ public enum LoggingSystemProperty {
private final String applicationPropertyName;
private final String includePropertyName;
LoggingSystemProperty(String environmentVariableName) {
this(environmentVariableName, null);
}
LoggingSystemProperty(String environmentVariableName, String applicationPropertyName) {
this(environmentVariableName, applicationPropertyName, null);
}
LoggingSystemProperty(String environmentVariableName, String applicationPropertyName, String includePropertyName) {
this.environmentVariableName = environmentVariableName;
this.applicationPropertyName = applicationPropertyName;
this.includePropertyName = includePropertyName;
}
/**
@@ -125,4 +132,8 @@ public enum LoggingSystemProperty {
return this.applicationPropertyName;
}
String getIncludePropertyName() {
return this.includePropertyName;
}
}

View File

@@ -0,0 +1,79 @@
/*
* Copyright 2012-2024 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 org.springframework.boot.logging.log4j2;
import java.util.List;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.plugins.Plugin;
import org.apache.logging.log4j.core.layout.PatternLayout;
import org.apache.logging.log4j.core.pattern.ConverterKeys;
import org.apache.logging.log4j.core.pattern.LogEventPatternConverter;
import org.apache.logging.log4j.core.pattern.PatternConverter;
import org.apache.logging.log4j.core.pattern.PatternFormatter;
import org.apache.logging.log4j.core.pattern.PatternParser;
/**
* Log4j2 {@link LogEventPatternConverter} used help format optional values that should be
* shown enclosed in square brackets.
*
* @author Phillip Webb
* @since 3.4.0
*/
@Plugin(name = "enclosedInSquareBrackets", category = PatternConverter.CATEGORY)
@ConverterKeys("esb")
public final class EnclosedInSquareBracketsConverter extends LogEventPatternConverter {
private final List<PatternFormatter> formatters;
private EnclosedInSquareBracketsConverter(List<PatternFormatter> formatters) {
super("enclosedInSquareBrackets", null);
this.formatters = formatters;
}
@Override
public void format(LogEvent event, StringBuilder toAppendTo) {
StringBuilder buf = new StringBuilder();
for (PatternFormatter formatter : this.formatters) {
formatter.format(event, buf);
}
if (buf.isEmpty()) {
return;
}
toAppendTo.append("[");
toAppendTo.append(buf);
toAppendTo.append("] ");
}
/**
* Creates a new instance of the class. Required by Log4J2.
* @param config the configuration
* @param options the options
* @return a new instance, or {@code null} if the options are invalid
*/
public static EnclosedInSquareBracketsConverter newInstance(Configuration config, String[] options) {
if (options.length < 1) {
LOGGER.error("Incorrect number of options on style. Expected at least 1, received {}", options.length);
return null;
}
PatternParser parser = PatternLayout.createPatternParser(config);
List<PatternFormatter> formatters = parser.parse(options[0]);
return new EnclosedInSquareBracketsConverter(formatters);
}
}

View File

@@ -1,47 +0,0 @@
/*
* Copyright 2012-2024 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 org.springframework.boot.logging.logback;
import ch.qos.logback.classic.pattern.ClassicConverter;
import ch.qos.logback.classic.pattern.PropertyConverter;
import ch.qos.logback.classic.spi.ILoggingEvent;
import org.springframework.boot.logging.LoggingSystemProperty;
/**
* Logback {@link ClassicConverter} to convert the
* {@link LoggingSystemProperty#APPLICATION_GROUP APPLICATION_GROUP} into a value
* suitable for logging. Similar to Logback's {@link PropertyConverter} but a non-existent
* property is logged as an empty string rather than {@code null}.
*
* @author Jakob Wanger
* @since 3.4.0
*/
public class ApplicationGroupConverter extends ClassicConverter {
private static final String ENVIRONMENT_VARIABLE_NAME = LoggingSystemProperty.APPLICATION_GROUP
.getEnvironmentVariableName();
@Override
public String convert(ILoggingEvent event) {
String applicationGroup = event.getLoggerContextVO().getPropertyMap().get(ENVIRONMENT_VARIABLE_NAME);
applicationGroup = (applicationGroup != null) ? applicationGroup
: System.getProperty(ENVIRONMENT_VARIABLE_NAME);
return (applicationGroup != null) ? applicationGroup : "";
}
}

View File

@@ -31,7 +31,10 @@ import org.springframework.boot.logging.LoggingSystemProperty;
* @author Andy Wilkinson
* @author Phillip Webb
* @since 3.2.4
* @deprecated since 3.4.0 for removal in 3.6.0 in favor of
* {@link EnclosedInSquareBracketsConverter}
*/
@Deprecated(since = "3.4.0", forRemoval = true)
public class ApplicationNameConverter extends ClassicConverter {
private static final String ENVIRONMENT_VARIABLE_NAME = LoggingSystemProperty.APPLICATION_NAME

View File

@@ -52,7 +52,7 @@ class DefaultLogbackConfiguration {
private static String DEFAULT_CHARSET = Charset.defaultCharset().name();
private static String NAME_AND_GROUP = "%applicationName%applicationGroup";
private static final String NAME_AND_GROUP = "%esb(){APPLICATION_NAME}%esb{APPLICATION_GROUP}";
private static String DATETIME = "%d{${LOG_DATEFORMAT_PATTERN:-yyyy-MM-dd'T'HH:mm:ss.SSSXXX}}";
@@ -90,10 +90,10 @@ class DefaultLogbackConfiguration {
}
private void defaults(LogbackConfigurator config) {
config.conversionRule("applicationGroup", ApplicationGroupConverter.class);
config.conversionRule("applicationName", ApplicationNameConverter.class);
deprecatedDefaults(config);
config.conversionRule("clr", ColorConverter.class);
config.conversionRule("correlationId", CorrelationIdConverter.class);
config.conversionRule("esb", EnclosedInSquareBracketsConverter.class);
config.conversionRule("wex", WhitespaceThrowableProxyConverter.class);
config.conversionRule("wEx", ExtendedWhitespaceThrowableProxyConverter.class);
putProperty(config, "CONSOLE_LOG_PATTERN", CONSOLE_LOG_PATTERN);
@@ -109,7 +109,12 @@ class DefaultLogbackConfiguration {
config.logger("org.apache.tomcat.util.net.NioSelectorPool", Level.WARN);
config.logger("org.eclipse.jetty.util.component.AbstractLifeCycle", Level.ERROR);
config.logger("org.hibernate.validator.internal.util.Version", Level.WARN);
config.logger("org.springframework.boot.actuate.endpoint.jmx", Level.WARN);// @formatter:on
config.logger("org.springframework.boot.actuate.endpoint.jmx", Level.WARN);
}
@SuppressWarnings("removal")
private void deprecatedDefaults(LogbackConfigurator config) {
config.conversionRule("applicationName", ApplicationNameConverter.class);
}
void putProperty(LogbackConfigurator config, String name, String val) {

View File

@@ -0,0 +1,48 @@
/*
* Copyright 2012-2024 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 org.springframework.boot.logging.logback;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.pattern.CompositeConverter;
import org.springframework.util.StringUtils;
/**
* Logback {@link CompositeConverter} used help format optional values that should be
* shown enclosed in square brackets.
*
* @author Phillip Webb
* @since 3.4.0
*/
public class EnclosedInSquareBracketsConverter extends CompositeConverter<ILoggingEvent> {
@Override
protected String transform(ILoggingEvent event, String in) {
in = (!StringUtils.hasLength(in)) ? resolveFromFirstOption(event) : in;
return (!StringUtils.hasLength(in)) ? "" : "[%s] ".formatted(in);
}
private String resolveFromFirstOption(ILoggingEvent event) {
String name = getFirstOption();
if (name == null) {
return null;
}
String value = event.getLoggerContextVO().getPropertyMap().get(name);
return (value != null) ? value : System.getProperty(name);
}
}

View File

@@ -44,6 +44,7 @@ class LogbackRuntimeHints implements RuntimeHintsRegistrar {
registerHintsForLogbackLoggingSystemTypeChecks(reflection, classLoader);
registerHintsForBuiltInLogbackConverters(reflection);
registerHintsForSpringBootConverters(reflection);
registerHintsForDeprecateSpringBootConverters(reflection);
}
private void registerHintsForLogbackLoggingSystemTypeChecks(ReflectionHints reflection, ClassLoader classLoader) {
@@ -58,11 +59,16 @@ class LogbackRuntimeHints implements RuntimeHintsRegistrar {
}
private void registerHintsForSpringBootConverters(ReflectionHints reflection) {
registerForPublicConstructorInvocation(reflection, ApplicationNameConverter.class,
ApplicationGroupConverter.class, ColorConverter.class, ExtendedWhitespaceThrowableProxyConverter.class,
registerForPublicConstructorInvocation(reflection, ColorConverter.class,
EnclosedInSquareBracketsConverter.class, ExtendedWhitespaceThrowableProxyConverter.class,
WhitespaceThrowableProxyConverter.class, CorrelationIdConverter.class);
}
@SuppressWarnings("removal")
private void registerHintsForDeprecateSpringBootConverters(ReflectionHints reflection) {
registerForPublicConstructorInvocation(reflection, ApplicationNameConverter.class);
}
private void registerForPublicConstructorInvocation(ReflectionHints reflection, Class<?>... classes) {
reflection.registerTypes(TypeReference.listOf(classes),
(hint) -> hint.withMembers(MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS));

View File

@@ -4,8 +4,8 @@
<Property name="LOG_EXCEPTION_CONVERSION_WORD">%xwEx</Property>
<Property name="LOG_LEVEL_PATTERN">%5p</Property>
<Property name="LOG_DATEFORMAT_PATTERN">yyyy-MM-dd'T'HH:mm:ss.SSSXXX</Property>
<Property name="CONSOLE_LOG_PATTERN">%clr{%d{${sys:LOG_DATEFORMAT_PATTERN}}}{faint} %clr{${sys:LOG_LEVEL_PATTERN}} %clr{%pid}{magenta} %clr{--- ${sys:LOGGED_APPLICATION_NAME:-}${sys:LOGGED_APPLICATION_GROUP:-}[%15.15t] ${sys:LOG_CORRELATION_PATTERN:-}}{faint}%clr{%-40.40c{1.}}{cyan} %clr{:}{faint} %m%n${sys:LOG_EXCEPTION_CONVERSION_WORD}</Property>
<Property name="FILE_LOG_PATTERN">%d{${sys:LOG_DATEFORMAT_PATTERN}} ${sys:LOG_LEVEL_PATTERN} %pid --- ${sys:LOGGED_APPLICATION_NAME:-}${sys:LOGGED_APPLICATION_GROUP:-}[%t] ${sys:LOG_CORRELATION_PATTERN:-}%-40.40c{1.} : %m%n${sys:LOG_EXCEPTION_CONVERSION_WORD}</Property>
<Property name="CONSOLE_LOG_PATTERN">%clr{%d{${sys:LOG_DATEFORMAT_PATTERN}}}{faint} %clr{${sys:LOG_LEVEL_PATTERN}} %clr{%pid}{magenta} %clr{--- %esb{${sys:APPLICATION_NAME:-}}%esb{${sys:APPLICATION_GROUP:-}}[%15.15t] ${sys:LOG_CORRELATION_PATTERN:-}}{faint}%clr{%-40.40c{1.}}{cyan} %clr{:}{faint} %m%n${sys:LOG_EXCEPTION_CONVERSION_WORD}</Property>
<Property name="FILE_LOG_PATTERN">%d{${sys:LOG_DATEFORMAT_PATTERN}} ${sys:LOG_LEVEL_PATTERN} %pid --- %esb{${sys:APPLICATION_NAME:-}}%esb{${sys:APPLICATION_GROUP:-}}[%t] ${sys:LOG_CORRELATION_PATTERN:-}%-40.40c{1.} : %m%n${sys:LOG_EXCEPTION_CONVERSION_WORD}</Property>
</Properties>
<Appenders>
<Console name="Console" target="SYSTEM_OUT" follow="true">

View File

@@ -4,8 +4,8 @@
<Property name="LOG_EXCEPTION_CONVERSION_WORD">%xwEx</Property>
<Property name="LOG_LEVEL_PATTERN">%5p</Property>
<Property name="LOG_DATEFORMAT_PATTERN">yyyy-MM-dd'T'HH:mm:ss.SSSXXX</Property>
<Property name="CONSOLE_LOG_PATTERN">%clr{%d{${sys:LOG_DATEFORMAT_PATTERN}}}{faint} %clr{${sys:LOG_LEVEL_PATTERN}} %clr{%pid}{magenta} %clr{--- ${sys:LOGGED_APPLICATION_NAME:-}${sys:LOGGED_APPLICATION_GROUP:-}[%15.15t] ${sys:LOG_CORRELATION_PATTERN:-}}{faint}%clr{%-40.40c{1.}}{cyan} %clr{:}{faint} %m%n${sys:LOG_EXCEPTION_CONVERSION_WORD}</Property>
<Property name="FILE_LOG_PATTERN">%d{${sys:LOG_DATEFORMAT_PATTERN}} ${sys:LOG_LEVEL_PATTERN} %pid --- ${sys:LOGGED_APPLICATION_NAME:-}${sys:LOGGED_APPLICATION_GROUP:-}[%t] ${sys:LOG_CORRELATION_PATTERN:-}%-40.40c{1.} : %m%n${sys:LOG_EXCEPTION_CONVERSION_WORD}</Property>
<Property name="CONSOLE_LOG_PATTERN">%clr{%d{${sys:LOG_DATEFORMAT_PATTERN}}}{faint} %clr{${sys:LOG_LEVEL_PATTERN}} %clr{%pid}{magenta} %clr{--- %esb{${sys:APPLICATION_NAME:-}}%esb{${sys:APPLICATION_GROUP:-}}[%15.15t] ${sys:LOG_CORRELATION_PATTERN:-}}{faint}%clr{%-40.40c{1.}}{cyan} %clr{:}{faint} %m%n${sys:LOG_EXCEPTION_CONVERSION_WORD}</Property>
<Property name="FILE_LOG_PATTERN">%d{${sys:LOG_DATEFORMAT_PATTERN}} ${sys:LOG_LEVEL_PATTERN} %pid --- %esb{${sys:APPLICATION_NAME:-}}%esb{${sys:APPLICATION_GROUP:-}}[%t] ${sys:LOG_CORRELATION_PATTERN:-}%-40.40c{1.} : %m%n${sys:LOG_EXCEPTION_CONVERSION_WORD}</Property>
</Properties>
<Appenders>
<Console name="Console" target="SYSTEM_OUT" follow="true">

View File

@@ -5,17 +5,17 @@ Default logback configuration provided for import
-->
<included>
<conversionRule conversionWord="applicationGroup" converterClass="org.springframework.boot.logging.logback.ApplicationGroupConverter" />
<conversionRule conversionWord="applicationName" converterClass="org.springframework.boot.logging.logback.ApplicationNameConverter" />
<conversionRule conversionWord="clr" converterClass="org.springframework.boot.logging.logback.ColorConverter" />
<conversionRule conversionWord="correlationId" converterClass="org.springframework.boot.logging.logback.CorrelationIdConverter" />
<conversionRule conversionWord="esb" converterClass="org.springframework.boot.logging.logback.EnclosedInSquareBracketsConverter" />
<conversionRule conversionWord="wex" converterClass="org.springframework.boot.logging.logback.WhitespaceThrowableProxyConverter" />
<conversionRule conversionWord="wEx" converterClass="org.springframework.boot.logging.logback.ExtendedWhitespaceThrowableProxyConverter" />
<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(%applicationName%applicationGroup[%15.15t]){faint} %clr(${LOG_CORRELATION_PATTERN:-}){faint}%clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}"/>
<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(--- %esb(){APPLICATION_NAME}%esb{APPLICATION_GROUP}[%15.15t] ${LOG_CORRELATION_PATTERN:-}){faint}%clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}"/>
<property name="CONSOLE_LOG_CHARSET" value="${CONSOLE_LOG_CHARSET:-${file.encoding:-UTF-8}}"/>
<property name="CONSOLE_LOG_THRESHOLD" value="${CONSOLE_LOG_THRESHOLD:-TRACE}"/>
<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(--- %applicationName%applicationGroup[%15.15t] ${LOG_CORRELATION_PATTERN:-}){faint}%clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}"/>
<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:-} --- %esb(){APPLICATION_NAME}%esb{APPLICATION_GROUP}[%t] ${LOG_CORRELATION_PATTERN:-}%-40.40logger{39} : %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}"/>
<property name="FILE_LOG_CHARSET" value="${FILE_LOG_CHARSET:-${file.encoding:-UTF-8}}"/>
<property name="FILE_LOG_THRESHOLD" value="${FILE_LOG_THRESHOLD:-TRACE}"/>

View File

@@ -49,6 +49,7 @@ class LoggingSystemPropertiesTests {
for (LoggingSystemProperty property : LoggingSystemProperty.values()) {
System.getProperties().remove(property.getEnvironmentVariableName());
}
System.getProperties().remove("LOGGED_APPLICATION_NAME");
this.systemPropertyNames = new HashSet<>(System.getProperties().keySet());
}
@@ -140,7 +141,7 @@ class LoggingSystemPropertiesTests {
@Test
void loggedApplicationNameWhenHasApplicationName() {
new LoggingSystemProperties(new MockEnvironment().withProperty("spring.application.name", "test")).apply(null);
assertThat(getSystemProperty(LoggingSystemProperty.APPLICATION_NAME)).isEqualTo("[test] ");
assertThat(getSystemProperty(LoggingSystemProperty.APPLICATION_NAME)).isEqualTo("test");
}
@Test
@@ -156,10 +157,16 @@ class LoggingSystemPropertiesTests {
assertThat(getSystemProperty(LoggingSystemProperty.APPLICATION_NAME)).isNull();
}
@Test
void legacyLoggedApplicationNameWhenHasApplicationName() {
new LoggingSystemProperties(new MockEnvironment().withProperty("spring.application.name", "test")).apply(null);
assertThat(System.getProperty("LOGGED_APPLICATION_NAME")).isEqualTo("[test] ");
}
@Test
void loggedApplicationGroupWhenHasApplicationGroup() {
new LoggingSystemProperties(new MockEnvironment().withProperty("spring.application.group", "test")).apply(null);
assertThat(getSystemProperty(LoggingSystemProperty.APPLICATION_GROUP)).isEqualTo("[test] ");
assertThat(getSystemProperty(LoggingSystemProperty.APPLICATION_GROUP)).isEqualTo("test");
}
@Test

View File

@@ -0,0 +1,52 @@
/*
* Copyright 2012-2024 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 org.springframework.boot.logging.log4j2;
import org.junit.jupiter.api.Test;
import org.springframework.boot.logging.log4j2.ColorConverterTests.TestLogEvent;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link EnclosedInSquareBracketsConverter}.
*
* @author Phillip Webb
*/
class EnclosedInSquareBracketsConverterTests {
private TestLogEvent event;
@Test
void transformWhenEmpty() {
StringBuilder output = new StringBuilder();
newConverter("").format(this.event, output);
assertThat(output).hasToString("");
}
@Test
void transformWhenName() {
StringBuilder output = new StringBuilder();
newConverter("My Application").format(this.event, output);
assertThat(output).hasToString("[My Application] ");
}
private EnclosedInSquareBracketsConverter newConverter(String in) {
return EnclosedInSquareBracketsConverter.newInstance(null, new String[] { in });
}
}

View File

@@ -607,6 +607,7 @@ class Log4J2LoggingSystemTests extends AbstractLoggingSystemTests {
this.loggingSystem.initialize(this.initializationContext, null, null);
this.logger.info("Hello world");
assertThat(getLineWithText(output, "Hello world")).doesNotContain("${sys:LOGGED_APPLICATION_NAME}")
.doesNotContain("${sys:APPLICATION_NAME}")
.doesNotContain("myapp");
}
@@ -648,6 +649,7 @@ class Log4J2LoggingSystemTests extends AbstractLoggingSystemTests {
this.loggingSystem.initialize(this.initializationContext, null, logFile);
this.logger.info("Hello world");
assertThat(getLineWithText(file, "Hello world")).doesNotContain("${sys:LOGGED_APPLICATION_NAME}")
.doesNotContain("${sys:APPLICATION_NAME}")
.doesNotContain("myapp");
}
@@ -680,6 +682,7 @@ class Log4J2LoggingSystemTests extends AbstractLoggingSystemTests {
this.loggingSystem.initialize(this.initializationContext, null, null);
this.logger.info("Hello world");
assertThat(getLineWithText(output, "Hello world")).doesNotContain("${sys:LOGGED_APPLICATION_GROUP}")
.doesNotContain("${sys:APPLICATION_GROUP}")
.doesNotContain("myapp");
}
@@ -721,6 +724,7 @@ class Log4J2LoggingSystemTests extends AbstractLoggingSystemTests {
this.loggingSystem.initialize(this.initializationContext, null, logFile);
this.logger.info("Hello world");
assertThat(getLineWithText(file, "Hello world")).doesNotContain("${sys:LOGGED_APPLICATION_GROUP}")
.doesNotContain("${sys:APPLICATION_GROUP}")
.doesNotContain("myapp");
}

View File

@@ -32,6 +32,7 @@ import static org.assertj.core.api.Assertions.assertThat;
*
* @author Andy Wilkinson
*/
@SuppressWarnings("removal")
class ApplicationNameConverterTests {
private final ApplicationNameConverter converter;

View File

@@ -17,37 +17,53 @@
package org.springframework.boot.logging.logback;
import java.util.Collections;
import java.util.List;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.spi.LoggerContextVO;
import ch.qos.logback.classic.spi.LoggingEvent;
import org.junit.jupiter.api.Test;
import org.springframework.boot.logging.LoggingSystemProperty;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link ApplicationGroupConverter}.
* Tests for {@link EnclosedInSquareBracketsConverter}.
*
* @author Jakob Wanger
* @author Phillip Webb
* @author Andy Wilkinson
*/
class ApplicationGroupConverterTests {
class EnclosedInSquareBracketsConverterTests {
private final ApplicationGroupConverter converter;
private final EnclosedInSquareBracketsConverter converter;
private final LoggingEvent event = new LoggingEvent();
ApplicationGroupConverterTests() {
this.converter = new ApplicationGroupConverter();
EnclosedInSquareBracketsConverterTests() {
this.converter = new EnclosedInSquareBracketsConverter();
this.converter.setContext(new LoggerContext());
this.event.setLoggerContextRemoteView(
new LoggerContextVO("test", Collections.emptyMap(), System.currentTimeMillis()));
}
@Test
void whenNoLoggedApplicationGroupConvertReturnsEmptyString() {
withLoggedApplicationGroup(null, () -> {
void transformWhenNull() {
assertThat(this.converter.transform(this.event, null)).isEqualTo("");
}
@Test
void transformWhenEmpty() {
assertThat(this.converter.transform(this.event, "")).isEqualTo("");
}
@Test
void transformWhenName() {
assertThat(this.converter.transform(this.event, "My Application")).isEqualTo("[My Application] ");
}
@Test
void transformWhenEmptyFromFirstOption() {
withLoggedApplicationName("spring", null, () -> {
this.converter.setOptionList(List.of("spring"));
this.converter.start();
String converted = this.converter.convert(this.event);
assertThat(converted).isEqualTo("");
@@ -55,26 +71,27 @@ class ApplicationGroupConverterTests {
}
@Test
void whenLoggedApplicationGroupConvertReturnsIt() {
withLoggedApplicationGroup("my-application", () -> {
void transformWhenNameFromFirstOption() {
withLoggedApplicationName("spring", "boot", () -> {
this.converter.setOptionList(List.of("spring"));
this.converter.start();
String converted = this.converter.convert(this.event);
assertThat(converted).isEqualTo("my-application");
assertThat(converted).isEqualTo("[boot] ");
});
}
private void withLoggedApplicationGroup(String group, Runnable action) {
if (group == null) {
System.clearProperty(LoggingSystemProperty.APPLICATION_GROUP.getEnvironmentVariableName());
private void withLoggedApplicationName(String name, String value, Runnable action) {
if (value == null) {
System.clearProperty(name);
}
else {
System.setProperty(LoggingSystemProperty.APPLICATION_GROUP.getEnvironmentVariableName(), group);
System.setProperty(name, value);
}
try {
action.run();
}
finally {
System.clearProperty(LoggingSystemProperty.APPLICATION_GROUP.getEnvironmentVariableName());
System.clearProperty(name);
}
}

View File

@@ -1,4 +1,4 @@
spring.application.name=sample
spring.application.name=sample (test)
spring.application.group=sample-group
#logging.include-application-name=false
#logging.include-application-group=false

View File

@@ -1,4 +1,4 @@
spring.application.name=sample
spring.application.name=sample (test)
spring.application.group=sample-group
#logging.include-application-name=false
#logging.include-application-group=false