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.DataSourceUnwrapper;
import org.springframework.boot.jdbc.metadata.DataSourcePoolMetadataProvider; import org.springframework.boot.jdbc.metadata.DataSourcePoolMetadataProvider;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.core.log.LogMessage;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
/** /**
@ -124,9 +125,7 @@ public class DataSourcePoolMetricsAutoConfiguration {
hikari.setMetricsTrackerFactory(new MicrometerMetricsTrackerFactory(this.registry)); hikari.setMetricsTrackerFactory(new MicrometerMetricsTrackerFactory(this.registry));
} }
catch (Exception ex) { catch (Exception ex) {
if (logger.isWarnEnabled()) { logger.warn(LogMessage.format("Failed to bind Hikari metrics: %s", ex.getMessage()));
logger.warn("Failed to bind Hikari metrics: " + 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.Health;
import org.springframework.boot.actuate.health.HealthIndicator; import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.boot.actuate.health.Status; import org.springframework.boot.actuate.health.Status;
import org.springframework.core.log.LogMessage;
import org.springframework.util.unit.DataSize; import org.springframework.util.unit.DataSize;
/** /**
@ -62,10 +63,8 @@ public class DiskSpaceHealthIndicator extends AbstractHealthIndicator {
builder.up(); builder.up();
} }
else { else {
if (logger.isWarnEnabled()) { logger.warn(LogMessage.format("Free disk space below threshold. Available: %d bytes (threshold: %s)",
logger.warn(String.format("Free disk space below threshold. Available: %d bytes (threshold: %s)", diskFreeInBytes, this.threshold));
diskFreeInBytes, this.threshold));
}
builder.down(); builder.down();
} }
builder.withDetail("total", this.path.getTotalSpace()).withDetail("free", diskFreeInBytes) builder.withDetail("total", this.path.getTotalSpace()).withDetail("free", diskFreeInBytes)

View File

@ -111,7 +111,7 @@ public class Neo4jDataAutoConfiguration {
@Bean @Bean
OpenSessionInViewInterceptor neo4jOpenSessionInViewInterceptor(Neo4jProperties properties) { 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." logger.warn("spring.data.neo4j.open-in-view is enabled by default."
+ "Therefore, database queries may be performed during view " + "Therefore, database queries may be performed during view "
+ "rendering. Explicitly configure " + "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.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.context.i18n.LocaleContextHolder; 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.UrlBasedViewResolver;
import org.springframework.web.servlet.view.groovy.GroovyMarkupConfig; import org.springframework.web.servlet.view.groovy.GroovyMarkupConfig;
import org.springframework.web.servlet.view.groovy.GroovyMarkupConfigurer; import org.springframework.web.servlet.view.groovy.GroovyMarkupConfigurer;
@ -83,10 +84,11 @@ public class GroovyTemplateAutoConfiguration {
public void checkTemplateLocationExists() { public void checkTemplateLocationExists() {
if (this.properties.isCheckTemplateLocation() && !isUsingGroovyAllJar()) { if (this.properties.isCheckTemplateLocation() && !isUsingGroovyAllJar()) {
TemplateLocation location = new TemplateLocation(this.properties.getResourceLoaderPath()); TemplateLocation location = new TemplateLocation(this.properties.getResourceLoaderPath());
if (!location.exists(this.applicationContext) && logger.isWarnEnabled()) { if (!location.exists(this.applicationContext)) {
logger.warn("Cannot find template location: " + location logger.warn(LogMessage.format(
+ " (please add some templates, check your Groovy " "Cannot find template location: %s (please add some templates, check your Groovy "
+ "configuration, or set spring.groovy.template.check-template-location=false)"); + "configuration, or set spring.groovy.template.check-template-location=false)",
location));
} }
} }
} }

View File

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

View File

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

View File

@ -216,7 +216,7 @@ public abstract class JpaBaseConfiguration implements BeanFactoryAware {
@Bean @Bean
public OpenEntityManagerInViewInterceptor openEntityManagerInViewInterceptor() { 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. " logger.warn("spring.jpa.open-in-view is enabled by default. "
+ "Therefore, database queries may be performed during view " + "Therefore, database queries may be performed during view "
+ "rendering. Explicitly configure spring.jpa.open-in-view to disable this warning"); + "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.context.ApplicationContext;
import org.springframework.core.NestedExceptionUtils; import org.springframework.core.NestedExceptionUtils;
import org.springframework.core.io.Resource; import org.springframework.core.io.Resource;
import org.springframework.core.log.LogMessage;
import org.springframework.http.HttpLogging; import org.springframework.http.HttpLogging;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.codec.HttpMessageReader; import org.springframework.http.codec.HttpMessageReader;
@ -287,9 +288,9 @@ public abstract class AbstractErrorWebExceptionHandler implements ErrorWebExcept
logger.debug(request.exchange().getLogPrefix() + formatError(throwable, request)); logger.debug(request.exchange().getLogPrefix() + formatError(throwable, request));
} }
if (HttpStatus.resolve(response.rawStatusCode()) != null if (HttpStatus.resolve(response.rawStatusCode()) != null
&& response.statusCode().equals(HttpStatus.INTERNAL_SERVER_ERROR) && logger.isErrorEnabled()) { && response.statusCode().equals(HttpStatus.INTERNAL_SERVER_ERROR)) {
logger.error(request.exchange().getLogPrefix() + "500 Server Error for " + formatRequest(request), logger.error(LogMessage.of(() -> String.format("%s 500 Server Error for %s",
throwable); 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.beans.factory.InitializingBean;
import org.springframework.boot.devtools.livereload.LiveReloadServer; import org.springframework.boot.devtools.livereload.LiveReloadServer;
import org.springframework.core.log.LogMessage;
/** /**
* Manages an optional {@link LiveReloadServer}. The {@link LiveReloadServer} may * Manages an optional {@link LiveReloadServer}. The {@link LiveReloadServer} may
@ -54,9 +55,7 @@ public class OptionalLiveReloadServer implements InitializingBean {
if (!this.server.isStarted()) { if (!this.server.isStarted()) {
this.server.start(); this.server.start();
} }
if (logger.isInfoEnabled()) { logger.info(LogMessage.format("LiveReload server is running on port %s", this.server.getPort()));
logger.info("LiveReload server is running on port " + this.server.getPort());
}
} }
catch (Exception ex) { catch (Exception ex) {
logger.warn("Unable to start LiveReload server"); 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.Conditional;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import; import org.springframework.context.annotation.Import;
import org.springframework.core.log.LogMessage;
import org.springframework.http.server.ServerHttpRequest; import org.springframework.http.server.ServerHttpRequest;
/** /**
@ -126,9 +127,7 @@ public class RemoteDevToolsAutoConfiguration {
RemoteDevToolsProperties remote = properties.getRemote(); RemoteDevToolsProperties remote = properties.getRemote();
String servletContextPath = (servlet.getContextPath() != null) ? servlet.getContextPath() : ""; String servletContextPath = (servlet.getContextPath() != null) ? servlet.getContextPath() : "";
String url = servletContextPath + remote.getContextPath() + "/restart"; String url = servletContextPath + remote.getContextPath() + "/restart";
if (logger.isWarnEnabled()) { logger.warn(LogMessage.format("Listening for remote restart updates on %s", url));
logger.warn("Listening for remote restart updates on " + url);
}
Handler handler = new HttpRestartServerHandler(server); Handler handler = new HttpRestartServerHandler(server);
return new UrlHandlerMapper(url, handler); 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.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.springframework.core.log.LogMessage;
import org.springframework.util.ResourceUtils; import org.springframework.util.ResourceUtils;
/** /**
@ -58,12 +59,8 @@ public class ClassPathFolders implements Iterable<File> {
this.folders.add(ResourceUtils.getFile(url)); this.folders.add(ResourceUtils.getFile(url));
} }
catch (Exception ex) { catch (Exception ex) {
if (logger.isWarnEnabled()) { logger.warn(LogMessage.format("Unable to get classpath URL %s", url));
logger.warn("Unable to get classpath URL " + url); logger.trace(LogMessage.format("Unable to get classpath URL ", url), ex);
}
if (logger.isTraceEnabled()) {
logger.trace("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.ConfigurableEnvironment;
import org.springframework.core.env.Environment; import org.springframework.core.env.Environment;
import org.springframework.core.env.MapPropertySource; import org.springframework.core.env.MapPropertySource;
import org.springframework.core.log.LogMessage;
import org.springframework.util.ClassUtils; import org.springframework.util.ClassUtils;
/** /**
@ -80,14 +81,14 @@ public class DevToolsPropertyDefaultsPostProcessor implements EnvironmentPostPro
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
if (DevToolsEnablementDeducer.shouldEnable(Thread.currentThread()) && isLocalApplication(environment)) { if (DevToolsEnablementDeducer.shouldEnable(Thread.currentThread()) && isLocalApplication(environment)) {
if (canAddProperties(environment)) { if (canAddProperties(environment)) {
if (logger.isInfoEnabled()) { logger.info(LogMessage.format("Devtools property defaults active! Set '%s' to 'false' to disable",
logger.info("Devtools property defaults active! Set '" + ENABLED + "' to 'false' to disable"); ENABLED));
}
environment.getPropertySources().addLast(new MapPropertySource("devtools", PROPERTIES)); environment.getPropertySources().addLast(new MapPropertySource("devtools", PROPERTIES));
} }
if (isWebApplication(environment) && !environment.containsProperty(WEB_LOGGING) && logger.isInfoEnabled()) { if (isWebApplication(environment) && !environment.containsProperty(WEB_LOGGING)) {
logger.info("For additional web related logging consider setting the '" + WEB_LOGGING logger.info(LogMessage.format(
+ "' property to 'DEBUG'"); "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.ClassLoaderFile.Kind;
import org.springframework.boot.devtools.restart.classloader.ClassLoaderFiles; import org.springframework.boot.devtools.restart.classloader.ClassLoaderFiles;
import org.springframework.context.ApplicationListener; import org.springframework.context.ApplicationListener;
import org.springframework.core.log.LogMessage;
import org.springframework.http.HttpHeaders; import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod; import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
@ -114,10 +115,8 @@ public class ClassPathChangeUploader implements ApplicationListener<ClassPathCha
return; return;
} }
catch (SocketException ex) { catch (SocketException ex) {
if (logger.isWarnEnabled()) { logger.warn(LogMessage.format(
logger.warn("A failure occurred when uploading to " + this.uri "A failure occurred when uploading to %s. Upload will be retried in 2 seconds", this.uri));
+ ". Upload will be retried in 2 seconds");
}
logger.debug("Upload failure", ex); logger.debug("Upload failure", ex);
Thread.sleep(2000); Thread.sleep(2000);
} }
@ -130,10 +129,8 @@ public class ClassPathChangeUploader implements ApplicationListener<ClassPathCha
} }
private void logUpload(ClassLoaderFiles classLoaderFiles) { private void logUpload(ClassLoaderFiles classLoaderFiles) {
if (logger.isInfoEnabled()) { int size = classLoaderFiles.size();
int size = classLoaderFiles.size(); logger.info(LogMessage.format("Uploaded %s class %s", size, (size != 1) ? "resources" : "resource"));
logger.info("Uploaded " + size + " class " + ((size != 1) ? "resources" : "resource"));
}
} }
private byte[] serialize(ClassLoaderFiles classLoaderFiles) throws IOException { 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.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.log.LogMessage;
import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.ClientHttpRequestInterceptor; import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.InterceptingClientHttpRequestFactory; import org.springframework.http.client.InterceptingClientHttpRequestFactory;
@ -118,9 +119,10 @@ public class RemoteClientConfiguration implements InitializingBean {
if (!remoteProperties.getRestart().isEnabled()) { if (!remoteProperties.getRestart().isEnabled()) {
logger.warn("Remote restart is disabled."); logger.warn("Remote restart is disabled.");
} }
if (!this.remoteUrl.startsWith("https://") && logger.isWarnEnabled()) { if (!this.remoteUrl.startsWith("https://")) {
logger.warn("The connection to " + this.remoteUrl logger.warn(LogMessage.format(
+ " is insecure. You should use a URL starting with 'https://'."); "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.logger.DevToolsLogFactory;
import org.springframework.boot.devtools.settings.DevToolsSettings; import org.springframework.boot.devtools.settings.DevToolsSettings;
import org.springframework.core.log.LogMessage;
import org.springframework.util.StringUtils; 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); throw new IllegalStateException("Class-Path attribute contains malformed URL", ex);
} }
} }
if (!nonExistentEntries.isEmpty() && logger.isInfoEnabled()) { if (!nonExistentEntries.isEmpty()) {
logger.info("The Class-Path manifest attribute in " + jarFile.getName() logger.info(LogMessage.of(() -> "The Class-Path manifest attribute in " + jarFile.getName()
+ " referenced one or more files that do not exist: " + " referenced one or more files that do not exist: "
+ StringUtils.collectionToCommaDelimitedString(nonExistentEntries)); + StringUtils.collectionToCommaDelimitedString(nonExistentEntries)));
} }
return urls; return urls;
} }

View File

@ -26,6 +26,7 @@ import org.springframework.boot.context.event.ApplicationStartingEvent;
import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener; import org.springframework.context.ApplicationListener;
import org.springframework.core.Ordered; import org.springframework.core.Ordered;
import org.springframework.core.log.LogMessage;
/** /**
* {@link ApplicationListener} to initialize the {@link Restarter}. * {@link ApplicationListener} to initialize the {@link Restarter}.
@ -73,9 +74,8 @@ public class RestartApplicationListener implements ApplicationListener<Applicati
Restarter.initialize(args, false, initializer, restartOnInitialize); Restarter.initialize(args, false, initializer, restartOnInitialize);
} }
else { else {
if (logger.isInfoEnabled()) { logger.info(LogMessage.format("Restart disabled due to System property '%s' being set to false",
logger.info("Restart disabled due to System property '" + ENABLED_PROPERTY + "' being set to false"); ENABLED_PROPERTY));
}
Restarter.disable(); 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.HttpTunnelPayload;
import org.springframework.boot.devtools.tunnel.payload.HttpTunnelPayloadForwarder; import org.springframework.boot.devtools.tunnel.payload.HttpTunnelPayloadForwarder;
import org.springframework.core.log.LogMessage;
import org.springframework.http.HttpMethod; import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpRequest; import org.springframework.http.client.ClientHttpRequest;
@ -92,9 +93,7 @@ public class HttpTunnelConnection implements TunnelConnection {
@Override @Override
public TunnelChannel open(WritableByteChannel incomingChannel, Closeable closeable) throws Exception { public TunnelChannel open(WritableByteChannel incomingChannel, Closeable closeable) throws Exception {
if (logger.isTraceEnabled()) { logger.trace(LogMessage.format("Opening HTTP tunnel to %s", this.uri));
logger.trace("Opening HTTP tunnel to " + this.uri);
}
return new TunnelChannel(incomingChannel, closeable); return new TunnelChannel(incomingChannel, closeable);
} }
@ -154,10 +153,8 @@ public class HttpTunnelConnection implements TunnelConnection {
} }
catch (IOException ex) { catch (IOException ex) {
if (ex instanceof ConnectException) { if (ex instanceof ConnectException) {
if (logger.isWarnEnabled()) { logger.warn(LogMessage.format("Failed to connect to remote application at %s",
logger.warn( HttpTunnelConnection.this.uri));
"Failed to connect to remote application at " + HttpTunnelConnection.this.uri);
}
} }
else { else {
logger.trace("Unexpected connection error", ex); 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.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.SmartInitializingSingleton; import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.core.log.LogMessage;
import org.springframework.util.Assert; import org.springframework.util.Assert;
/** /**
@ -88,9 +89,7 @@ public class TunnelClient implements SmartInitializingSingleton {
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.socket().bind(new InetSocketAddress(this.listenPort)); serverSocketChannel.socket().bind(new InetSocketAddress(this.listenPort));
int port = serverSocketChannel.socket().getLocalPort(); int port = serverSocketChannel.socket().getLocalPort();
if (logger.isTraceEnabled()) { logger.trace(LogMessage.format("Listening for TCP traffic to tunnel on port %s", port));
logger.trace("Listening for TCP traffic to tunnel on port " + port);
}
this.serverThread = new ServerThread(serverSocketChannel); this.serverThread = new ServerThread(serverSocketChannel);
this.serverThread.start(); this.serverThread.start();
return port; return port;
@ -146,9 +145,8 @@ public class TunnelClient implements SmartInitializingSingleton {
} }
public void close() throws IOException { public void close() throws IOException {
if (logger.isTraceEnabled()) { logger.trace(LogMessage.format("Closing tunnel client on port %s",
logger.trace("Closing tunnel client on port " + this.serverSocketChannel.socket().getLocalPort()); this.serverSocketChannel.socket().getLocalPort()));
}
this.serverSocketChannel.close(); this.serverSocketChannel.close();
this.acceptConnections = false; this.acceptConnections = false;
interrupt(); interrupt();

View File

@ -28,6 +28,7 @@ import java.nio.channels.SocketChannel;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.springframework.core.log.LogMessage;
import org.springframework.util.Assert; import org.springframework.util.Assert;
/** /**
@ -54,9 +55,7 @@ public class SocketTargetServerConnection implements TargetServerConnection {
@Override @Override
public ByteChannel open(int socketTimeout) throws IOException { public ByteChannel open(int socketTimeout) throws IOException {
SocketAddress address = new InetSocketAddress(this.portProvider.getPort()); SocketAddress address = new InetSocketAddress(this.portProvider.getPort());
if (logger.isTraceEnabled()) { logger.trace(LogMessage.format("Opening tunnel connection to target server on %s", address));
logger.trace("Opening tunnel connection to target server on " + address);
}
SocketChannel channel = SocketChannel.open(address); SocketChannel channel = SocketChannel.open(address);
channel.socket().setSoTimeout(socketTimeout); channel.socket().setSoTimeout(socketTimeout);
return new TimeoutAwareChannel(channel); 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.boot.ansi.AnsiOutput;
import org.springframework.core.env.Environment; import org.springframework.core.env.Environment;
import org.springframework.core.io.Resource; import org.springframework.core.io.Resource;
import org.springframework.core.log.LogMessage;
import org.springframework.util.Assert; import org.springframework.util.Assert;
/** /**
@ -78,10 +79,8 @@ public class ImageBanner implements Banner {
printBanner(environment, out); printBanner(environment, out);
} }
catch (Throwable ex) { catch (Throwable ex) {
if (logger.isWarnEnabled()) { logger.warn(LogMessage.format("Image banner not printable: %s (%s: '%s')", this.image, ex.getClass(),
logger.warn("Image banner not printable: " + this.image + " (" + ex.getClass() + ": '" + ex.getMessage() ex.getMessage()));
+ "')");
}
logger.debug("Image banner printing failure", ex); logger.debug("Image banner printing failure", ex);
} }
finally { finally {

View File

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

View File

@ -112,18 +112,19 @@ class StartupInfoLogger {
long startTime = System.currentTimeMillis(); long startTime = System.currentTimeMillis();
append(message, "on ", () -> InetAddress.getLocalHost().getHostName()); append(message, "on ", () -> InetAddress.getLocalHost().getHostName());
long resolveTime = System.currentTimeMillis() - startTime; long resolveTime = System.currentTimeMillis() - startTime;
if (resolveTime > HOST_NAME_RESOLVE_THRESHOLD && logger.isWarnEnabled()) { if (resolveTime > HOST_NAME_RESOLVE_THRESHOLD) {
StringBuilder warning = new StringBuilder(); logger.warn(LogMessage.of(() -> {
warning.append("InetAddress.getLocalHost().getHostName() took "); StringBuilder warning = new StringBuilder();
warning.append(resolveTime); warning.append("InetAddress.getLocalHost().getHostName() took ");
warning.append(" milliseconds to respond."); warning.append(resolveTime);
warning.append(" Please verify your network configuration"); warning.append(" milliseconds to respond.");
if (System.getProperty("os.name").toLowerCase().contains("mac")) { warning.append(" Please verify your network configuration");
warning.append(" (macOS machines may need to add entries to /etc/hosts)"); 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.ResolvableType;
import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment; import org.springframework.core.env.Environment;
import org.springframework.core.log.LogMessage;
import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap; import org.springframework.util.MultiValueMap;
import org.springframework.util.ResourceUtils; import org.springframework.util.ResourceUtils;
@ -416,9 +417,7 @@ public class LoggingApplicationListener implements GenericApplicationListener {
system.setLogLevel(name, level); system.setLogLevel(name, level);
} }
catch (RuntimeException ex) { catch (RuntimeException ex) {
if (this.logger.isErrorEnabled()) { this.logger.error(LogMessage.format("Cannot set level '%s' for '%s'", level, name));
this.logger.error("Cannot set level '" + level + "' for '" + name + "'");
}
} }
}; };
} }

View File

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

View File

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