聊聊springboot的logback配置

2023-10-31 21:35:15 浏览数 (2)

本文主要研究一下springboot的logback配置

defaults.xml

org/springframework/boot/logging/logback/defaults.xml

代码语言:javascript复制
<?xml version="1.0" encoding="UTF-8"?>

<!--
Default logback configuration provided for import
-->

<included>
	<conversionRule conversionWord="clr" converterClass="org.springframework.boot.logging.logback.ColorConverter" />
	<conversionRule conversionWord="wex" converterClass="org.springframework.boot.logging.logback.WhitespaceThrowableProxyConverter" />
	<conversionRule conversionWord="wEx" converterClass="org.springframework.boot.logging.logback.ExtendedWhitespaceThrowableProxyConverter" />
	<property name="CONSOLE_LOG_PATTERN" value="${CONSOLE_LOG_PATTERN:-%clr(%d{${LOG_DATEFORMAT_PATTERN:-yyyy-MM-dd HH:mm:ss.SSS}}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}"/>
	<property name="FILE_LOG_PATTERN" value="${FILE_LOG_PATTERN:-%d{${LOG_DATEFORMAT_PATTERN:-yyyy-MM-dd HH:mm:ss.SSS}} ${LOG_LEVEL_PATTERN:-%5p} ${PID:- } --- [%t] %-40.40logger{39} : %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}"/>

	<logger name="org.apache.catalina.startup.DigesterFactory" level="ERROR"/>
	<logger name="org.apache.catalina.util.LifecycleBase" level="ERROR"/>
	<logger name="org.apache.coyote.http11.Http11NioProtocol" level="WARN"/>
	<logger name="org.apache.sshd.common.util.SecurityUtils" level="WARN"/>
	<logger name="org.apache.tomcat.util.net.NioSelectorPool" level="WARN"/>
	<logger name="org.eclipse.jetty.util.component.AbstractLifeCycle" level="ERROR"/>
	<logger name="org.hibernate.validator.internal.util.Version" level="WARN"/>
	<logger name="org.springframework.boot.actuate.endpoint.jmx" level="WARN"/>
</included>

spring-boot包含了defaults.xml,它定义了一些conversionRule、CONSOLE_LOG_PATTERN、FILE_LOG_PATTERN变量以及一些logger

console-appender.xml

org/springframework/boot/logging/logback/console-appender.xml

代码语言:javascript复制
<?xml version="1.0" encoding="UTF-8"?>

<!--
Console appender logback configuration provided for import, equivalent to the programmatic
initialization performed by Boot
-->

<included>
	<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
		<encoder>
			<pattern>${CONSOLE_LOG_PATTERN}</pattern>
		</encoder>
	</appender>
</included>

console-appender.xml定义了CONSOLE这个appender,其pattern取决于CONSOLE_LOG_PATTERN变量

file-appender.xml

org/springframework/boot/logging/logback/file-appender.xml

代码语言:javascript复制
<?xml version="1.0" encoding="UTF-8"?>

<!--
File appender logback configuration provided for import, equivalent to the programmatic
initialization performed by Boot
-->

<included>
	<appender name="FILE"
		class="ch.qos.logback.core.rolling.RollingFileAppender">
		<encoder>
			<pattern>${FILE_LOG_PATTERN}</pattern>
		</encoder>
		<file>${LOG_FILE}</file>
		<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
			<cleanHistoryOnStart>${LOG_FILE_CLEAN_HISTORY_ON_START:-false}</cleanHistoryOnStart>
			<fileNamePattern>${ROLLING_FILE_NAME_PATTERN:-${LOG_FILE}.%d{yyyy-MM-dd}.%i.gz}</fileNamePattern>
			<maxFileSize>${LOG_FILE_MAX_SIZE:-10MB}</maxFileSize>
			<maxHistory>${LOG_FILE_MAX_HISTORY:-7}</maxHistory>
			<totalSizeCap>${LOG_FILE_TOTAL_SIZE_CAP:-0}</totalSizeCap>
		</rollingPolicy>
	</appender>
</included>

file-appender.xml定义了RollingFileAppender这个appender,其pattern取决于FILE_LOG_PATTERN,其file取决于LOG_FILE变量,rollingPolicy为SizeAndTimeBasedRollingPolicy,cleanHistoryOnStart默认为false,fileNamePattern默认为${LOG_FILE}.%d{yyyy-MM-dd}.%i.gz},maxFileSize默认为10MB,maxHistory默认为7,totalSizeCap默认为0

base.xml

org/springframework/boot/logging/logback/base.xml

代码语言:javascript复制
<?xml version="1.0" encoding="UTF-8"?>

<!--
Base logback configuration provided for compatibility with Spring Boot 1.1
-->

<included>
	<include resource="org/springframework/boot/logging/logback/defaults.xml" />
	<property name="LOG_FILE" value="${LOG_FILE:-${LOG_PATH:-${LOG_TEMP:-${java.io.tmpdir:-/tmp}}}/spring.log}"/>
	<include resource="org/springframework/boot/logging/logback/console-appender.xml" />
	<include resource="org/springframework/boot/logging/logback/file-appender.xml" />
	<root level="INFO">
		<appender-ref ref="CONSOLE" />
		<appender-ref ref="FILE" />
	</root>
