【问题标题】:Spring Sleuth - Correlation Id not loggingSpring Sleuth - 相关 ID 未记录
【发布时间】:2021-10-30 19:44:48
【问题描述】:

当前流量: SchedulerA -> ServiceA -> FeignOfB (Other ServiceB) -> ControllerB

log.xml

<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <layout class="ch.qos.logback.classic.PatternLayout">
        <Pattern>
            %d{yyyy-MM-dd HH:mm:ss,SS} [%thread] %-5level %logger{36} -
            %msg
            ${appName:-}, %X{Correlation-Id:-}, %X{traceId:-}, %X{spanId:-}%n
        </Pattern>
    </layout>
</appender>

application.yml

spring:
   sleuth:
     baggage:
       correlation-enabled: true
       correlation-fields:
         - Correlation-Id
       remote-fields:
         - Correlation-Id

调度程序代码:

public void scheduleFixedDelayTask() {
    String cId = UUID.randomUUID().toString().replace("-", "");
    BaggageField bField = BaggageField.getByName("Correlation-Id");
    if (bField != null) {
        bField.updateValue(tracer.currentSpan().context(), cId);
    }
    //MDC.put("Correlation-Id", cId);
    log.info("scheduleFixedDelayTask, {}", new Date());
    List<Foo> foos = this.feignService.getData("foo");
    log.info("scheduleFixedDelayTask - completed", new Date());
}

生成 UUID 并设置 BaggageField 值。 Correlation-Id 值打印在 ServiceB 控制器中,但在发出请求的 serviceA 的调度程序日志中,它不会打印 Correlation-Id。它在两个服务中打印 spanId 和 traceId(自行生成)。

如果我使用 MDC(注释行)手动设置值,则它会打印。 这是手动设置值的正确方法吗?

【问题讨论】:

    标签: java spring-boot spring-cloud spring-cloud-sleuth


    【解决方案1】:

    您需要配置 Brave 以在更新时执行刷新 - https://docs.spring.io/spring-cloud-sleuth/docs/current/reference/html/project-features.html#features-baggage

    @Bean
    ScopeDecorator mdcScopeDecorator() {
        return MDCScopeDecorator.newBuilder()
                .clear()
                .add(SingleCorrelationField.newBuilder(BaggageField.create("Correlation-Id"))
                        .flushOnUpdate()
                        .build())
                .build();
    }
    

    【讨论】:

    • 太棒了,它正在工作。 @JmsListener 有可用的仪器吗?在消息接收到侦听器之前,我想要某种拦截器,并想检查是否需要 Correlation-Id 和标头中可用的其他内容。
    猜你喜欢
    • 1970-01-01
    • 2021-03-20
    • 2020-08-08
    • 2018-09-09
    • 1970-01-01
    • 1970-01-01
    • 2021-07-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多