Search code examples
spring-bootresttemplateopentracingjaeger

Inject the OpenTracing's SpanContext in a Spring RestTemplate


I have the necessity to manually inject a SpanContext into a Spring RestTemplate.

For reasons that are irrelevant to the question, I can't just use "opentracing-spring-web-starter" because that would conflict with other starters I have set up and makes the project crash.

I have found this snippet of code relative to injecting the Context into an HTTP request, but I can't find anything relative to the a RestTemplate:

Tags.SPAN_KIND.set(tracer.activeSpan(), Tags.SPAN_KIND_CLIENT);
Tags.HTTP_METHOD.set(tracer.activeSpan(), "GET");
Tags.HTTP_URL.set(tracer.activeSpan(), url.toString());
tracer.inject(tracer.activeSpan().context(), Format.Builtin.HTTP_HEADERS, new RequestBuilderCarrier(requestBuilder));

Any help would be greatly appreciated, thanks in advance!


Solution

  • You can find the code in the java-spring-web library:

        @Override
        public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] body,
                                            ClientHttpRequestExecution execution) throws IOException {
            ClientHttpResponse httpResponse;
    
            Span span = tracer.buildSpan(httpRequest.getMethod().toString())
                    .withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CLIENT)
                    .start();
            tracer.inject(span.context(), Format.Builtin.HTTP_HEADERS,
                    new HttpHeadersCarrier(httpRequest.getHeaders()));
            ...
        }
    

    Refs: