Getting two traceId and spanId in my MDC logs

257 Views Asked by At

I am using opentelemetry for distributed logging. I have a TracingFilter from which I am putting the traceId and spanId in MDC so that I can use it later for some tracking purpose.

TracingFilter.java

public class TracingFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
            ServletException {
        Tracer tracer = OpenTelemetrySdk.builder()
                        .setTracerProvider(SdkTracerProvider.builder().build()).build()
                        .getTracer("oTelTracer");
        Span restSpan = tracer.spanBuilder("restSpan").setParent(Context.root()).startSpan();
        MDC.put("traceId", restSpan.getSpanContext().getTraceId());
        MDC.put("spanId", restSpan.getSpanContext().getSpanId());
        chain.doFilter(request, response);
    }
}

When I see logs I can see two traceIds in like this

[traceId=24bfdd47cbca0307, spanId=Vd7kdIYE4jIkv91Hy8oDByS/3UfLygMHAAAAAAAAAAA=, corrId=65a48a13-93cb-497b-a1d3-025b95351b40, trace_id=74f80fbcdcf3ecda30f0d62956c3d67a, trace_flags=01, span_id=a95f524c0383f822]

I want only one traceId in my logs. What am I missing here?

I have tried to change how Tracer is created.

1

There are 1 best solutions below

1
On

Always clear the MDC after use. The MDC is tied to a thread but thread pooling can make it visible to subsequent requests.

public class TracingFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
            ServletException {
        Tracer tracer = OpenTelemetrySdk.builder()
                        .setTracerProvider(SdkTracerProvider.builder().build()).build()
                        .getTracer("oTelTracer");
        Span restSpan = tracer.spanBuilder("restSpan").setParent(Context.root()).startSpan();
        try {
            MDC.put("traceId", restSpan.getSpanContext().getTraceId());
            MDC.put("spanId", restSpan.getSpanContext().getSpanId());
            chain.doFilter(request, response);
        } finally {
            MDC.clear();
        }
    }
}