Skip to content

Commit db5830a

Browse files
committed
Polish logging related code
1 parent 653443a commit db5830a

File tree

15 files changed

+191
-125
lines changed

15 files changed

+191
-125
lines changed

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -149,7 +149,7 @@ private void setApplicationGroupSystemProperty(PropertyResolver resolver) {
149149
if (resolver.getProperty("logging.include-application-group", Boolean.class, Boolean.TRUE)) {
150150
String applicationGroup = resolver.getProperty("spring.application.group");
151151
if (StringUtils.hasText(applicationGroup)) {
152-
setSystemProperty(LoggingSystemProperty.LOGGED_APPLICATION_GROUP.getEnvironmentVariableName(),
152+
setSystemProperty(LoggingSystemProperty.APPLICATION_GROUP.getEnvironmentVariableName(),
153153
"[%s] ".formatted(applicationGroup));
154154
}
155155
}

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2012-2023 the original author or authors.
2+
* Copyright 2012-2024 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -33,7 +33,7 @@ public enum LoggingSystemProperty {
3333
/**
3434
* Logging system property for the application group that should be logged.
3535
*/
36-
LOGGED_APPLICATION_GROUP("LOGGED_APPLICATION_GROUP"),
36+
APPLICATION_GROUP("LOGGED_APPLICATION_GROUP"),
3737

3838
/**
3939
* Logging system property for the process ID.

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

Lines changed: 27 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2012-2023 the original author or authors.
2+
* Copyright 2012-2024 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -16,6 +16,7 @@
1616

1717
package org.springframework.boot.logging.log4j2;
1818

19+
import java.util.Arrays;
1920
import java.util.Collections;
2021
import java.util.HashMap;
2122
import java.util.List;
@@ -38,7 +39,7 @@
3839
import org.springframework.boot.ansi.AnsiStyle;
3940

4041
/**
41-
* Log4j2 {@link LogEventPatternConverter} colors output using the {@link AnsiOutput}
42+
* Log4j2 {@link LogEventPatternConverter} to color output using the {@link AnsiOutput}
4243
* class. A single option 'styling' can be provided to the converter, or if not specified
4344
* color styling will be picked based on the logging level.
4445
*
@@ -53,23 +54,10 @@ public final class ColorConverter extends LogEventPatternConverter {
5354

5455
static {
5556
Map<String, AnsiElement> ansiElements = new HashMap<>();
56-
ansiElements.put("black", AnsiColor.BLACK);
57-
ansiElements.put("white", AnsiColor.WHITE);
57+
Arrays.stream(AnsiColor.values())
58+
.filter((color) -> color != AnsiColor.DEFAULT)
59+
.forEach((color) -> ansiElements.put(color.name().toLowerCase(), color));
5860
ansiElements.put("faint", AnsiStyle.FAINT);
59-
ansiElements.put("red", AnsiColor.RED);
60-
ansiElements.put("green", AnsiColor.GREEN);
61-
ansiElements.put("yellow", AnsiColor.YELLOW);
62-
ansiElements.put("blue", AnsiColor.BLUE);
63-
ansiElements.put("magenta", AnsiColor.MAGENTA);
64-
ansiElements.put("cyan", AnsiColor.CYAN);
65-
ansiElements.put("bright_black", AnsiColor.BRIGHT_BLACK);
66-
ansiElements.put("bright_white", AnsiColor.BRIGHT_WHITE);
67-
ansiElements.put("bright_red", AnsiColor.BRIGHT_RED);
68-
ansiElements.put("bright_green", AnsiColor.BRIGHT_GREEN);
69-
ansiElements.put("bright_yellow", AnsiColor.BRIGHT_YELLOW);
70-
ansiElements.put("bright_blue", AnsiColor.BRIGHT_BLUE);
71-
ansiElements.put("bright_magenta", AnsiColor.BRIGHT_MAGENTA);
72-
ansiElements.put("bright_cyan", AnsiColor.BRIGHT_CYAN);
7361
ELEMENTS = Collections.unmodifiableMap(ansiElements);
7462
}
7563

@@ -93,27 +81,6 @@ private ColorConverter(List<PatternFormatter> formatters, AnsiElement styling) {
9381
this.styling = styling;
9482
}
9583

96-
/**
97-
* Creates a new instance of the class. Required by Log4J2.
98-
* @param config the configuration
99-
* @param options the options
100-
* @return a new instance, or {@code null} if the options are invalid
101-
*/
102-
public static ColorConverter newInstance(Configuration config, String[] options) {
103-
if (options.length < 1) {
104-
LOGGER.error("Incorrect number of options on style. Expected at least 1, received {}", options.length);
105-
return null;
106-
}
107-
if (options[0] == null) {
108-
LOGGER.error("No pattern supplied on style");
109-
return null;
110-
}
111-
PatternParser parser = PatternLayout.createPatternParser(config);
112-
List<PatternFormatter> formatters = parser.parse(options[0]);
113-
AnsiElement element = (options.length != 1) ? ELEMENTS.get(options[1]) : null;
114-
return new ColorConverter(formatters, element);
115-
}
116-
11784
@Override
11885
public boolean handlesThrowable() {
11986
for (PatternFormatter formatter : this.formatters) {
@@ -145,4 +112,25 @@ protected void appendAnsiString(StringBuilder toAppendTo, String in, AnsiElement
145112
toAppendTo.append(AnsiOutput.toString(element, in));
146113
}
147114

115+
/**
116+
* Creates a new instance of the class. Required by Log4J2.
117+
* @param config the configuration
118+
* @param options the options
119+
* @return a new instance, or {@code null} if the options are invalid
120+
*/
121+
public static ColorConverter newInstance(Configuration config, String[] options) {
122+
if (options.length < 1) {
123+
LOGGER.error("Incorrect number of options on style. Expected at least 1, received {}", options.length);
124+
return null;
125+
}
126+
if (options[0] == null) {
127+
LOGGER.error("No pattern supplied on style");
128+
return null;
129+
}
130+
PatternParser parser = PatternLayout.createPatternParser(config);
131+
List<PatternFormatter> formatters = parser.parse(options[0]);
132+
AnsiElement element = (options.length != 1) ? ELEMENTS.get(options[1]) : null;
133+
return new ColorConverter(formatters, element);
134+
}
135+
148136
}

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

Lines changed: 8 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424

2525
/**
2626
* Logback {@link ClassicConverter} to convert the
27-
* {@link LoggingSystemProperty#LOGGED_APPLICATION_GROUP APPLICATION_GROUP} into a value
27+
* {@link LoggingSystemProperty#APPLICATION_GROUP APPLICATION_GROUP} into a value
2828
* suitable for logging. Similar to Logback's {@link PropertyConverter} but a non-existent
2929
* property is logged as an empty string rather than {@code null}.
3030
*
@@ -33,19 +33,15 @@
3333
*/
3434
public class ApplicationGroupConverter extends ClassicConverter {
3535

36+
private static final String ENVIRONMENT_VARIABLE_NAME = LoggingSystemProperty.APPLICATION_GROUP
37+
.getEnvironmentVariableName();
38+
3639
@Override
3740
public String convert(ILoggingEvent event) {
38-
String applicationGroup = event.getLoggerContextVO()
39-
.getPropertyMap()
40-
.get(LoggingSystemProperty.LOGGED_APPLICATION_GROUP.getEnvironmentVariableName());
41-
if (applicationGroup == null) {
42-
applicationGroup = System
43-
.getProperty(LoggingSystemProperty.LOGGED_APPLICATION_GROUP.getEnvironmentVariableName());
44-
if (applicationGroup == null) {
45-
applicationGroup = "";
46-
}
47-
}
48-
return applicationGroup;
41+
String applicationGroup = event.getLoggerContextVO().getPropertyMap().get(ENVIRONMENT_VARIABLE_NAME);
42+
applicationGroup = (applicationGroup != null) ? applicationGroup
43+
: System.getProperty(ENVIRONMENT_VARIABLE_NAME);
44+
return (applicationGroup != null) ? applicationGroup : "";
4945
}
5046

5147
}

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

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -29,22 +29,19 @@
2929
* is logged as an empty string rather than {@code null}.
3030
*
3131
* @author Andy Wilkinson
32+
* @author Phillip Webb
3233
* @since 3.2.4
3334
*/
3435
public class ApplicationNameConverter extends ClassicConverter {
3536

37+
private static final String ENVIRONMENT_VARIABLE_NAME = LoggingSystemProperty.APPLICATION_NAME
38+
.getEnvironmentVariableName();
39+
3640
@Override
3741
public String convert(ILoggingEvent event) {
38-
String applicationName = event.getLoggerContextVO()
39-
.getPropertyMap()
40-
.get(LoggingSystemProperty.APPLICATION_NAME.getEnvironmentVariableName());
41-
if (applicationName == null) {
42-
applicationName = System.getProperty(LoggingSystemProperty.APPLICATION_NAME.getEnvironmentVariableName());
43-
if (applicationName == null) {
44-
applicationName = "";
45-
}
46-
}
47-
return applicationName;
42+
String applicationName = event.getLoggerContextVO().getPropertyMap().get(ENVIRONMENT_VARIABLE_NAME);
43+
applicationName = (applicationName != null) ? applicationName : System.getProperty(ENVIRONMENT_VARIABLE_NAME);
44+
return (applicationName != null) ? applicationName : "";
4845
}
4946

5047
}

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

Lines changed: 22 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2012-2023 the original author or authors.
2+
* Copyright 2012-2024 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -16,6 +16,7 @@
1616

1717
package org.springframework.boot.logging.logback;
1818

19+
import java.util.Arrays;
1920
import java.util.Collections;
2021
import java.util.HashMap;
2122
import java.util.Map;
@@ -30,9 +31,9 @@
3031
import org.springframework.boot.ansi.AnsiStyle;
3132

3233
/**
33-
* Logback {@link CompositeConverter} colors output using the {@link AnsiOutput} class. A
34-
* single 'color' option can be provided to the converter, or if not specified color will
35-
* be picked based on the logging level.
34+
* Logback {@link CompositeConverter} to color output using the {@link AnsiOutput} class.
35+
* A single 'color' option can be provided to the converter, or if not specified color
36+
* will be picked based on the logging level.
3637
*
3738
* @author Phillip Webb
3839
* @since 1.0.0
@@ -43,23 +44,10 @@ public class ColorConverter extends CompositeConverter<ILoggingEvent> {
4344

4445
static {
4546
Map<String, AnsiElement> ansiElements = new HashMap<>();
46-
ansiElements.put("black", AnsiColor.BLACK);
47-
ansiElements.put("white", AnsiColor.WHITE);
47+
Arrays.stream(AnsiColor.values())
48+
.filter((color) -> color != AnsiColor.DEFAULT)
49+
.forEach((color) -> ansiElements.put(color.name().toLowerCase(), color));
4850
ansiElements.put("faint", AnsiStyle.FAINT);
49-
ansiElements.put("red", AnsiColor.RED);
50-
ansiElements.put("green", AnsiColor.GREEN);
51-
ansiElements.put("yellow", AnsiColor.YELLOW);
52-
ansiElements.put("blue", AnsiColor.BLUE);
53-
ansiElements.put("magenta", AnsiColor.MAGENTA);
54-
ansiElements.put("cyan", AnsiColor.CYAN);
55-
ansiElements.put("bright_black", AnsiColor.BRIGHT_BLACK);
56-
ansiElements.put("bright_white", AnsiColor.BRIGHT_WHITE);
57-
ansiElements.put("bright_red", AnsiColor.BRIGHT_RED);
58-
ansiElements.put("bright_green", AnsiColor.BRIGHT_GREEN);
59-
ansiElements.put("bright_yellow", AnsiColor.BRIGHT_YELLOW);
60-
ansiElements.put("bright_blue", AnsiColor.BRIGHT_BLUE);
61-
ansiElements.put("bright_magenta", AnsiColor.BRIGHT_MAGENTA);
62-
ansiElements.put("bright_cyan", AnsiColor.BRIGHT_CYAN);
6351
ELEMENTS = Collections.unmodifiableMap(ansiElements);
6452
}
6553

@@ -74,17 +62,26 @@ public class ColorConverter extends CompositeConverter<ILoggingEvent> {
7462

7563
@Override
7664
protected String transform(ILoggingEvent event, String in) {
77-
AnsiElement element = ELEMENTS.get(getFirstOption());
78-
if (element == null) {
65+
AnsiElement color = ELEMENTS.get(getFirstOption());
66+
if (color == null) {
7967
// Assume highlighting
80-
element = LEVELS.get(event.getLevel().toInteger());
81-
element = (element != null) ? element : AnsiColor.GREEN;
68+
color = LEVELS.get(event.getLevel().toInteger());
69+
color = (color != null) ? color : AnsiColor.GREEN;
8270
}
83-
return toAnsiString(in, element);
71+
return toAnsiString(in, color);
8472
}
8573

8674
protected String toAnsiString(String in, AnsiElement element) {
8775
return AnsiOutput.toString(element, in);
8876
}
8977

78+
static String getName(AnsiElement element) {
79+
return ELEMENTS.entrySet()
80+
.stream()
81+
.filter((entry) -> entry.getValue().equals(element))
82+
.map(Map.Entry::getKey)
83+
.findFirst()
84+
.orElseThrow();
85+
}
86+
9087
}

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

Lines changed: 53 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,9 @@
3030
import ch.qos.logback.core.util.FileSize;
3131
import ch.qos.logback.core.util.OptionHelper;
3232

33+
import org.springframework.boot.ansi.AnsiColor;
34+
import org.springframework.boot.ansi.AnsiElement;
35+
import org.springframework.boot.ansi.AnsiStyle;
3336
import org.springframework.boot.logging.LogFile;
3437

3538
/**
@@ -47,6 +50,25 @@
4750
*/
4851
class DefaultLogbackConfiguration {
4952

53+
private static String DEFAULT_CHARSET = Charset.defaultCharset().name();
54+
55+
private static String NAME_AND_GROUP = "%applicationName%applicationGroup";
56+
57+
private static String DATETIME = "%d{${LOG_DATEFORMAT_PATTERN:-yyyy-MM-dd'T'HH:mm:ss.SSSXXX}}";
58+
59+
private static String DEFAULT_CONSOLE_LOG_PATTERN = faint(DATETIME) + " "
60+
+ colorByLevel("${LOG_LEVEL_PATTERN:-%5p}") + " " + magenta("${PID:-}") + " "
61+
+ faint("--- " + NAME_AND_GROUP + "[%15.15t] ${LOG_CORRELATION_PATTERN:-}") + cyan("%-40.40logger{39}")
62+
+ " " + faint(":") + " %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}";
63+
64+
static final String CONSOLE_LOG_PATTERN = "${CONSOLE_LOG_PATTERN:-" + DEFAULT_CONSOLE_LOG_PATTERN;
65+
66+
private static String DEFAULT_FILE_LOG_PATTERN = DATETIME + " ${LOG_LEVEL_PATTERN:-%5p} ${PID:-} --- "
67+
+ NAME_AND_GROUP + "[%t] ${LOG_CORRELATION_PATTERN:-}"
68+
+ "%-40.40logger{39} : %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}";
69+
70+
static final String FILE_LOG_PATTERN = "${FILE_LOG_PATTERN:-" + DEFAULT_FILE_LOG_PATTERN;
71+
5072
private final LogFile logFile;
5173

5274
DefaultLogbackConfiguration(LogFile logFile) {
@@ -74,32 +96,24 @@ private void defaults(LogbackConfigurator config) {
7496
config.conversionRule("correlationId", CorrelationIdConverter.class);
7597
config.conversionRule("wex", WhitespaceThrowableProxyConverter.class);
7698
config.conversionRule("wEx", ExtendedWhitespaceThrowableProxyConverter.class);
77-
config.getContext()
78-
.putProperty("CONSOLE_LOG_PATTERN", resolve(config, "${CONSOLE_LOG_PATTERN:-"
79-
+ "%clr(%d{${LOG_DATEFORMAT_PATTERN:-yyyy-MM-dd'T'HH:mm:ss.SSSXXX}}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) "
80-
+ "%clr(${PID:- }){magenta} %clr(---){faint} %clr(%applicationName%applicationGroup[%15.15t]){faint} "
81-
+ "%clr(${LOG_CORRELATION_PATTERN:-}){faint}%clr(%-40.40logger{39}){cyan} "
82-
+ "%clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}"));
83-
String defaultCharset = Charset.defaultCharset().name();
84-
config.getContext()
85-
.putProperty("CONSOLE_LOG_CHARSET", resolve(config, "${CONSOLE_LOG_CHARSET:-" + defaultCharset + "}"));
86-
config.getContext().putProperty("CONSOLE_LOG_THRESHOLD", resolve(config, "${CONSOLE_LOG_THRESHOLD:-TRACE}"));
87-
config.getContext()
88-
.putProperty("FILE_LOG_PATTERN", resolve(config, "${FILE_LOG_PATTERN:-"
89-
+ "%d{${LOG_DATEFORMAT_PATTERN:-yyyy-MM-dd'T'HH:mm:ss.SSSXXX}} ${LOG_LEVEL_PATTERN:-%5p} ${PID:- } --- %applicationName%applicationGroup[%t] "
90-
+ "${LOG_CORRELATION_PATTERN:-}"
91-
+ "%-40.40logger{39} : %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}"));
92-
config.getContext()
93-
.putProperty("FILE_LOG_CHARSET", resolve(config, "${FILE_LOG_CHARSET:-" + defaultCharset + "}"));
94-
config.getContext().putProperty("FILE_LOG_THRESHOLD", resolve(config, "${FILE_LOG_THRESHOLD:-TRACE}"));
99+
putProperty(config, "CONSOLE_LOG_PATTERN", CONSOLE_LOG_PATTERN);
100+
putProperty(config, "CONSOLE_LOG_CHARSET", "${CONSOLE_LOG_CHARSET:-" + DEFAULT_CHARSET + "}");
101+
putProperty(config, "CONSOLE_LOG_THRESHOLD", "${CONSOLE_LOG_THRESHOLD:-TRACE}");
102+
putProperty(config, "FILE_LOG_PATTERN", FILE_LOG_PATTERN);
103+
putProperty(config, "FILE_LOG_CHARSET", "${FILE_LOG_CHARSET:-" + DEFAULT_CHARSET + "}");
104+
putProperty(config, "FILE_LOG_THRESHOLD", "${FILE_LOG_THRESHOLD:-TRACE}");
95105
config.logger("org.apache.catalina.startup.DigesterFactory", Level.ERROR);
96106
config.logger("org.apache.catalina.util.LifecycleBase", Level.ERROR);
97107
config.logger("org.apache.coyote.http11.Http11NioProtocol", Level.WARN);
98108
config.logger("org.apache.sshd.common.util.SecurityUtils", Level.WARN);
99109
config.logger("org.apache.tomcat.util.net.NioSelectorPool", Level.WARN);
100110
config.logger("org.eclipse.jetty.util.component.AbstractLifeCycle", Level.ERROR);
101111
config.logger("org.hibernate.validator.internal.util.Version", Level.WARN);
102-
config.logger("org.springframework.boot.actuate.endpoint.jmx", Level.WARN);
112+
config.logger("org.springframework.boot.actuate.endpoint.jmx", Level.WARN);// @formatter:on
113+
}
114+
115+
void putProperty(LogbackConfigurator config, String name, String val) {
116+
config.getContext().putProperty(name, resolve(config, val));
103117
}
104118

105119
private Appender<ILoggingEvent> consoleAppender(LogbackConfigurator config) {
@@ -174,4 +188,24 @@ private String resolve(LogbackConfigurator config, String val) {
174188
}
175189
}
176190

191+
private static String faint(String value) {
192+
return color(value, AnsiStyle.FAINT);
193+
}
194+
195+
private static String cyan(String value) {
196+
return color(value, AnsiColor.CYAN);
197+
}
198+
199+
private static String magenta(String value) {
200+
return color(value, AnsiColor.MAGENTA);
201+
}
202+
203+
private static String colorByLevel(String value) {
204+
return "%clr(" + value + "){}";
205+
}
206+
207+
private static String color(String value, AnsiElement ansiElement) {
208+
return "%clr(" + value + "){" + ColorConverter.getName(ansiElement) + "}";
209+
}
210+
177211
}

0 commit comments

Comments
 (0)