Opentememetry Zuul integration

157 views Asked by At

I'm trying with no success to integrate Opentelemetry with Zuul using Spring Boot. What I'm trying to do is to pass Opentelemetry context from Zuul to other microservices in the chain and when the response came into Zuul close the trace

(Create trace) Zuul --call--> (new Span) Microservice A --call--> (new Span) Microservice B

(Close trace ) Zuul <--response-- Microservice A <-response-- Microservice B

Anyone has made something similar to this?

1

There are 1 answers

0
Ares91 On

I solved this way:

@Component
public class HeaderRequestFilter extends ZuulFilter {
    
    @Autowired
    private Tracer tracer;
    
    @Override
    public int filterOrder() {
        // run before PreDecoration
        return FilterConstants.PRE_DECORATION_FILTER_ORDER - 1;
    }

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
                
        RequestContext ctx = RequestContext.getCurrentContext();

        Span span = tracer.spanBuilder(ctx.getRequest().getRequestURI()).startSpan();
        span.setAttribute("eurekaInstanceId", eurekaInstanceId);        
        tracer.withSpan(span);
        
        OpenTelemetry.getPropagators().getTextMapPropagator().inject(Context.current(), ctx, new Setter<RequestContext>() {
            @Override
            public void set(RequestContext carrier, String key, String value) {             
                carrier.addZuulRequestHeader(key, value);
            }
        });

        return null;
    }
}

and the response, where the span is closed

@Component
public class HeaderResponseFilter extends ZuulFilter {

    @Autowired
    private Tracer tracer;
    
    
    @Override
    public int filterOrder() {
        // Run before PreDecoration
        return FilterConstants.PRE_DECORATION_FILTER_ORDER - 1; 
    }

    @Override
    public String filterType() {
        return FilterConstants.POST_TYPE;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        // Close span
        tracer.getCurrentSpan().end();
        
        return null;
    }
}