1.配置logbak-spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="5 seconds">
<!-- 定义日志文件的存储路径 -->
<property name="LOGS_PATH" value="./logs/" />
<timestamp key="datetime" datePattern="yyyy-MM-dd"/>
<springProperty scope="context" name="APP_NAME" source="com.appName" defaultValue="LOG"/>
<!--0. 日志格式和颜色渲染 -->
<!-- 彩色日志依赖的渲染类 -->
<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{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}"/>
<!-- 控制台日志输出 -->
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%date %-5level [%replace(%thread){'DubboServerHandler-','Dubbo'}] %logger{35}[%L] - %msg%n</pattern>
</encoder>
</appender>
<!-- 使用 MDC 的 appender 核心!!!-->
<appender name="FILE" class="ch.qos.logback.classic.sift.SiftingAppender">
<discriminator>
<key>threadName</key>
<defaultValue>main</defaultValue>
</discriminator>
<sift>
<appender name="FILE-${threadName}" class="ch.qos.logback.core.rolling.RollingFileAppender">
<encoder>
<Encoding>UTF-8</Encoding>
<pattern>%date %-5level [%replace(%thread){'DubboServerHandler-','Dubbo'}] %logger{35}[%L] - %msg%n</pattern>
</encoder>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<!--日志文件名称格式-->
<fileNamePattern>${LOGS_PATH}%d{yyyyMMdd}/${threadName}-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<!-- 日志文件保留30天 -->
<maxHistory>30</maxHistory>
<!--单文件大小-->
<maxFileSize>100MB</maxFileSize>
<totalSizeCap>10GB</totalSizeCap>
</rollingPolicy>
</appender>
</sift>
</appender>
<root level="info">
<appender-ref ref="CONSOLE" />
<appender-ref ref="FILE" />
</root>
</configuration>
2.在方法中使用MDC
MDC.put("threadName", "yourName");
//具体业务代码
MDC.remove("threadName")
注意:threadName和xml文件中的<discriminator>标签中的<key>一致;