</included>

base.xml引入了defaults.xml、console-appender.xml、file-appender.xml,它主要是定义了LOG_FILE路径,默认为${java.io.tmpdir:-/tmp}}}/spring.log

logback.xml示例

代码语言:javascript复制
	<?xml version="1.0" encoding="UTF-8"?>
	<configuration>
		<include resource="org/springframework/boot/logging/logback/defaults.xml"/>
		<include resource="org/springframework/boot/logging/logback/console-appender.xml" />
		<root level="INFO">
			<appender-ref ref="CONSOLE" />
		</root>
		<logger name="org.springframework.web" level="DEBUG"/>
	</configuration>

loadDefaults

org/springframework/boot/logging/logback/LogbackLoggingSystem.java

代码语言:javascript复制
	@Override
	protected void loadDefaults(LoggingInitializationContext initializationContext, LogFile logFile) {
		LoggerContext context = getLoggerContext();
		stopAndReset(context);
		boolean debug = Boolean.getBoolean("logback.debug");
		if (debug) {
			StatusListenerConfigHelper.addOnConsoleListenerInstance(context, new OnConsoleStatusListener());
		}
		LogbackConfigurator configurator = debug ? new DebugLogbackConfigurator(context)
				: new LogbackConfigurator(context);
		Environment environment = initializationContext.getEnvironment();
		context.putProperty(LoggingSystemProperties.LOG_LEVEL_PATTERN,
				environment.resolvePlaceholders("${logging.pattern.level:${LOG_LEVEL_PATTERN:%5p}}"));
		context.putProperty(LoggingSystemProperties.LOG_DATEFORMAT_PATTERN, environment.resolvePlaceholders(
				"${logging.pattern.dateformat:${LOG_DATEFORMAT_PATTERN:yyyy-MM-dd HH:mm:ss.SSS}}"));
		context.putProperty(LoggingSystemProperties.ROLLING_FILE_NAME_PATTERN, environment
				.resolvePlaceholders("${logging.pattern.rolling-file-name:${LOG_FILE}.%d{yyyy-MM-dd}.%i.gz}"));
		new DefaultLogbackConfiguration(initializationContext, logFile).apply(configurator);
		context.setPackagingDataEnabled(true);
	}

在没有logback.xml或者logback-spring.xml的时候,默认走的loadDefaults,它定义了LOG_LEVEL_PATTERN、LOG_DATEFORMAT_PATTERN、ROLLING_FILE_NAME_PATTERN,然后创建DefaultLogbackConfiguration并作用了LogbackConfigurator

DefaultLogbackConfiguration

org/springframework/boot/logging/logback/DefaultLogbackConfiguration.java

代码语言:javascript复制
class DefaultLogbackConfiguration {

	private static final String CONSOLE_LOG_PATTERN = "%clr(%d{${LOG_DATEFORMAT_PATTERN:-yyyy-MM-dd HH:mm:ss.SSS}}){faint} "
			  "%clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} "
			  "%clr([.15t]){faint} %clr(%-40.40logger{39}){cyan} "
			  "%clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}";

	private static final String FILE_LOG_PATTERN = "%d{${LOG_DATEFORMAT_PATTERN:-yyyy-MM-dd HH:mm:ss.SSS}} "
			  "${LOG_LEVEL_PATTERN:-%5p} ${PID:- } --- [%t] %-40.40logger{39} : %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}";

	private static final DataSize MAX_FILE_SIZE = DataSize.ofMegabytes(10);

	private static final Integer MAX_FILE_HISTORY = 7;

	private final PropertyResolver patterns;

	private final LogFile logFile;

	DefaultLogbackConfiguration(LoggingInitializationContext initializationContext, LogFile logFile) {
		this.patterns = getPatternsResolver(initializationContext.getEnvironment());
		this.logFile = logFile;
	}

	void apply(LogbackConfigurator config) {
		synchronized (config.getConfigurationLock()) {
			base(config);
			Appender<ILoggingEvent> consoleAppender = consoleAppender(config);
			if (this.logFile != null) {
				Appender<ILoggingEvent> fileAppender = fileAppender(config, this.logFile.toString());
				config.root(Level.INFO, consoleAppender, fileAppender);
			}
			else {
				config.root(Level.INFO, consoleAppender);
			}
		}
	}

	//......
}	

DefaultLogbackConfiguration类似于defaults.xml, console-appender.xml及file-appender.xml,不过它把相关配置直接写在代码里头省去xml解析,效率高一点;这里的apply代码显示执行base(config),再是创建consoleAppender,再创建fileAppender

小结

spring-boot定义了defaults.xml提供了conversion rules、CONSOLE_LOG_PATTERN、FILE_LOG_PATTERN变量及一些常用logger;console-appender.xml则定义了使用CONSOLE_LOG_PATTERN的ConsoleAppender;file-appender.xml则定义了使用FILE_LOG_PATTERN及ROLLING_FILE_NAME_PATTERN的RollingFileAppender;而base.xml是兼容旧版springboot定义的,它集成了defaults.xml、console-appender.xml、file-appender.xml;而新版的话默认是通过DefaultLogbackConfiguration来定义base、consoleAppender以及fileAppender的,省去xml解析,效率更高一点。

0 人点赞