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));
}
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();
}
else {
logger.warn(String.format("Free disk space below threshold. Available: %d bytes (threshold: %s)",
diskFreeInBytes, this.threshold));
if (logger.isWarnEnabled()) {
logger.warn(String.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) {
if (properties.getOpenInView() == null && logger.isWarnEnabled()) {
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

@ -83,7 +83,7 @@ public class GroovyTemplateAutoConfiguration {
public void checkTemplateLocationExists() {
if (this.properties.isCheckTemplateLocation() && !isUsingGroovyAllJar()) {
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
+ " (please add some templates, check your Groovy "
+ "configuration, or set spring.groovy.template.check-template-location=false)");

View File

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

@ -76,7 +76,9 @@ class DataSourceInitializerInvoker implements ApplicationListener<DataSourceSche
}
}
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() {
if (this.mustache.isCheckTemplateLocation()) {
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
+ " (please add some templates, check your Mustache configuration, or set spring.mustache."
+ "check-template-location=false)");

View File

@ -216,7 +216,7 @@ public abstract class JpaBaseConfiguration implements BeanFactoryAware {
@Bean
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. "
+ "Therefore, database queries may be performed during view "
+ "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));
}
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),
throwable);
}

View File

@ -54,7 +54,9 @@ public class OptionalLiveReloadServer implements InitializingBean {
if (!this.server.isStarted()) {
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) {
logger.warn("Unable to start LiveReload server");

View File

@ -126,7 +126,9 @@ public class RemoteDevToolsAutoConfiguration {
RemoteDevToolsProperties remote = properties.getRemote();
String servletContextPath = (servlet.getContextPath() != null) ? servlet.getContextPath() : "";
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);
return new UrlHandlerMapper(url, handler);
}

View File

@ -58,8 +58,12 @@ public class ClassPathFolders implements Iterable<File> {
this.folders.add(ResourceUtils.getFile(url));
}
catch (Exception ex) {
logger.warn("Unable to get classpath URL " + url);
logger.trace("Unable to get classpath URL " + url, ex);
if (logger.isWarnEnabled()) {
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) {
if (DevToolsEnablementDeducer.shouldEnable(Thread.currentThread()) && isLocalApplication(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));
}
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
+ "' property to 'DEBUG'");
}

View File

@ -114,8 +114,10 @@ public class ClassPathChangeUploader implements ApplicationListener<ClassPathCha
return;
}
catch (SocketException ex) {
logger.warn("A failure occurred when uploading to " + this.uri
+ ". Upload will be retried in 2 seconds");
if (logger.isWarnEnabled()) {
logger.warn("A failure occurred when uploading to " + this.uri
+ ". Upload will be retried in 2 seconds");
}
logger.debug("Upload failure", ex);
Thread.sleep(2000);
}
@ -128,8 +130,10 @@ public class ClassPathChangeUploader implements ApplicationListener<ClassPathCha
}
private void logUpload(ClassLoaderFiles classLoaderFiles) {
int size = classLoaderFiles.size();
logger.info("Uploaded " + size + " class " + ((size != 1) ? "resources" : "resource"));
if (logger.isInfoEnabled()) {
int size = classLoaderFiles.size();
logger.info("Uploaded " + size + " class " + ((size != 1) ? "resources" : "resource"));
}
}
private byte[] serialize(ClassLoaderFiles classLoaderFiles) throws IOException {

View File

@ -118,7 +118,7 @@ public class RemoteClientConfiguration implements InitializingBean {
if (!remoteProperties.getRestart().isEnabled()) {
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
+ " 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);
}
}
if (!nonExistentEntries.isEmpty()) {
if (!nonExistentEntries.isEmpty() && logger.isInfoEnabled()) {
logger.info("The Class-Path manifest attribute in " + jarFile.getName()
+ " referenced one or more files that do not exist: "
+ StringUtils.collectionToCommaDelimitedString(nonExistentEntries));

View File

@ -73,7 +73,9 @@ public class RestartApplicationListener implements ApplicationListener<Applicati
Restarter.initialize(args, false, initializer, restartOnInitialize);
}
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();
}
}

View File

@ -92,7 +92,9 @@ public class HttpTunnelConnection implements TunnelConnection {
@Override
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);
}
@ -152,7 +154,10 @@ public class HttpTunnelConnection implements TunnelConnection {
}
catch (IOException ex) {
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 {
logger.trace("Unexpected connection error", ex);

View File

@ -88,7 +88,9 @@ public class TunnelClient implements SmartInitializingSingleton {
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.socket().bind(new InetSocketAddress(this.listenPort));
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.start();
return port;
@ -144,7 +146,9 @@ public class TunnelClient implements SmartInitializingSingleton {
}
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.acceptConnections = false;
interrupt();

View File

@ -54,7 +54,9 @@ public class SocketTargetServerConnection implements TargetServerConnection {
@Override
public ByteChannel open(int socketTimeout) throws IOException {
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);
channel.socket().setSoTimeout(socketTimeout);
return new TimeoutAwareChannel(channel);

View File

@ -78,8 +78,10 @@ public class ImageBanner implements Banner {
printBanner(environment, out);
}
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);
}
finally {

View File

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

View File

@ -121,7 +121,9 @@ class StartupInfoLogger {
if (System.getProperty("os.name").toLowerCase().contains("mac")) {
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 desired = environment.getProperty("spring.mandatory-file-encoding");
if (encoding != null && !desired.equalsIgnoreCase(encoding)) {
logger.error("System property 'file.encoding' is currently '" + encoding + "'. It should be '" + desired
+ "' (as defined in 'spring.mandatoryFileEncoding').");
logger.error("Environment variable LANG is '" + System.getenv("LANG")
+ "'. 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 + "'.");
if (logger.isErrorEnabled()) {
logger.error("System property 'file.encoding' is currently '" + encoding + "'. It should be '" + desired
+ "' (as defined in 'spring.mandatoryFileEncoding').");
logger.error("Environment variable LANG is '" + System.getenv("LANG")
+ "'. 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 "
+ "desired default character encoding (" + desired + ").");
}

View File

@ -416,7 +416,9 @@ public class LoggingApplicationListener implements GenericApplicationListener {
system.setLogLevel(name, level);
}
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());
}
catch (Throwable ex) {
logger.trace("Failed to load " + analyzerName, ex);
if (logger.isTraceEnabled()) {
logger.trace("Failed to load " + analyzerName, ex);
}
}
}
AnnotationAwareOrderComparator.sort(analyzers);

View File

@ -91,7 +91,9 @@ public class WebServerPortFileWriter implements ApplicationListener<WebServerIni
portFile.deleteOnExit();
}
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));
}
}
}