java 中我们在同一个请求中多个方法进行调用时,多条日志如何形成链路进行查询呢? 这个时候就需要 slf4j 中的 MDC 把每条日志中添加一些额外的属性,从而方便日志的查询和使用。
MDC 更多的应用在 web 请求中,在 filter 设置 MDC,MDC 添加每个请求的唯一值,请求链路中打印日志就携带这个唯一值,实现请求链路。
1.pom
<dependencies>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.21</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.7</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.1.7</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
</dependencies>
2.logback配置
classpath 下新建 logback.xml 文件
<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] [traceId = %X{traceId}] [%logger{32}] - %msg%n</pattern>
</encoder>
</appender>
<root level="info">
<appender-ref ref="console"/>
</root>
</configuration>
3.java
private final static Logger LOGGER = LoggerFactory.getLogger(MDTest.class);
@Test
public void testMD() {
try {
MDC.put("traceId", UUID.randomUUID().toString());
LOGGER.info("this is testMD");
method1();
method2();
} finally {
MDC.clear();
}
}
public void method1() {
LOGGER.info("this is method1");
}
public void method2() {
LOGGER.info("this is method2");
}
4.结果
2024-04-13 14:41:22.431 [main] [traceId = afff341d-5e9e-43a0-a305-57abfcda7f72] [org.example.MDTest] - this is testMD
2024-04-13 14:41:22.432 [main] [traceId = afff341d-5e9e-43a0-a305-57abfcda7f72] [org.example.MDTest] - this is method1
2024-04-13 14:41:22.432 [main] [traceId = afff341d-5e9e-43a0-a305-57abfcda7f72] [org.example.MDTest] - this is method2