近期新项目,直接引入spring-cloud-starter-sleuth
- <!--springCloud链接追踪-->
- <dependency>
- <groupId>org.springframework.cloud</groupId>
- <artifactId>spring-cloud-starter-sleuth</artifactId>
- </dependency>
-
然后yml里面也一样配置
- spring:
- sleuth: #springCloud链接追踪
- web:
- client:
- enabled: true
- sampler:
- probability: 1.0 # 将采样比例设置为 1.0,也就是全部都需要。默认是 0.1
日志里面也正常配置了 %X{X-B3-TraceId:-},%X{X-B3-SpanId:-}
- <contextName>logback</contextName>
- <property name="log.pattern" value="[%-5level] %date [${log.context.name:-},%X{X-B3-TraceId:-},%X{X-B3-SpanId:-}] --%thread-- [%logger:%L] %msg %n" />
但是问题来了:打印出来的日志X-B3-TraceId和X-B3-SpanId都没有获取到日志
- 20:40:39.756 [,] [boundedElastic-6] INFO c.y.g.f.CacheRequestFilter - [apply,41] - CacheRequestFilter:{}
- 20:41:02.508 [,] [boundedElastic-1] INFO c.y.g.f.CacheRequestFilter - [apply,41] - CacheRequestFilter:{}
- 20:41:32.513 [,] [boundedElastic-3] INFO c.y.g.f.CacheRequestFilter - [apply,41] - CacheRequestFilter:{}
- 20:42:02.513 [,] [boundedElastic-8] INFO c.y.g.f.CacheRequestFilter - [apply,41] - CacheRequestFilter:{}
- 20:42:32.514 [,] [boundedElastic-1] INFO c.y.g.f.CacheRequestFilter - [apply,41] - CacheRequestFilter:{}
- 20:43:02.517 [,] [boundedElastic-2] INFO c.y.g.f.CacheRequestFilter - [apply,41] - CacheRequestFilter:{}
- 20:43:32.519 [,] [boundedElastic-7] INFO c.y.g.f.CacheRequestFilter - [apply,41] - CacheRequestFilter:{}
- 20:44:02.521 [,] [boundedElastic-8] INFO c.y.g.f.CacheRequestFilter - [apply,41] - CacheRequestFilter:{}
- 20:44:32.528 [,] [boundedElastic-2] INFO c.y.g.f.CacheRequestFilter - [apply,41] - CacheRequestFilter:{}
由于引入了spring-cloud-starter-gateway ,一查百度上各种建议,基本上都是同一种解决方案,配置如下,实际上并不行
- spring:
- sleuth:
- reactor:
- #在2020.0.0中,已将默认网关反应器检测模式更改为manual,
- #ON_EACH-用跟踪表示形式包装每个Reactor运算符。在大多数情况下,传递跟踪上下文。此模式可能会导致性能急剧下降。
- #ON_LAST-将最后一个Reactor运算符包装在跟踪表示中。在某些情况下传递跟踪上下文,
- #因此访问MDC上下文可能不起作用。此模式可能会导致中等性能下降。
- #MANUAL-以最小侵入性的方式包装每个Reactor,而无需通过跟踪上下文。由用户决定
- instrumentation-type: decorate_on_each
还引入了nacos,以前是eureka,怀疑是不是配置文件的问题,找了一下午,终于发现了一个不一样的地方,
老项目中的版本号是
新项目中的版本号是
这个时候我怀疑了,是不是版本的问题,于是按照这个版本接着找啊找,问题找到了:
Spring Cloud 2020.0.x 之后,也就是 spring-cloud-sleuth 3.0.0 之后,放入 ThreadContext 的 key 发生了变化,原来的 traceId 与 spanId 分别是 X-B3-traceId 与 X-B3-spanId,现在改成了更为通用的 traceId 和 spanId。改了日志中的内容,再运行项目,日志中的traceId来了;
- 20:40:40.751 [c0643f4a8ada1a00,7a3ae50e472620f8] [http-nio-9201-exec-1] INFO c.y.s.c.SysUserController - [list,97] - span:LazySpan(c0643f4a8ada1a00/7a3ae50e472620f8)
- 20:40:40.806 [c0643f4a8ada1a00,7a3ae50e472620f8] [http-nio-9201-exec-1] INFO c.y.s.c.SysUserController - [list,98] - 获取用户列表:{"admin":false,"params":{}}