工程源码:Gitee
日志门面(如Slf4j)就是一个标准,同JDBC一样来制定“规则”,把不同的日志系统的实现进行了具体的抽象化,只提供了统一的日志使用接口。而Logback、log4j等具体的日志系统就如同MySQL驱动、PGSQL驱动一样,才是日志功能的真正实现。
SpringBoot使用Slf4j作为日志门面,Logback作为默认的日志实现。在SpringBoot的pom.xml中,依赖为:
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-loggingartifactId>
dependency>
此依赖在SpringBoot Starter包中包含,所以在SpringBoot项目中导入 spring-boot-starter
后可直接使用:
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starterartifactId>
dependency>
dependencies>
LoggerFactory
创建日志记录器实例import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class LoggingApplication {
private static final Logger logger = LoggerFactory.getLogger(LoggingApplication.class);
public static void main(String[] args) {
logger.info("LoggingApplication start...");
SpringApplication.run(LoggingApplication.class, args);
logger.info("LoggingApplication end...");
}
}
lombok
依赖,通过注解@Slf4j
创建日志记录器实例<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starterartifactId>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
dependency>
dependencies>
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@Slf4j
@SpringBootApplication
public class LoggingApplication {
public static void main(String[] args) {
log.info("LoggingApplication start...");
SpringApplication.run(LoggingApplication.class, args);
log.info("LoggingApplication end...");
}
}
SpringBoot推荐将配置文件名称命名为logback-spring.xml
表示这是SpringBoot下Logback专用的配置,可以使用SpringBoot 的高级Profile功能,它的内容类似于这样:
<configuration>
configuration>
最外层由configuration
包裹,一旦编写,那么就会替换默认的配置,所以如果内部什么都不写的话,那么会导致我们的SpringBoot项目没有配置任何日志输出方式,控制台也不会打印日志。
也可在配置文件中指定要使用的日志配置,如
application.yml
中通过配置logging.config
指定要使用的日志配置。
logging:
config: classpath:logback-spring.xml
SpringBoot 的默认Logback文件可在依赖项中找到。路径为:
org/springframework/boot/logging/logback/defaults.xml
在配置文件中对默认配置进行引用,及编写定制配置覆盖默认配置。
<configuration>
<include resource="org/springframework/boot/logging/logback/defaults.xml"/>
<property name="CONSOLE_LOG_PATTERN"
value="MyLogPattern %clr(%d{${LOG_DATEFORMAT_PATTERN:-yyyy-MM-dd HH:mm:ss.SSS}}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr(${LOGGED_APPLICATION_NAME:-}[%15.15t]){faint} %clr(${LOG_CORRELATION_PATTERN:-}){faint}%clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}"/>
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>${CONSOLE_LOG_THRESHOLD}level>
filter>
<encoder>
<pattern>${CONSOLE_LOG_PATTERN}pattern>
<charset>${CONSOLE_LOG_CHARSET}charset>
encoder>
appender>
<root level="INFO">
<appender-ref ref="CONSOLE"/>
root>
configuration>
logback-spring.xml
添加如下内容:
<configuration>
<include resource="org/springframework/boot/logging/logback/defaults.xml"/>
<property name="LOG_PATH" value="./logs"/>
<property name="LOG_FILE" value="${LOG_PATH}/spring-boot.log"/>
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>${FILE_LOG_THRESHOLD}level>
filter>
<encoder>
<pattern>${FILE_LOG_PATTERN}pattern>
<charset>${FILE_LOG_CHARSET}charset>
encoder>
<file>${LOG_FILE}file>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${LOGBACK_ROLLINGPOLICY_FILE_NAME_PATTERN:-${LOG_FILE}.%d{yyyy-MM-dd}.%i.gz}fileNamePattern>
<cleanHistoryOnStart>${LOGBACK_ROLLINGPOLICY_CLEAN_HISTORY_ON_START:-false}cleanHistoryOnStart>
<maxFileSize>${LOGBACK_ROLLINGPOLICY_MAX_FILE_SIZE:-10MB}maxFileSize>
<totalSizeCap>${LOGBACK_ROLLINGPOLICY_TOTAL_SIZE_CAP:-0}totalSizeCap>
<maxHistory>${LOGBACK_ROLLINGPOLICY_MAX_HISTORY:-7}maxHistory>
rollingPolicy>
appender>
<root level="INFO">
<appender-ref ref="FILE"/>
root>
configuration>
MDC
全称Mapped Diagnostic Context
(映射诊断上下文),“映射诊断上下文” 本质上是由日志记录框架维护的映射,其中应用程序代码提供键值对,然后可以由日志记录框架将其插入日志消息中。MDC数据在过滤消息或触发某些操作时也非常有用。通俗的说就是可以将特定的信息(如请求Id,链路Id),通过MDC机制注入到当前日志线程的上下文中,将信息在日志中记录、输出。
MDC 常用的三个方法:
MDC注入属性配置:
在logback-spring.xml
文件的输出格式中添加需要注入的KEY信息与代码注入的信息相对应。假定我需要注入当前用户的Id信息,且设置key为user-id
代码:
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import java.util.UUID;
@Slf4j
@SpringBootApplication
public class LoggingApplication {
public static void main(String[] args) {
SpringApplication.run(LoggingApplication.class, args);
String mdcKey = "user-id";
log.info("Logging before MDC put...");
MDC.put("mdcKey", UUID.randomUUID().toString());
log.info("Logging after MDC put...");
MDC.clear();
log.info("Logging after MDC clear...");
}
}
logback-spring.xml
<configuration>
<include resource="org/springframework/boot/logging/logback/defaults.xml"/>
<property name="CONSOLE_LOG_PATTERN"
value="[%X{user-id}] %clr(%d{${LOG_DATEFORMAT_PATTERN:-yyyy-MM-dd HH:mm:ss.SSS}}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr(${LOGGED_APPLICATION_NAME:-}[%15.15t]){faint} %clr(${LOG_CORRELATION_PATTERN:-}){faint}%clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}"/>
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>${CONSOLE_LOG_THRESHOLD}level>
filter>
<encoder>
<pattern>${CONSOLE_LOG_PATTERN}pattern>
<charset>${CONSOLE_LOG_CHARSET}charset>
encoder>
appender>
<root level="INFO">
<appender-ref ref="CONSOLE"/>
root>
configuration>
使用方式:
- 通过注册拦截器或过滤器,在业务开始前获取到相关信息(请求Id,操作人Id),将相关信息通过MDC自动注入到当前线程中,实现关键信息记录。
- 在创建子线程时,需要通过
MDC.getCopyOfContextMap()
方法获取到当前线程的MDC注入相关信息,传递给子线程,才能在子线打印日志信息时获取到父线程MDC的注入信息。
<configuration>
<include resource="org/springframework/boot/logging/logback/defaults.xml"/>
<property name="LOG_PATH" value="./logs"/>
<property name="LOG_FILE" value="${LOG_PATH}/spring-boot.log"/>
<property name="FILE_NAME_PATTERN" value="${LOG_FILE}-%d{yyyyMMdd}.%i.gz"/>
<property name="LOGBACK_ROLLINGPOLICY_CLEAN_HISTORY_ON_START" value="false"/>
<property name="LOGBACK_ROLLINGPOLICY_MAX_FILE_SIZE" value="100MB"/>
<property name="LOGBACK_ROLLINGPOLICY_TOTAL_SIZE_CAP" value="0"/>
<property name="LOGBACK_ROLLINGPOLICY_MAX_HISTORY" value="7"/>
<property name="CONSOLE_LOG_CHARSET" value="UTF-8"/>
<property name="CONSOLE_LOG_PATTERN"
value="%clr(%d{${LOG_DATEFORMAT_PATTERN:-yyyy-MM-dd HH:mm:ss.SSS}}){faint} [%X{user-id}] [%X{request-id}] [%X{client-ip}] %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr(${LOGGED_APPLICATION_NAME:-}[%15.15t]){faint} %clr(${LOG_CORRELATION_PATTERN:-}){faint}%clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}"/>
<property name="CONSOLE_LOG_THRESHOLD" value="INFO"/>
<property name="FILE_LOG_PATTERN"
value="%d{${LOG_DATEFORMAT_PATTERN:-yyyy-MM-dd HH:mm:ss.SSS}} [%X{user-id}] [%X{request-id}] [%X{client-ip}] ${LOG_LEVEL_PATTERN:-%5p} ${PID:- } --- ${LOGGED_APPLICATION_NAME:-}[%t] ${LOG_CORRELATION_PATTERN:-}%-40.40logger{39} : %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}"/>
<property name="FILE_LOG_CHARSET" value="UTF-8"/>
<property name="FILE_LOG_THRESHOLD" value="INFO"/>
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>${CONSOLE_LOG_THRESHOLD}level>
filter>
<encoder>
<pattern>${CONSOLE_LOG_PATTERN}pattern>
<charset>${CONSOLE_LOG_CHARSET}charset>
encoder>
appender>
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>${FILE_LOG_THRESHOLD}level>
filter>
<encoder>
<pattern>${FILE_LOG_PATTERN}pattern>
<charset>${FILE_LOG_CHARSET}charset>
encoder>
<file>${LOG_FILE}file>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${FILE_NAME_PATTERN}fileNamePattern>
<cleanHistoryOnStart>${LOGBACK_ROLLINGPOLICY_CLEAN_HISTORY_ON_START}cleanHistoryOnStart>
<maxFileSize>${LOGBACK_ROLLINGPOLICY_MAX_FILE_SIZE}maxFileSize>
<totalSizeCap>${LOGBACK_ROLLINGPOLICY_TOTAL_SIZE_CAP}totalSizeCap>
<maxHistory>${LOGBACK_ROLLINGPOLICY_MAX_HISTORY}maxHistory>
rollingPolicy>
appender>
<root level="INFO">
<appender-ref ref="CONSOLE"/>
<appender-ref ref="FILE"/>
root>
configuration>