javaspringspring-cloud-sleuthmicrometer-tracing

Brave Baggage not working after switching from spring-cloud-sleuth to micrometer-tracing


I am updating my spring project to newer versions, and after updating I got the following message:

Your project setup is incompatible with our requirements due to following reasons: Spring Cloud Sleuth is not compatible with this Spring Cloud release train, Action: Consider applying the following actions: Migrate from Spring Cloud Sleuth to Micrometer Tracing.

So I removed sleuth and added the micrometer-tracing and micrometer-tracing-bridge-brave dependencies and switched to the following configuration:

management:
  tracing:
    enabled: true
    baggage:
      enabled: true
      correlation:
        enabled: true
        fields: USER_ID
      remote-fields: USER_ID

Now my BaggageField is not getting added to my MDCs as it was before. I have narrowed it down to the tracing.currentTraceContext().get() returning null when I call BaggageField.updateValue() but I cannot figure out why this is.

@Nullable static TraceContext currentTraceContext() {
    Tracing tracing = Tracing.current();
    return tracing != null ? tracing.currentTraceContext().get() : null;
}

Here is my code that creates the BaggageField bean:

import brave.baggage.BaggageField;
import brave.baggage.CorrelationScopeConfig;
import brave.context.slf4j.MDCScopeDecorator;
import brave.propagation.CurrentTraceContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class BaggageConfig {

    public static final String USER_ID_KEY = "USER_ID";

    @Bean
    BaggageField userIdField() {
        return BaggageField.create(USER_ID_KEY);
    }
    

    @Bean
    public CurrentTraceContext.ScopeDecorator mdcScopeDecorator(BaggageField userIdField) {
        return MDCScopeDecorator.newBuilder()
                .clear()
                .add(CorrelationScopeConfig.SingleCorrelationField.newBuilder(userIdField).flushOnUpdate().build())
                .build();
    }
}

And when I try to update the value I autowire in the BaggageField:

private final BaggageField userIdField;

And update:

userIdField.updateValue(requestMetadataContext.getUserId());

Versions:

org.springframework.boot:3.0.6
org.springframework.cloud:spring-cloud-starter-bootstrap:4.0.2
org.springframework.cloud:spring-cloud-starter-consul-all:4.0.2
io.micrometer:micrometer-tracing:1.1.0
io.micrometer:micrometer-tracing-bridge-brave:1.1.0

Edit: Small application to reproduce Baggage Example


Solution

  • I managed to make this work by autowiring a Tracer and instead adding the baggage inside the Tracer.

    @Autowired
    private final Tracer tracer;
    
    tracer.createBaggageInScope("USER_ID", "USER_ID_VALUE");