Search code examples
javaspring-bootspring-cloudspring-cloud-sleuth

Spring Sleuth - Correlation Id not logging


Current flow: 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

Scheduler Code:

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());
}

Generating UUID and setting BaggageField value. Correlation-Id value prints in ServiceB controller but in scheduler log of serviceA from where request originate, it does not print Correlation-Id. It prints spanId and traceId in both of the services(self generated).

If I manually set value using MDC(the commented line) then it prints. Is this a right way to manually set the value ?


Solution

  • You need to configure Brave to perform flush on update - 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();
    }