You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决Spring Cloud Gateway中micrometer-brave获取trace-id为空的问题

Spring Cloud Gateway 请求日志TraceId/SpanId空值问题解决方案

问题场景

在Spring Cloud Gateway中配置了日志格式,期望每个请求日志显示traceId和spanId,但实际输出中这两个字段为空。当前配置如下:

日志配置

logging:
  pattern:
    level: "%5p [TRACE_ID: %X{traceId:-}] [SPAN_ID: %X{spanId:-}]"

现有依赖

<dependency>
    <groupId>io.micrometer</groupId>
    <artifactId>micrometer-tracing-bridge-brave</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
    <version>3.0.1</version>
</dependency>

解决方案

1. 补全WebFlux链路追踪依赖

Spring Cloud Gateway基于WebFlux实现,当前缺少Brave对WebFlux的链路追踪 instrumentation 依赖,导致无法生成并传播traceId/spanId。添加以下依赖:

<dependency>
    <groupId>io.zipkin.brave</groupId>
    <artifactId>brave-instrumentation-spring-webflux</artifactId>
</dependency>

注意:确保依赖版本与micrometer-tracing-bridge-brave版本一致,建议通过Spring Cloud BOM统一管理版本,避免版本冲突。

2. 开启Gateway指标与链路追踪配置

在application.yml中添加以下配置,确保Gateway启用链路追踪支持:

spring:
  cloud:
    gateway:
      metrics:
        enabled: true
micrometer:
  tracing:
    sampling:
      probability: 1.0  # 设置采样率为100%,生产环境可根据需求调整

3. 优化日志格式配置(可选)

将traceId/spanId配置到控制台日志格式中,确保日志输出更直观:

logging:
  pattern:
    console: "%d{yyyy-MM-dd HH:mm:ss.SSS} %5p [TRACE_ID: %X{traceId:-}] [SPAN_ID: %X{spanId:-}] [%t] %c{1}:%L - %m%n"

4. 验证上下文传播

确保请求经过Gateway时,Brave的WebFlux过滤器已将traceId/spanId写入MDC(Mapped Diagnostic Context),这样日志中的%X{traceId}才能正确取值。

完成以上配置后,重启服务,发起请求即可在日志中看到正常输出的traceId和spanId。

内容的提问来源于stack exchange,提问作者Murad Zulfugarov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 07:21:24