connectrpc / otelconnect-go

OpenTelemetry tracing and metrics for Connect.
https://connectrpc.com
Apache License 2.0
123 stars 27 forks source link

Make span available in http.Request Context #164

Open abh opened 5 months ago

abh commented 5 months ago

I don't know fi this is an otelconnect issue or a general connectrpc issue (I'm new to both).

I have a mix of interceptors (including this one) and http.Handlers. It'd be very helpful if this interceptor added the request span to the http.Request context.

Right now to have tracing in the http.Handler middleware I have to use otelhttp which adds another span to the trace, or do similar work to "recapture" the traceparent from the incoming headers.

emcfarlane commented 5 months ago

Hey @abh , it currently isn't possible to update the requests context from an interceptor as the interceptor will always be called within the connect handler. Updating the context using WithContext creates a shallow copy so any changes to the request won't be visible outside. We are looking at improving support for HTTP middleware by adding Handler and Client options for middleware in connect-go.

emcfarlane commented 5 months ago

As a workaround for this issue you may create a new middleware layer above the authn middleware to set a parent trace and attach it to the request context. This will provide all subsequent middleware and interceptors with access to the span. As an example:

func RequestStartMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        ctx, span := trace.StartSpan(r.Context(), "observability.RequestStart")
        defer span.End()
        next.ServeHTTP(w, r.WithContext(ctx))
    })
}