在一个基于Spring boot开发的项目里,常常需要有多套环境的配置:开发,测试以及产品。这里给出一个logback的通用配置。
在src/main/resources目录下创建配置文件logback-spring.xml,多环境的通用配置内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<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" />
<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.TimeBasedRollingPolicy">
<fileNamePattern>${LOG_FILE}.%d</fileNamePattern>
</rollingPolicy>
</appender>
<springProfile name="dev">
<root level="INFO">
<appender-ref ref="CONSOLE" />
<appender-ref ref="FILE" />
</root>
</springProfile>
<springProfile name="test,prod">
<root level="INFO">
<appender-ref ref="FILE" />
</root>
</springProfile>
</configuration>
Spring Boot提供了一个默认的logback配置,把它引进来:
<include resource="org/springframework/boot/logging/logback/defaults.xml" />
Spring Boot也提供了一个控制台的appender,在开发环境可以使用它:
<include resource="org/springframework/boot/logging/logback/console-appender.xml" />
配置了一个按日期滚动的输出文件,它用于生产或测试环境
<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.TimeBasedRollingPolicy">
<fileNamePattern>${LOG_FILE}.%d</fileNamePattern>
</rollingPolicy>
</appender>
其中FILE_LOG_PATTERN是在org/springframework/boot/logging/logback/defaults.xml已定义:
<property name="FILE_LOG_PATTERN" value="%d{yyyy-MM-dd HH:mm:ss.SSS} ${LOG_LEVEL_PATTERN:-%5p} ${PID:- } --- [%t] %-40.40logger{39} : %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}"/>
最后使用springProfile 分配配置了开发(dev),测试(test)以及生产(prod)三套环境