MDC是线程级别的
1、监听器
@WebListener
public class LogListener implements ServletRequestListener {
private final Logger log = LoggerFactory.getLogger(this.getClass());
@Override
public void requestDestroyed(ServletRequestEvent servletRequestEvent) {
MDC.clear();
}
@Override
public void requestInitialized(ServletRequestEvent servletRequestEvent) {
String mdcseq = RandomStringUtils.randomNumeric(16);
MDC.put("mdcseq", mdcseq);
}
}
2、logback.xml 放在 resources下
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<include resource="org/springframework/boot/logging/logback/default.xml"/>
<property name="LOG_FILE" value="logs/testlog-all" />
<property name="MY_FILE_LOG_PATTERN" value="%X{mdcseq} %date{yyyy-MM-dd HH:mm:ss.SSS} %-5level[%thread]%logger{56}.%method:%L -%msg%n" />
<appender name="ROLLING" class="ch.qos.logback.core.rolling.RollingFileAppender">
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${LOG_FILE}-%d{yyyy-MM-dd}.%i.log}</fileNamePattern>
<maxFileSize>100MB</maxFileSize>
<maxHistory>360</maxHistory>
<totalSizeCap>50GB</totalSizeCap>
</rollingPolicy>
<encoder>
<pattern>${MY_FILE_LOG_PATTERN}</pattern>
<charset>utf8</charset>
</encoder>
</appender>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>${MY_FILE_LOG_PATTERN}</pattern>
<charset>utf8</charset>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="ROLLING" />
<appender-ref ref="STDOUT" />
</root>
</configuration>
3、启动器注解:@ServletComponentScan(basePackages = {"com.*"})
4、日志前显示当前线程序号
2019-08-15 22:51:24.750 INFO [main]com.busy.DemoControlStarter.logStarted:59 -Started DemoControlStarter in 10.188 seconds (JVM running for 11.884)
4297028648688778 2019-08-15 22:52:07.841 INFO [http-nio-8765-exec-1]o.a.catalina.core.ContainerBase.[Tomcat].[localhost].[/].log:180 -Initializing Spring FrameworkServlet 'dispatcherServlet'
4297028648688778 2019-08-15 22:52:07.846 INFO [http-nio-8765-exec-1]org.springframework.web.servlet.DispatcherServlet.initServletBean:494 -FrameworkServlet 'dispatcherServlet': initialization started
4297028648688778 2019-08-15 22:52:07.896 INFO [http-nio-8765-exec-1]org.springframework.web.servlet.DispatcherServlet.initServletBean:509 -FrameworkServlet 'dispatcherServlet': initialization completed in 49 ms
4297028648688778 2019-08-15 22:52:07.951 INFO [http-nio-8765-exec-1]com.busy.controller.DemoController.test:27 -消费者日志
2019-08-15 22:52:08.322 INFO