# SpringBoot全链路日志

SpringBoot全链路日志

# 1. MDC

一般是使用 MDC 实现全链路日志,如下

但是对于接口调用,异步线程,MQ 等处理实现是比较麻烦的,SpringCloud 可以使用 Sleuth 组件实现

# 2. Sleuth

引入对应 Jar 包

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-sleuth</artifactId>
</dependency>

Logback 加上 [%X{traceId:-}] [%X{spanId:-}] 即可

<property name="log.pattern" value="%d{yyyy-MM-dd HH:mm:ss:SSS} [%-3p] [%X{user:-}] [%thread] [%X{traceId:-}] [%X{spanId:-}] %C{5}.%method:%L: %m%n" />

可以输出当前 MDC 携带的参数

Map<String, String> mdcMap =  MDC.getCopyOfContextMap();
{"traceId":"9324df3ca00d62ac","spanId":"9324df3ca00d62ac","spanExportable":"false","X-Span-Export":"false","X-B3-SpanId":"9324df3ca00d62ac","X-B3-TraceId":"9324df3ca00d62ac"}

Zipkin B3 Header标准,其格式如下

X-B3-TraceId: {TraceID}
X-B3-ParentSpanId: {ParentSpanID}
X-B3-SpanId: {SpanID}
X-B3-Sampled: {SampleFlag}

X-B3-TraceId:"5dbf140f59e8232f",
X-B3-ParentSpanId:"5dbf140f59e8232f",
X-B3-SpanId:"47a415c4317ffbdd",
X-B3-Sampled:"1",

参考

上次更新时间: 2023-12-15 03:14:55