Search code examples
springopentracingjaeger

How to add tags or baggage with spring-cloud starter?


I am trying to add a tag or baggage to an OpenTracing trace. I am creating the tracer via @Beans but can not figure out how to reference the active span when using the autoconfiguration that comes with cloud-starter.

Using this dependency

    <groupId>io.opentracing.contrib</groupId>
    <artifactId>opentracing-spring-cloud-starter</artifactId>
    <version>0.2.4</version>

I tried this

    tracer.activeSpan().setBaggageItem("baggage", "baggage");

And this

    scope.span().setBaggageItem("baggage", "baggage");

Both result in NPE. Even trying to log the span or tracer object gives me an NPE so seems I do not have to right pattern for interacting with it.

Here is how the tracer is getting setup.

    @Bean
    public io.opentracing.Tracer jaegerTracer() {
        SamplerConfiguration samplerConfig = SamplerConfiguration.fromEnv().withType("const").withParam(1);
        SenderConfiguration senderConfig = SenderConfiguration.fromEnv().withEndpoint("http://jaeger:14268/api/traces");
        ReporterConfiguration reporterConfig = ReporterConfiguration.fromEnv().withLogSpans(true).withSender(senderConfig);
        Configuration config = new Configuration("eclipse-hawkular").withSampler(samplerConfig).withReporter(reporterConfig);
        return config.getTracer();
    }

More info...

Looking at the opentracing-spring-web-contrib code where the span decorator is defined which is where I am getting the default spans and associated tags from. But how to add custom tag/baggage if executing the restTemplate is what triggers the intercept that starts the active span? I assume I should not be interacting with the spanDecorator directly.

And more info...

Also tried to add baggage when using opentracing-contrib-okhttp. Tracing worked great but cannot figure out how to add bagged when using the interceptor based auto tracers.


Solution

  • Can now add baggage with this single line.

    TracerResolver.resolveTracer().activeSpan().setBaggageItem("baggage", "adding baggage");
    

    In the course of working on this also started using Spring 2.0.9.RELEASE and a single dependency for OpenTracing which uses the 0.32 version of the Jaeger tracer.

    <dependency>
        <groupId>io.opentracing.contrib</groupId>
        <artifactId>opentracing-spring-jaeger-cloud-starter</artifactId>
        <version>1.0.3</version>
    </dependency>