Optimize logger calls

Guard logger calls to ensure that they are only made when the
level is set.

See gh-18710
This commit is contained in:
wycm 2019-10-23 20:27:06 +08:00 committed by Phillip Webb
parent 744dcd9426
commit 240b1f9e29
27 changed files with 92 additions and 44 deletions

View File

@ -124,7 +124,9 @@ public class DataSourcePoolMetricsAutoConfiguration {
hikari.setMetricsTrackerFactory(new MicrometerMetricsTrackerFactory(this.registry)); hikari.setMetricsTrackerFactory(new MicrometerMetricsTrackerFactory(this.registry));
} }
catch (Exception ex) { catch (Exception ex) {
logger.warn("Failed to bind Hikari metrics: " + ex.getMessage()); if (logger.isWarnEnabled()) {
logger.warn("Failed to bind Hikari metrics: " + ex.getMessage());
}
} }
} }
} }

View File

@ -62,8 +62,10 @@ public class DiskSpaceHealthIndicator extends AbstractHealthIndicator {
builder.up(); builder.up();
} }
else { else {
logger.warn(String.format("Free disk space below threshold. Available: %d bytes (threshold: %s)", if (logger.isWarnEnabled()) {
diskFreeInBytes, this.threshold)); logger.warn(String.format("Free disk space below threshold. Available: %d bytes (threshold: %s)",
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) { if (properties.getOpenInView() == null && logger.isWarnEnabled()) {
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

@ -83,7 +83,7 @@ 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)) { if (!location.exists(this.applicationContext) && logger.isWarnEnabled()) {
logger.warn("Cannot find template location: " + location logger.warn("Cannot find template location: " + location
+ " (please add some templates, check your Groovy " + " (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)");

View File

@ -119,8 +119,10 @@ public class JacksonAutoConfiguration {
@Bean @Bean
SimpleModule jodaDateTimeSerializationModule(JacksonProperties jacksonProperties) { SimpleModule jodaDateTimeSerializationModule(JacksonProperties jacksonProperties) {
logger.warn("Auto-configuration of Jackson's Joda-Time integration is deprecated in favor of using " if (logger.isWarnEnabled()) {
+ "java.time (JSR-310)."); logger.warn("Auto-configuration of Jackson's Joda-Time integration is deprecated in favor of using "
+ "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

@ -76,7 +76,9 @@ class DataSourceInitializerInvoker implements ApplicationListener<DataSourceSche
} }
} }
catch (IllegalStateException ex) { catch (IllegalStateException ex) {
logger.warn("Could not send event to complete DataSource initialization (" + ex.getMessage() + ")"); if (logger.isWarnEnabled()) {
logger.warn("Could not send event to complete DataSource initialization (" + ex.getMessage() + ")");
}
} }
} }

View File

@ -63,7 +63,7 @@ public class MustacheAutoConfiguration {
public void checkTemplateLocationExists() { public void checkTemplateLocationExists() {
if (this.mustache.isCheckTemplateLocation()) { if (this.mustache.isCheckTemplateLocation()) {
TemplateLocation location = new TemplateLocation(this.mustache.getPrefix()); TemplateLocation location = new TemplateLocation(this.mustache.getPrefix());
if (!location.exists(this.applicationContext)) { if (!location.exists(this.applicationContext) && logger.isWarnEnabled()) {
logger.warn("Cannot find template location: " + location logger.warn("Cannot find template location: " + location
+ " (please add some templates, check your Mustache configuration, or set spring.mustache." + " (please add some templates, check your Mustache configuration, or set spring.mustache."
+ "check-template-location=false)"); + "check-template-location=false)");

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) { if (this.jpaProperties.getOpenInView() == null && logger.isWarnEnabled()) {
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

@ -287,7 +287,7 @@ 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)) { && response.statusCode().equals(HttpStatus.INTERNAL_SERVER_ERROR) && logger.isErrorEnabled()) {
logger.error(request.exchange().getLogPrefix() + "500 Server Error for " + formatRequest(request), logger.error(request.exchange().getLogPrefix() + "500 Server Error for " + formatRequest(request),
throwable); throwable);
} }

View File

@ -54,7 +54,9 @@ public class OptionalLiveReloadServer implements InitializingBean {
if (!this.server.isStarted()) { if (!this.server.isStarted()) {
this.server.start(); this.server.start();
} }
logger.info("LiveReload server is running on port " + this.server.getPort()); if (logger.isInfoEnabled()) {
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

@ -126,7 +126,9 @@ 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";
logger.warn("Listening for remote restart updates on " + url); if (logger.isWarnEnabled()) {
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

@ -58,8 +58,12 @@ public class ClassPathFolders implements Iterable<File> {
this.folders.add(ResourceUtils.getFile(url)); this.folders.add(ResourceUtils.getFile(url));
} }
catch (Exception ex) { catch (Exception ex) {
logger.warn("Unable to get classpath URL " + url); if (logger.isWarnEnabled()) {
logger.trace("Unable to get classpath URL " + url, ex); logger.warn("Unable to get classpath URL " + url);
}
if (logger.isTraceEnabled()) {
logger.trace("Unable to get classpath URL " + url, ex);
}
} }
} }
} }

View File

@ -80,10 +80,12 @@ 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)) {
logger.info("Devtools property defaults active! Set '" + ENABLED + "' to 'false' to disable"); if (logger.isInfoEnabled()) {
logger.info("Devtools property defaults active! Set '" + ENABLED + "' to 'false' to disable");
}
environment.getPropertySources().addLast(new MapPropertySource("devtools", PROPERTIES)); environment.getPropertySources().addLast(new MapPropertySource("devtools", PROPERTIES));
} }
if (isWebApplication(environment) && !environment.containsProperty(WEB_LOGGING)) { if (isWebApplication(environment) && !environment.containsProperty(WEB_LOGGING) && logger.isInfoEnabled()) {
logger.info("For additional web related logging consider setting the '" + WEB_LOGGING logger.info("For additional web related logging consider setting the '" + WEB_LOGGING
+ "' property to 'DEBUG'"); + "' property to 'DEBUG'");
} }

View File

@ -114,8 +114,10 @@ public class ClassPathChangeUploader implements ApplicationListener<ClassPathCha
return; return;
} }
catch (SocketException ex) { catch (SocketException ex) {
logger.warn("A failure occurred when uploading to " + this.uri if (logger.isWarnEnabled()) {
+ ". Upload will be retried in 2 seconds"); logger.warn("A failure occurred when uploading to " + 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);
} }
@ -128,8 +130,10 @@ public class ClassPathChangeUploader implements ApplicationListener<ClassPathCha
} }
private void logUpload(ClassLoaderFiles classLoaderFiles) { private void logUpload(ClassLoaderFiles classLoaderFiles) {
int size = classLoaderFiles.size(); if (logger.isInfoEnabled()) {
logger.info("Uploaded " + size + " class " + ((size != 1) ? "resources" : "resource")); int size = classLoaderFiles.size();
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

@ -118,7 +118,7 @@ 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://")) { if (!this.remoteUrl.startsWith("https://") && logger.isWarnEnabled()) {
logger.warn("The connection to " + this.remoteUrl logger.warn("The connection to " + this.remoteUrl
+ " is insecure. You should use a URL starting with 'https://'."); + " is insecure. You should use a URL starting with 'https://'.");
} }

View File

@ -170,7 +170,7 @@ 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()) { if (!nonExistentEntries.isEmpty() && logger.isInfoEnabled()) {
logger.info("The Class-Path manifest attribute in " + jarFile.getName() logger.info("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));

View File

@ -73,7 +73,9 @@ public class RestartApplicationListener implements ApplicationListener<Applicati
Restarter.initialize(args, false, initializer, restartOnInitialize); Restarter.initialize(args, false, initializer, restartOnInitialize);
} }
else { else {
logger.info("Restart disabled due to System property '" + ENABLED_PROPERTY + "' being set to false"); if (logger.isInfoEnabled()) {
logger.info("Restart disabled due to System property '" + ENABLED_PROPERTY + "' being set to false");
}
Restarter.disable(); Restarter.disable();
} }
} }

View File

@ -92,7 +92,9 @@ 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 {
logger.trace("Opening HTTP tunnel to " + this.uri); if (logger.isTraceEnabled()) {
logger.trace("Opening HTTP tunnel to " + this.uri);
}
return new TunnelChannel(incomingChannel, closeable); return new TunnelChannel(incomingChannel, closeable);
} }
@ -152,7 +154,10 @@ public class HttpTunnelConnection implements TunnelConnection {
} }
catch (IOException ex) { catch (IOException ex) {
if (ex instanceof ConnectException) { if (ex instanceof ConnectException) {
logger.warn("Failed to connect to remote application at " + HttpTunnelConnection.this.uri); if (logger.isWarnEnabled()) {
logger.warn(
"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

@ -88,7 +88,9 @@ 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();
logger.trace("Listening for TCP traffic to tunnel on port " + port); if (logger.isTraceEnabled()) {
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;
@ -144,7 +146,9 @@ public class TunnelClient implements SmartInitializingSingleton {
} }
public void close() throws IOException { public void close() throws IOException {
logger.trace("Closing tunnel client on port " + this.serverSocketChannel.socket().getLocalPort()); if (logger.isTraceEnabled()) {
logger.trace("Closing tunnel client on port " + this.serverSocketChannel.socket().getLocalPort());
}
this.serverSocketChannel.close(); this.serverSocketChannel.close();
this.acceptConnections = false; this.acceptConnections = false;
interrupt(); interrupt();

View File

@ -54,7 +54,9 @@ 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());
logger.trace("Opening tunnel connection to target server on " + address); if (logger.isTraceEnabled()) {
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

@ -78,8 +78,10 @@ public class ImageBanner implements Banner {
printBanner(environment, out); printBanner(environment, out);
} }
catch (Throwable ex) { catch (Throwable ex) {
logger.warn("Image banner not printable: " + this.image + " (" + ex.getClass() + ": '" + ex.getMessage() if (logger.isWarnEnabled()) {
+ "')"); logger.warn("Image banner not printable: " + this.image + " (" + ex.getClass() + ": '" + ex.getMessage()
+ "')");
}
logger.debug("Image banner printing failure", ex); logger.debug("Image banner printing failure", ex);
} }
finally { finally {

View File

@ -70,9 +70,10 @@ public class ResourceBanner implements Banner {
out.println(banner); out.println(banner);
} }
catch (Exception ex) { catch (Exception ex) {
logger.warn( if (logger.isWarnEnabled()) {
"Banner not printable: " + this.resource + " (" + ex.getClass() + ": '" + ex.getMessage() + "')", logger.warn("Banner not printable: " + this.resource + " (" + ex.getClass() + ": '" + ex.getMessage()
ex); + "')", ex);
}
} }
} }

View File

@ -121,7 +121,9 @@ class StartupInfoLogger {
if (System.getProperty("os.name").toLowerCase().contains("mac")) { if (System.getProperty("os.name").toLowerCase().contains("mac")) {
warning.append(" (macOS machines may need to add entries to /etc/hosts)"); warning.append(" (macOS machines may need to add entries to /etc/hosts)");
} }
logger.warn(warning.append(".")); if (logger.isWarnEnabled()) {
logger.warn(warning.append("."));
}
} }
} }

View File

@ -64,12 +64,14 @@ public class FileEncodingApplicationListener
String encoding = System.getProperty("file.encoding"); String encoding = System.getProperty("file.encoding");
String desired = environment.getProperty("spring.mandatory-file-encoding"); String desired = environment.getProperty("spring.mandatory-file-encoding");
if (encoding != null && !desired.equalsIgnoreCase(encoding)) { if (encoding != null && !desired.equalsIgnoreCase(encoding)) {
logger.error("System property 'file.encoding' is currently '" + encoding + "'. It should be '" + desired if (logger.isErrorEnabled()) {
+ "' (as defined in 'spring.mandatoryFileEncoding')."); logger.error("System property 'file.encoding' is currently '" + encoding + "'. It should be '" + desired
logger.error("Environment variable LANG is '" + System.getenv("LANG") + "' (as defined in 'spring.mandatoryFileEncoding').");
+ "'. You could use a locale setting that matches encoding='" + desired + "'."); logger.error("Environment variable LANG is '" + System.getenv("LANG")
logger.error("Environment variable LC_ALL is '" + System.getenv("LC_ALL") + "'. You could use a locale setting that matches encoding='" + desired + "'.");
+ "'. You could use a locale setting that matches encoding='" + desired + "'."); logger.error("Environment variable LC_ALL is '" + System.getenv("LC_ALL")
+ "'. You could use a locale setting that matches encoding='" + desired + "'.");
}
throw new IllegalStateException("The Java Virtual Machine has not been configured to use the " throw new IllegalStateException("The Java Virtual Machine has not been configured to use the "
+ "desired default character encoding (" + desired + ")."); + "desired default character encoding (" + desired + ").");
} }

View File

@ -416,7 +416,9 @@ public class LoggingApplicationListener implements GenericApplicationListener {
system.setLogLevel(name, level); system.setLogLevel(name, level);
} }
catch (RuntimeException ex) { catch (RuntimeException ex) {
this.logger.error("Cannot set level '" + level + "' for '" + name + "'"); if (this.logger.isErrorEnabled()) {
this.logger.error("Cannot set level '" + level + "' for '" + name + "'");
}
} }
}; };
} }

View File

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

View File

@ -91,7 +91,9 @@ public class WebServerPortFileWriter implements ApplicationListener<WebServerIni
portFile.deleteOnExit(); portFile.deleteOnExit();
} }
catch (Exception ex) { catch (Exception ex) {
logger.warn(String.format("Cannot create port file %s", this.file)); if (logger.isWarnEnabled()) {
logger.warn(String.format("Cannot create port file %s", this.file));
}
} }
} }