Skip to content

Commit 597baf9

Browse files
committed
Polish "Optimize logger calls"
See spring-projectsgh-18710
1 parent 240b1f9 commit 597baf9

File tree

25 files changed

+87
-103
lines changed

25 files changed

+87
-103
lines changed

spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/jdbc/DataSourcePoolMetricsAutoConfiguration.java

+2-3
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@
4343
import org.springframework.boot.jdbc.DataSourceUnwrapper;
4444
import org.springframework.boot.jdbc.metadata.DataSourcePoolMetadataProvider;
4545
import org.springframework.context.annotation.Configuration;
46+
import org.springframework.core.log.LogMessage;
4647
import org.springframework.util.StringUtils;
4748

4849
/**
@@ -124,9 +125,7 @@ private void bindMetricsRegistryToHikariDataSource(HikariDataSource hikari) {
124125
hikari.setMetricsTrackerFactory(new MicrometerMetricsTrackerFactory(this.registry));
125126
}
126127
catch (Exception ex) {
127-
if (logger.isWarnEnabled()) {
128-
logger.warn("Failed to bind Hikari metrics: " + ex.getMessage());
129-
}
128+
logger.warn(LogMessage.format("Failed to bind Hikari metrics: %s", ex.getMessage()));
130129
}
131130
}
132131
}

spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/system/DiskSpaceHealthIndicator.java

+3-4
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
import org.springframework.boot.actuate.health.Health;
2626
import org.springframework.boot.actuate.health.HealthIndicator;
2727
import org.springframework.boot.actuate.health.Status;
28+
import org.springframework.core.log.LogMessage;
2829
import org.springframework.util.unit.DataSize;
2930

3031
/**
@@ -62,10 +63,8 @@ protected void doHealthCheck(Health.Builder builder) throws Exception {
6263
builder.up();
6364
}
6465
else {
65-
if (logger.isWarnEnabled()) {
66-
logger.warn(String.format("Free disk space below threshold. Available: %d bytes (threshold: %s)",
67-
diskFreeInBytes, this.threshold));
68-
}
66+
logger.warn(LogMessage.format("Free disk space below threshold. Available: %d bytes (threshold: %s)",
67+
diskFreeInBytes, this.threshold));
6968
builder.down();
7069
}
7170
builder.withDetail("total", this.path.getTotalSpace()).withDetail("free", diskFreeInBytes)

spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jDataAutoConfiguration.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,7 @@ static class Neo4jWebConfiguration {
111111

112112
@Bean
113113
OpenSessionInViewInterceptor neo4jOpenSessionInViewInterceptor(Neo4jProperties properties) {
114-
if (properties.getOpenInView() == null && logger.isWarnEnabled()) {
114+
if (properties.getOpenInView() == null) {
115115
logger.warn("spring.data.neo4j.open-in-view is enabled by default."
116116
+ "Therefore, database queries may be performed during view "
117117
+ "rendering. Explicitly configure "

spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAutoConfiguration.java

+6-4
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@
4141
import org.springframework.context.annotation.Bean;
4242
import org.springframework.context.annotation.Configuration;
4343
import org.springframework.context.i18n.LocaleContextHolder;
44+
import org.springframework.core.log.LogMessage;
4445
import org.springframework.web.servlet.view.UrlBasedViewResolver;
4546
import org.springframework.web.servlet.view.groovy.GroovyMarkupConfig;
4647
import org.springframework.web.servlet.view.groovy.GroovyMarkupConfigurer;
@@ -83,10 +84,11 @@ public GroovyMarkupConfiguration(ApplicationContext applicationContext, GroovyTe
8384
public void checkTemplateLocationExists() {
8485
if (this.properties.isCheckTemplateLocation() && !isUsingGroovyAllJar()) {
8586
TemplateLocation location = new TemplateLocation(this.properties.getResourceLoaderPath());
86-
if (!location.exists(this.applicationContext) && logger.isWarnEnabled()) {
87-
logger.warn("Cannot find template location: " + location
88-
+ " (please add some templates, check your Groovy "
89-
+ "configuration, or set spring.groovy.template.check-template-location=false)");
87+
if (!location.exists(this.applicationContext)) {
88+
logger.warn(LogMessage.format(
89+
"Cannot find template location: %s (please add some templates, check your Groovy "
90+
+ "configuration, or set spring.groovy.template.check-template-location=false)",
91+
location));
9092
}
9193
}
9294
}

spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jackson/JacksonAutoConfiguration.java

+2-4
Original file line numberDiff line numberDiff line change
@@ -119,10 +119,8 @@ static class JodaDateTimeJacksonConfiguration {
119119

120120
@Bean
121121
SimpleModule jodaDateTimeSerializationModule(JacksonProperties jacksonProperties) {
122-
if (logger.isWarnEnabled()) {
123-
logger.warn("Auto-configuration of Jackson's Joda-Time integration is deprecated in favor of using "
124-
+ "java.time (JSR-310).");
125-
}
122+
logger.warn("Auto-configuration of Jackson's Joda-Time integration is deprecated in favor of using "
123+
+ "java.time (JSR-310).");
126124
SimpleModule module = new SimpleModule();
127125
JacksonJodaDateFormat jacksonJodaFormat = getJacksonJodaDateFormat(jacksonProperties);
128126
if (jacksonJodaFormat != null) {

spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceInitializerInvoker.java

+3-3
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
import org.springframework.beans.factory.ObjectProvider;
2626
import org.springframework.context.ApplicationContext;
2727
import org.springframework.context.ApplicationListener;
28+
import org.springframework.core.log.LogMessage;
2829

2930
/**
3031
* Bean to handle {@link DataSource} initialization by running {@literal schema-*.sql} on
@@ -76,9 +77,8 @@ private void initialize(DataSourceInitializer initializer) {
7677
}
7778
}
7879
catch (IllegalStateException ex) {
79-
if (logger.isWarnEnabled()) {
80-
logger.warn("Could not send event to complete DataSource initialization (" + ex.getMessage() + ")");
81-
}
80+
logger.warn(LogMessage.format("Could not send event to complete DataSource initialization (%s)",
81+
ex.getMessage()));
8282
}
8383
}
8484

spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/JpaBaseConfiguration.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -216,7 +216,7 @@ protected JpaWebConfiguration(JpaProperties jpaProperties) {
216216

217217
@Bean
218218
public OpenEntityManagerInViewInterceptor openEntityManagerInViewInterceptor() {
219-
if (this.jpaProperties.getOpenInView() == null && logger.isWarnEnabled()) {
219+
if (this.jpaProperties.getOpenInView() == null) {
220220
logger.warn("spring.jpa.open-in-view is enabled by default. "
221221
+ "Therefore, database queries may be performed during view "
222222
+ "rendering. Explicitly configure spring.jpa.open-in-view to disable this warning");

spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/error/AbstractErrorWebExceptionHandler.java

+4-3
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@
3434
import org.springframework.context.ApplicationContext;
3535
import org.springframework.core.NestedExceptionUtils;
3636
import org.springframework.core.io.Resource;
37+
import org.springframework.core.log.LogMessage;
3738
import org.springframework.http.HttpLogging;
3839
import org.springframework.http.HttpStatus;
3940
import org.springframework.http.codec.HttpMessageReader;
@@ -287,9 +288,9 @@ protected void logError(ServerRequest request, ServerResponse response, Throwabl
287288
logger.debug(request.exchange().getLogPrefix() + formatError(throwable, request));
288289
}
289290
if (HttpStatus.resolve(response.rawStatusCode()) != null
290-
&& response.statusCode().equals(HttpStatus.INTERNAL_SERVER_ERROR) && logger.isErrorEnabled()) {
291-
logger.error(request.exchange().getLogPrefix() + "500 Server Error for " + formatRequest(request),
292-
throwable);
291+
&& response.statusCode().equals(HttpStatus.INTERNAL_SERVER_ERROR)) {
292+
logger.error(LogMessage.of(() -> String.format("%s 500 Server Error for %s",
293+
request.exchange().getLogPrefix(), formatRequest(request))), throwable);
293294
}
294295
}
295296

spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/OptionalLiveReloadServer.java

+2-3
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121

2222
import org.springframework.beans.factory.InitializingBean;
2323
import org.springframework.boot.devtools.livereload.LiveReloadServer;
24+
import org.springframework.core.log.LogMessage;
2425

2526
/**
2627
* Manages an optional {@link LiveReloadServer}. The {@link LiveReloadServer} may
@@ -54,9 +55,7 @@ void startServer() throws Exception {
5455
if (!this.server.isStarted()) {
5556
this.server.start();
5657
}
57-
if (logger.isInfoEnabled()) {
58-
logger.info("LiveReload server is running on port " + this.server.getPort());
59-
}
58+
logger.info(LogMessage.format("LiveReload server is running on port %s", this.server.getPort()));
6059
}
6160
catch (Exception ex) {
6261
logger.warn("Unable to start LiveReload server");

spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/RemoteDevToolsAutoConfiguration.java

+2-3
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@
4848
import org.springframework.context.annotation.Conditional;
4949
import org.springframework.context.annotation.Configuration;
5050
import org.springframework.context.annotation.Import;
51+
import org.springframework.core.log.LogMessage;
5152
import org.springframework.http.server.ServerHttpRequest;
5253

5354
/**
@@ -126,9 +127,7 @@ UrlHandlerMapper remoteRestartHandlerMapper(HttpRestartServer server, ServerProp
126127
RemoteDevToolsProperties remote = properties.getRemote();
127128
String servletContextPath = (servlet.getContextPath() != null) ? servlet.getContextPath() : "";
128129
String url = servletContextPath + remote.getContextPath() + "/restart";
129-
if (logger.isWarnEnabled()) {
130-
logger.warn("Listening for remote restart updates on " + url);
131-
}
130+
logger.warn(LogMessage.format("Listening for remote restart updates on %s", url));
132131
Handler handler = new HttpRestartServerHandler(server);
133132
return new UrlHandlerMapper(url, handler);
134133
}

spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/classpath/ClassPathFolders.java

+3-6
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
import org.apache.commons.logging.Log;
2727
import org.apache.commons.logging.LogFactory;
2828

29+
import org.springframework.core.log.LogMessage;
2930
import org.springframework.util.ResourceUtils;
3031

3132
/**
@@ -58,12 +59,8 @@ private void addUrl(URL url) {
5859
this.folders.add(ResourceUtils.getFile(url));
5960
}
6061
catch (Exception ex) {
61-
if (logger.isWarnEnabled()) {
62-
logger.warn("Unable to get classpath URL " + url);
63-
}
64-
if (logger.isTraceEnabled()) {
65-
logger.trace("Unable to get classpath URL " + url, ex);
66-
}
62+
logger.warn(LogMessage.format("Unable to get classpath URL %s", url));
63+
logger.trace(LogMessage.format("Unable to get classpath URL ", url), ex);
6764
}
6865
}
6966
}

spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/env/DevToolsPropertyDefaultsPostProcessor.java

+7-6
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232
import org.springframework.core.env.ConfigurableEnvironment;
3333
import org.springframework.core.env.Environment;
3434
import org.springframework.core.env.MapPropertySource;
35+
import org.springframework.core.log.LogMessage;
3536
import org.springframework.util.ClassUtils;
3637

3738
/**
@@ -80,14 +81,14 @@ public class DevToolsPropertyDefaultsPostProcessor implements EnvironmentPostPro
8081
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
8182
if (DevToolsEnablementDeducer.shouldEnable(Thread.currentThread()) && isLocalApplication(environment)) {
8283
if (canAddProperties(environment)) {
83-
if (logger.isInfoEnabled()) {
84-
logger.info("Devtools property defaults active! Set '" + ENABLED + "' to 'false' to disable");
85-
}
84+
logger.info(LogMessage.format("Devtools property defaults active! Set '%s' to 'false' to disable",
85+
ENABLED));
8686
environment.getPropertySources().addLast(new MapPropertySource("devtools", PROPERTIES));
8787
}
88-
if (isWebApplication(environment) && !environment.containsProperty(WEB_LOGGING) && logger.isInfoEnabled()) {
89-
logger.info("For additional web related logging consider setting the '" + WEB_LOGGING
90-
+ "' property to 'DEBUG'");
88+
if (isWebApplication(environment) && !environment.containsProperty(WEB_LOGGING)) {
89+
logger.info(LogMessage.format(
90+
"For additional web related logging consider setting the '%s' property to 'DEBUG'",
91+
WEB_LOGGING));
9192
}
9293
}
9394
}

spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/client/ClassPathChangeUploader.java

+5-8
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@
3838
import org.springframework.boot.devtools.restart.classloader.ClassLoaderFile.Kind;
3939
import org.springframework.boot.devtools.restart.classloader.ClassLoaderFiles;
4040
import org.springframework.context.ApplicationListener;
41+
import org.springframework.core.log.LogMessage;
4142
import org.springframework.http.HttpHeaders;
4243
import org.springframework.http.HttpMethod;
4344
import org.springframework.http.HttpStatus;
@@ -114,10 +115,8 @@ private void performUpload(ClassLoaderFiles classLoaderFiles, byte[] bytes) thro
114115
return;
115116
}
116117
catch (SocketException ex) {
117-
if (logger.isWarnEnabled()) {
118-
logger.warn("A failure occurred when uploading to " + this.uri
119-
+ ". Upload will be retried in 2 seconds");
120-
}
118+
logger.warn(LogMessage.format(
119+
"A failure occurred when uploading to %s. Upload will be retried in 2 seconds", this.uri));
121120
logger.debug("Upload failure", ex);
122121
Thread.sleep(2000);
123122
}
@@ -130,10 +129,8 @@ private void performUpload(ClassLoaderFiles classLoaderFiles, byte[] bytes) thro
130129
}
131130

132131
private void logUpload(ClassLoaderFiles classLoaderFiles) {
133-
if (logger.isInfoEnabled()) {
134-
int size = classLoaderFiles.size();
135-
logger.info("Uploaded " + size + " class " + ((size != 1) ? "resources" : "resource"));
136-
}
132+
int size = classLoaderFiles.size();
133+
logger.info(LogMessage.format("Uploaded %s class %s", size, (size != 1) ? "resources" : "resource"));
137134
}
138135

139136
private byte[] serialize(ClassLoaderFiles classLoaderFiles) throws IOException {

spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/client/RemoteClientConfiguration.java

+5-3
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@
5353
import org.springframework.context.annotation.Bean;
5454
import org.springframework.context.annotation.Configuration;
5555
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
56+
import org.springframework.core.log.LogMessage;
5657
import org.springframework.http.client.ClientHttpRequestFactory;
5758
import org.springframework.http.client.ClientHttpRequestInterceptor;
5859
import org.springframework.http.client.InterceptingClientHttpRequestFactory;
@@ -118,9 +119,10 @@ private void logWarnings() {
118119
if (!remoteProperties.getRestart().isEnabled()) {
119120
logger.warn("Remote restart is disabled.");
120121
}
121-
if (!this.remoteUrl.startsWith("https://") && logger.isWarnEnabled()) {
122-
logger.warn("The connection to " + this.remoteUrl
123-
+ " is insecure. You should use a URL starting with 'https://'.");
122+
if (!this.remoteUrl.startsWith("https://")) {
123+
logger.warn(LogMessage.format(
124+
"The connection to %s is insecure. You should use a URL starting with 'https://'.",
125+
this.remoteUrl));
124126
}
125127
}
126128

spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/ChangeableUrls.java

+4-3
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@
3737

3838
import org.springframework.boot.devtools.logger.DevToolsLogFactory;
3939
import org.springframework.boot.devtools.settings.DevToolsSettings;
40+
import org.springframework.core.log.LogMessage;
4041
import org.springframework.util.StringUtils;
4142

4243
/**
@@ -170,10 +171,10 @@ private static List<URL> getUrlsFromManifestClassPathAttribute(URL jarUrl, JarFi
170171
throw new IllegalStateException("Class-Path attribute contains malformed URL", ex);
171172
}
172173
}
173-
if (!nonExistentEntries.isEmpty() && logger.isInfoEnabled()) {
174-
logger.info("The Class-Path manifest attribute in " + jarFile.getName()
174+
if (!nonExistentEntries.isEmpty()) {
175+
logger.info(LogMessage.of(() -> "The Class-Path manifest attribute in " + jarFile.getName()
175176
+ " referenced one or more files that do not exist: "
176-
+ StringUtils.collectionToCommaDelimitedString(nonExistentEntries));
177+
+ StringUtils.collectionToCommaDelimitedString(nonExistentEntries)));
177178
}
178179
return urls;
179180
}

spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/RestartApplicationListener.java

+3-3
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
import org.springframework.context.ApplicationEvent;
2727
import org.springframework.context.ApplicationListener;
2828
import org.springframework.core.Ordered;
29+
import org.springframework.core.log.LogMessage;
2930

3031
/**
3132
* {@link ApplicationListener} to initialize the {@link Restarter}.
@@ -73,9 +74,8 @@ private void onApplicationStartingEvent(ApplicationStartingEvent event) {
7374
Restarter.initialize(args, false, initializer, restartOnInitialize);
7475
}
7576
else {
76-
if (logger.isInfoEnabled()) {
77-
logger.info("Restart disabled due to System property '" + ENABLED_PROPERTY + "' being set to false");
78-
}
77+
logger.info(LogMessage.format("Restart disabled due to System property '%s' being set to false",
78+
ENABLED_PROPERTY));
7979
Restarter.disable();
8080
}
8181
}

spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/client/HttpTunnelConnection.java

+4-7
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@
3535

3636
import org.springframework.boot.devtools.tunnel.payload.HttpTunnelPayload;
3737
import org.springframework.boot.devtools.tunnel.payload.HttpTunnelPayloadForwarder;
38+
import org.springframework.core.log.LogMessage;
3839
import org.springframework.http.HttpMethod;
3940
import org.springframework.http.HttpStatus;
4041
import org.springframework.http.client.ClientHttpRequest;
@@ -92,9 +93,7 @@ protected HttpTunnelConnection(String url, ClientHttpRequestFactory requestFacto
9293

9394
@Override
9495
public TunnelChannel open(WritableByteChannel incomingChannel, Closeable closeable) throws Exception {
95-
if (logger.isTraceEnabled()) {
96-
logger.trace("Opening HTTP tunnel to " + this.uri);
97-
}
96+
logger.trace(LogMessage.format("Opening HTTP tunnel to %s", this.uri));
9897
return new TunnelChannel(incomingChannel, closeable);
9998
}
10099

@@ -154,10 +153,8 @@ public void run() {
154153
}
155154
catch (IOException ex) {
156155
if (ex instanceof ConnectException) {
157-
if (logger.isWarnEnabled()) {
158-
logger.warn(
159-
"Failed to connect to remote application at " + HttpTunnelConnection.this.uri);
160-
}
156+
logger.warn(LogMessage.format("Failed to connect to remote application at %s",
157+
HttpTunnelConnection.this.uri));
161158
}
162159
else {
163160
logger.trace("Unexpected connection error", ex);

spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/client/TunnelClient.java

+4-6
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@
3030
import org.apache.commons.logging.LogFactory;
3131

3232
import org.springframework.beans.factory.SmartInitializingSingleton;
33+
import org.springframework.core.log.LogMessage;
3334
import org.springframework.util.Assert;
3435

3536
/**
@@ -88,9 +89,7 @@ public int start() throws IOException {
8889
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
8990
serverSocketChannel.socket().bind(new InetSocketAddress(this.listenPort));
9091
int port = serverSocketChannel.socket().getLocalPort();
91-
if (logger.isTraceEnabled()) {
92-
logger.trace("Listening for TCP traffic to tunnel on port " + port);
93-
}
92+
logger.trace(LogMessage.format("Listening for TCP traffic to tunnel on port %s", port));
9493
this.serverThread = new ServerThread(serverSocketChannel);
9594
this.serverThread.start();
9695
return port;
@@ -146,9 +145,8 @@ public ServerThread(ServerSocketChannel serverSocketChannel) {
146145
}
147146

148147
public void close() throws IOException {
149-
if (logger.isTraceEnabled()) {
150-
logger.trace("Closing tunnel client on port " + this.serverSocketChannel.socket().getLocalPort());
151-
}
148+
logger.trace(LogMessage.format("Closing tunnel client on port %s",
149+
this.serverSocketChannel.socket().getLocalPort()));
152150
this.serverSocketChannel.close();
153151
this.acceptConnections = false;
154152
interrupt();

0 commit comments

Comments
 (0)