Polish "Optimize logger calls"

See gh-18710
This commit is contained in:
Phillip Webb 2019-10-23 20:44:52 -07:00
parent 240b1f9e29
commit 597baf9774
25 changed files with 87 additions and 103 deletions

View File

@ -43,6 +43,7 @@ import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.jdbc.DataSourceUnwrapper;
import org.springframework.boot.jdbc.metadata.DataSourcePoolMetadataProvider;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.log.LogMessage;
import org.springframework.util.StringUtils;
/**
@ -124,9 +125,7 @@ public class DataSourcePoolMetricsAutoConfiguration {
hikari.setMetricsTrackerFactory(new MicrometerMetricsTrackerFactory(this.registry));
}
catch (Exception ex) {
if (logger.isWarnEnabled()) {
logger.warn("Failed to bind Hikari metrics: " + ex.getMessage());
}
logger.warn(LogMessage.format("Failed to bind Hikari metrics: %s", ex.getMessage()));
}
}
}

View File

@ -25,6 +25,7 @@ import org.springframework.boot.actuate.health.AbstractHealthIndicator;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.boot.actuate.health.Status;
import org.springframework.core.log.LogMessage;
import org.springframework.util.unit.DataSize;
/**
@ -62,10 +63,8 @@ public class DiskSpaceHealthIndicator extends AbstractHealthIndicator {
builder.up();
}
else {
if (logger.isWarnEnabled()) {
logger.warn(String.format("Free disk space below threshold. Available: %d bytes (threshold: %s)",
logger.warn(LogMessage.format("Free disk space below threshold. Available: %d bytes (threshold: %s)",
diskFreeInBytes, this.threshold));
}
builder.down();
}
builder.withDetail("total", this.path.getTotalSpace()).withDetail("free", diskFreeInBytes)

View File

@ -111,7 +111,7 @@ public class Neo4jDataAutoConfiguration {
@Bean
OpenSessionInViewInterceptor neo4jOpenSessionInViewInterceptor(Neo4jProperties properties) {
if (properties.getOpenInView() == null && logger.isWarnEnabled()) {
if (properties.getOpenInView() == null) {
logger.warn("spring.data.neo4j.open-in-view is enabled by default."
+ "Therefore, database queries may be performed during view "
+ "rendering. Explicitly configure "

View File

@ -41,6 +41,7 @@ import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.core.log.LogMessage;
import org.springframework.web.servlet.view.UrlBasedViewResolver;
import org.springframework.web.servlet.view.groovy.GroovyMarkupConfig;
import org.springframework.web.servlet.view.groovy.GroovyMarkupConfigurer;
@ -83,10 +84,11 @@ public class GroovyTemplateAutoConfiguration {
public void checkTemplateLocationExists() {
if (this.properties.isCheckTemplateLocation() && !isUsingGroovyAllJar()) {
TemplateLocation location = new TemplateLocation(this.properties.getResourceLoaderPath());
if (!location.exists(this.applicationContext) && logger.isWarnEnabled()) {
logger.warn("Cannot find template location: " + location
+ " (please add some templates, check your Groovy "
+ "configuration, or set spring.groovy.template.check-template-location=false)");
if (!location.exists(this.applicationContext)) {
logger.warn(LogMessage.format(
"Cannot find template location: %s (please add some templates, check your Groovy "
+ "configuration, or set spring.groovy.template.check-template-location=false)",
location));
}
}
}

View File

@ -119,10 +119,8 @@ public class JacksonAutoConfiguration {
@Bean
SimpleModule jodaDateTimeSerializationModule(JacksonProperties jacksonProperties) {
if (logger.isWarnEnabled()) {
logger.warn("Auto-configuration of Jackson's Joda-Time integration is deprecated in favor of using "
+ "java.time (JSR-310).");
}
SimpleModule module = new SimpleModule();
JacksonJodaDateFormat jacksonJodaFormat = getJacksonJodaDateFormat(jacksonProperties);
if (jacksonJodaFormat != null) {

View File

@ -25,6 +25,7 @@ import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.core.log.LogMessage;
/**
* Bean to handle {@link DataSource} initialization by running {@literal schema-*.sql} on
@ -76,9 +77,8 @@ class DataSourceInitializerInvoker implements ApplicationListener<DataSourceSche
}
}
catch (IllegalStateException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Could not send event to complete DataSource initialization (" + ex.getMessage() + ")");
}
logger.warn(LogMessage.format("Could not send event to complete DataSource initialization (%s)",
ex.getMessage()));
}
}

View File

@ -216,7 +216,7 @@ public abstract class JpaBaseConfiguration implements BeanFactoryAware {
@Bean
public OpenEntityManagerInViewInterceptor openEntityManagerInViewInterceptor() {
if (this.jpaProperties.getOpenInView() == null && logger.isWarnEnabled()) {
if (this.jpaProperties.getOpenInView() == null) {
logger.warn("spring.jpa.open-in-view is enabled by default. "
+ "Therefore, database queries may be performed during view "
+ "rendering. Explicitly configure spring.jpa.open-in-view to disable this warning");

View File

@ -34,6 +34,7 @@ import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.context.ApplicationContext;
import org.springframework.core.NestedExceptionUtils;
import org.springframework.core.io.Resource;
import org.springframework.core.log.LogMessage;
import org.springframework.http.HttpLogging;
import org.springframework.http.HttpStatus;
import org.springframework.http.codec.HttpMessageReader;
@ -287,9 +288,9 @@ public abstract class AbstractErrorWebExceptionHandler implements ErrorWebExcept
logger.debug(request.exchange().getLogPrefix() + formatError(throwable, request));
}
if (HttpStatus.resolve(response.rawStatusCode()) != null
&& response.statusCode().equals(HttpStatus.INTERNAL_SERVER_ERROR) && logger.isErrorEnabled()) {
logger.error(request.exchange().getLogPrefix() + "500 Server Error for " + formatRequest(request),
throwable);
&& response.statusCode().equals(HttpStatus.INTERNAL_SERVER_ERROR)) {
logger.error(LogMessage.of(() -> String.format("%s 500 Server Error for %s",
request.exchange().getLogPrefix(), formatRequest(request))), throwable);
}
}

View File

@ -21,6 +21,7 @@ import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.devtools.livereload.LiveReloadServer;
import org.springframework.core.log.LogMessage;
/**
* Manages an optional {@link LiveReloadServer}. The {@link LiveReloadServer} may
@ -54,9 +55,7 @@ public class OptionalLiveReloadServer implements InitializingBean {
if (!this.server.isStarted()) {
this.server.start();
}
if (logger.isInfoEnabled()) {
logger.info("LiveReload server is running on port " + this.server.getPort());
}
logger.info(LogMessage.format("LiveReload server is running on port %s", this.server.getPort()));
}
catch (Exception ex) {
logger.warn("Unable to start LiveReload server");

View File

@ -48,6 +48,7 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.log.LogMessage;
import org.springframework.http.server.ServerHttpRequest;
/**
@ -126,9 +127,7 @@ public class RemoteDevToolsAutoConfiguration {
RemoteDevToolsProperties remote = properties.getRemote();
String servletContextPath = (servlet.getContextPath() != null) ? servlet.getContextPath() : "";
String url = servletContextPath + remote.getContextPath() + "/restart";
if (logger.isWarnEnabled()) {
logger.warn("Listening for remote restart updates on " + url);
}
logger.warn(LogMessage.format("Listening for remote restart updates on %s", url));
Handler handler = new HttpRestartServerHandler(server);
return new UrlHandlerMapper(url, handler);
}

View File

@ -26,6 +26,7 @@ import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.log.LogMessage;
import org.springframework.util.ResourceUtils;
/**
@ -58,12 +59,8 @@ public class ClassPathFolders implements Iterable<File> {
this.folders.add(ResourceUtils.getFile(url));
}
catch (Exception ex) {
if (logger.isWarnEnabled()) {
logger.warn("Unable to get classpath URL " + url);
}
if (logger.isTraceEnabled()) {
logger.trace("Unable to get classpath URL " + url, ex);
}
logger.warn(LogMessage.format("Unable to get classpath URL %s", url));
logger.trace(LogMessage.format("Unable to get classpath URL ", url), ex);
}
}
}

View File

@ -32,6 +32,7 @@ import org.springframework.core.annotation.Order;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.log.LogMessage;
import org.springframework.util.ClassUtils;
/**
@ -80,14 +81,14 @@ public class DevToolsPropertyDefaultsPostProcessor implements EnvironmentPostPro
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
if (DevToolsEnablementDeducer.shouldEnable(Thread.currentThread()) && isLocalApplication(environment)) {
if (canAddProperties(environment)) {
if (logger.isInfoEnabled()) {
logger.info("Devtools property defaults active! Set '" + ENABLED + "' to 'false' to disable");
}
logger.info(LogMessage.format("Devtools property defaults active! Set '%s' to 'false' to disable",
ENABLED));
environment.getPropertySources().addLast(new MapPropertySource("devtools", PROPERTIES));
}
if (isWebApplication(environment) && !environment.containsProperty(WEB_LOGGING) && logger.isInfoEnabled()) {
logger.info("For additional web related logging consider setting the '" + WEB_LOGGING
+ "' property to 'DEBUG'");
if (isWebApplication(environment) && !environment.containsProperty(WEB_LOGGING)) {
logger.info(LogMessage.format(
"For additional web related logging consider setting the '%s' property to 'DEBUG'",
WEB_LOGGING));
}
}
}

View File

@ -38,6 +38,7 @@ import org.springframework.boot.devtools.restart.classloader.ClassLoaderFile;
import org.springframework.boot.devtools.restart.classloader.ClassLoaderFile.Kind;
import org.springframework.boot.devtools.restart.classloader.ClassLoaderFiles;
import org.springframework.context.ApplicationListener;
import org.springframework.core.log.LogMessage;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
@ -114,10 +115,8 @@ public class ClassPathChangeUploader implements ApplicationListener<ClassPathCha
return;
}
catch (SocketException ex) {
if (logger.isWarnEnabled()) {
logger.warn("A failure occurred when uploading to " + this.uri
+ ". Upload will be retried in 2 seconds");
}
logger.warn(LogMessage.format(
"A failure occurred when uploading to %s. Upload will be retried in 2 seconds", this.uri));
logger.debug("Upload failure", ex);
Thread.sleep(2000);
}
@ -130,10 +129,8 @@ public class ClassPathChangeUploader implements ApplicationListener<ClassPathCha
}
private void logUpload(ClassLoaderFiles classLoaderFiles) {
if (logger.isInfoEnabled()) {
int size = classLoaderFiles.size();
logger.info("Uploaded " + size + " class " + ((size != 1) ? "resources" : "resource"));
}
logger.info(LogMessage.format("Uploaded %s class %s", size, (size != 1) ? "resources" : "resource"));
}
private byte[] serialize(ClassLoaderFiles classLoaderFiles) throws IOException {

View File

@ -53,6 +53,7 @@ import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.log.LogMessage;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.InterceptingClientHttpRequestFactory;
@ -118,9 +119,10 @@ public class RemoteClientConfiguration implements InitializingBean {
if (!remoteProperties.getRestart().isEnabled()) {
logger.warn("Remote restart is disabled.");
}
if (!this.remoteUrl.startsWith("https://") && logger.isWarnEnabled()) {
logger.warn("The connection to " + this.remoteUrl
+ " is insecure. You should use a URL starting with 'https://'.");
if (!this.remoteUrl.startsWith("https://")) {
logger.warn(LogMessage.format(
"The connection to %s is insecure. You should use a URL starting with 'https://'.",
this.remoteUrl));
}
}

View File

@ -37,6 +37,7 @@ import org.apache.commons.logging.Log;
import org.springframework.boot.devtools.logger.DevToolsLogFactory;
import org.springframework.boot.devtools.settings.DevToolsSettings;
import org.springframework.core.log.LogMessage;
import org.springframework.util.StringUtils;
/**
@ -170,10 +171,10 @@ final class ChangeableUrls implements Iterable<URL> {
throw new IllegalStateException("Class-Path attribute contains malformed URL", ex);
}
}
if (!nonExistentEntries.isEmpty() && logger.isInfoEnabled()) {
logger.info("The Class-Path manifest attribute in " + jarFile.getName()
if (!nonExistentEntries.isEmpty()) {
logger.info(LogMessage.of(() -> "The Class-Path manifest attribute in " + jarFile.getName()
+ " referenced one or more files that do not exist: "
+ StringUtils.collectionToCommaDelimitedString(nonExistentEntries));
+ StringUtils.collectionToCommaDelimitedString(nonExistentEntries)));
}
return urls;
}

View File

@ -26,6 +26,7 @@ import org.springframework.boot.context.event.ApplicationStartingEvent;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.Ordered;
import org.springframework.core.log.LogMessage;
/**
* {@link ApplicationListener} to initialize the {@link Restarter}.
@ -73,9 +74,8 @@ public class RestartApplicationListener implements ApplicationListener<Applicati
Restarter.initialize(args, false, initializer, restartOnInitialize);
}
else {
if (logger.isInfoEnabled()) {
logger.info("Restart disabled due to System property '" + ENABLED_PROPERTY + "' being set to false");
}
logger.info(LogMessage.format("Restart disabled due to System property '%s' being set to false",
ENABLED_PROPERTY));
Restarter.disable();
}
}

View File

@ -35,6 +35,7 @@ import org.apache.commons.logging.LogFactory;
import org.springframework.boot.devtools.tunnel.payload.HttpTunnelPayload;
import org.springframework.boot.devtools.tunnel.payload.HttpTunnelPayloadForwarder;
import org.springframework.core.log.LogMessage;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpRequest;
@ -92,9 +93,7 @@ public class HttpTunnelConnection implements TunnelConnection {
@Override
public TunnelChannel open(WritableByteChannel incomingChannel, Closeable closeable) throws Exception {
if (logger.isTraceEnabled()) {
logger.trace("Opening HTTP tunnel to " + this.uri);
}
logger.trace(LogMessage.format("Opening HTTP tunnel to %s", this.uri));
return new TunnelChannel(incomingChannel, closeable);
}
@ -154,10 +153,8 @@ public class HttpTunnelConnection implements TunnelConnection {
}
catch (IOException ex) {
if (ex instanceof ConnectException) {
if (logger.isWarnEnabled()) {
logger.warn(
"Failed to connect to remote application at " + HttpTunnelConnection.this.uri);
}
logger.warn(LogMessage.format("Failed to connect to remote application at %s",
HttpTunnelConnection.this.uri));
}
else {
logger.trace("Unexpected connection error", ex);

View File

@ -30,6 +30,7 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.core.log.LogMessage;
import org.springframework.util.Assert;
/**
@ -88,9 +89,7 @@ public class TunnelClient implements SmartInitializingSingleton {
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.socket().bind(new InetSocketAddress(this.listenPort));
int port = serverSocketChannel.socket().getLocalPort();
if (logger.isTraceEnabled()) {
logger.trace("Listening for TCP traffic to tunnel on port " + port);
}
logger.trace(LogMessage.format("Listening for TCP traffic to tunnel on port %s", port));
this.serverThread = new ServerThread(serverSocketChannel);
this.serverThread.start();
return port;
@ -146,9 +145,8 @@ public class TunnelClient implements SmartInitializingSingleton {
}
public void close() throws IOException {
if (logger.isTraceEnabled()) {
logger.trace("Closing tunnel client on port " + this.serverSocketChannel.socket().getLocalPort());
}
logger.trace(LogMessage.format("Closing tunnel client on port %s",
this.serverSocketChannel.socket().getLocalPort()));
this.serverSocketChannel.close();
this.acceptConnections = false;
interrupt();

View File

@ -28,6 +28,7 @@ import java.nio.channels.SocketChannel;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.log.LogMessage;
import org.springframework.util.Assert;
/**
@ -54,9 +55,7 @@ public class SocketTargetServerConnection implements TargetServerConnection {
@Override
public ByteChannel open(int socketTimeout) throws IOException {
SocketAddress address = new InetSocketAddress(this.portProvider.getPort());
if (logger.isTraceEnabled()) {
logger.trace("Opening tunnel connection to target server on " + address);
}
logger.trace(LogMessage.format("Opening tunnel connection to target server on %s", address));
SocketChannel channel = SocketChannel.open(address);
channel.socket().setSoTimeout(socketTimeout);
return new TimeoutAwareChannel(channel);

View File

@ -42,6 +42,7 @@ import org.springframework.boot.ansi.AnsiElement;
import org.springframework.boot.ansi.AnsiOutput;
import org.springframework.core.env.Environment;
import org.springframework.core.io.Resource;
import org.springframework.core.log.LogMessage;
import org.springframework.util.Assert;
/**
@ -78,10 +79,8 @@ public class ImageBanner implements Banner {
printBanner(environment, out);
}
catch (Throwable ex) {
if (logger.isWarnEnabled()) {
logger.warn("Image banner not printable: " + this.image + " (" + ex.getClass() + ": '" + ex.getMessage()
+ "')");
}
logger.warn(LogMessage.format("Image banner not printable: %s (%s: '%s')", this.image, ex.getClass(),
ex.getMessage()));
logger.debug("Image banner printing failure", ex);
}
finally {

View File

@ -35,6 +35,7 @@ import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertyResolver;
import org.springframework.core.env.PropertySourcesPropertyResolver;
import org.springframework.core.io.Resource;
import org.springframework.core.log.LogMessage;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;
@ -70,10 +71,8 @@ public class ResourceBanner implements Banner {
out.println(banner);
}
catch (Exception ex) {
if (logger.isWarnEnabled()) {
logger.warn("Banner not printable: " + this.resource + " (" + ex.getClass() + ": '" + ex.getMessage()
+ "')", ex);
}
logger.warn(LogMessage.format("Banner not printable: %s (%s: '%s')", this.resource, ex.getClass(),
ex.getMessage()), ex);
}
}

View File

@ -112,7 +112,8 @@ class StartupInfoLogger {
long startTime = System.currentTimeMillis();
append(message, "on ", () -> InetAddress.getLocalHost().getHostName());
long resolveTime = System.currentTimeMillis() - startTime;
if (resolveTime > HOST_NAME_RESOLVE_THRESHOLD && logger.isWarnEnabled()) {
if (resolveTime > HOST_NAME_RESOLVE_THRESHOLD) {
logger.warn(LogMessage.of(() -> {
StringBuilder warning = new StringBuilder();
warning.append("InetAddress.getLocalHost().getHostName() took ");
warning.append(resolveTime);
@ -121,9 +122,9 @@ class StartupInfoLogger {
if (System.getProperty("os.name").toLowerCase().contains("mac")) {
warning.append(" (macOS machines may need to add entries to /etc/hosts)");
}
if (logger.isWarnEnabled()) {
logger.warn(warning.append("."));
}
warning.append(".");
return warning;
}));
}
}

View File

@ -50,6 +50,7 @@ import org.springframework.core.Ordered;
import org.springframework.core.ResolvableType;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;
import org.springframework.core.log.LogMessage;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.ResourceUtils;
@ -416,9 +417,7 @@ public class LoggingApplicationListener implements GenericApplicationListener {
system.setLogLevel(name, level);
}
catch (RuntimeException ex) {
if (this.logger.isErrorEnabled()) {
this.logger.error("Cannot set level '" + level + "' for '" + name + "'");
}
this.logger.error(LogMessage.format("Cannot set level '%s' for '%s'", level, name));
}
};
}

View File

@ -77,9 +77,7 @@ final class FailureAnalyzers implements SpringBootExceptionReporter {
analyzers.add((FailureAnalyzer) constructor.newInstance());
}
catch (Throwable ex) {
if (logger.isTraceEnabled()) {
logger.trace("Failed to load " + analyzerName, ex);
}
logger.trace(LogMessage.format("Failed to load %s", analyzerName), ex);
}
}
AnnotationAwareOrderComparator.sort(analyzers);

View File

@ -25,6 +25,7 @@ import org.apache.commons.logging.LogFactory;
import org.springframework.boot.system.SystemProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.core.log.LogMessage;
import org.springframework.util.Assert;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.StringUtils;
@ -91,9 +92,7 @@ public class WebServerPortFileWriter implements ApplicationListener<WebServerIni
portFile.deleteOnExit();
}
catch (Exception ex) {
if (logger.isWarnEnabled()) {
logger.warn(String.format("Cannot create port file %s", this.file));
}
logger.warn(LogMessage.format("Cannot create port file %s", this.file));
}
}