如何让 Springboot 打印的启动失败日志更明确?

如何让 Springboot 打印的启动失败日志更明确?

有的时候 Springboot 启动失败的详细日志会给的不太明确,给我们排查问题带来了一定的困难,此时我们可以通过设置 LoggingFailureAnalysisReporter 的日志级别来解决这个问题。

FailureAnalysisReporter 类的源码

package org.springframework.boot.diagnostics;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.util.StringUtils;

/**
 * {@link FailureAnalysisReporter} that logs the failure analysis.
 *
 * @author Andy Wilkinson
 * @since 1.4.0
 */
public final class LoggingFailureAnalysisReporter implements FailureAnalysisReporter {

	private static final Log logger = LogFactory.getLog(LoggingFailureAnalysisReporter.class);

	@Override
	public void report(FailureAnalysis failureAnalysis) {
		if (logger.isDebugEnabled()) {
			logger.debug("Application failed to start due to an exception", failureAnalysis.getCause());
		}
		if (logger.isErrorEnabled()) {
			logger.error(buildMessage(failureAnalysis));
		}
	}

	private String buildMessage(FailureAnalysis failureAnalysis) {
		StringBuilder builder = new StringBuilder();
		builder.append(String.format("%n%n"));
		builder.append(String.format("***************************%n"));
		builder.append(String.format("APPLICATION FAILED TO START%n"));
		builder.append(String.format("***************************%n%n"));
		builder.append(String.format("Description:%n%n"));
		builder.append(String.format("%s%n", failureAnalysis.getDescription()));
		if (StringUtils.hasText(failureAnalysis.getAction())) {
			builder.append(String.format("%nAction:%n%n"));
			builder.append(String.format("%s%n", failureAnalysis.getAction()));
		}
		return builder.toString();
	}

}

设置日志级别

DEBUG

logging:
  level:
    org.springframework.boot.diagnostics.LoggingFailureAnalysisReporter: DEBUG
if (logger.isDebugEnabled()) {
	logger.debug("Application failed to start due to an exception", failureAnalysis.getCause());
}

日志级别设置为 DEBUG 级别会打印启动失败的 Cause

ERROR

logging:
  level:
    org.springframework.boot.diagnostics.LoggingFailureAnalysisReporter: ERROR
if (logger.isErrorEnabled()) {
	logger.error(buildMessage(failureAnalysis));
}

日志级别设置为 ERROR 级别后除了会打印启动失败的 Cause,还会打印具体的格式化消息

你可能感兴趣的:(躺坑现场,spring,boot,java,后端)