Skip to content

Commit

Permalink
httptransport: add request ID to profiler labels
Browse files Browse the repository at this point in the history
This should allow for cross-referencing traces and profiles.

Signed-off-by: Hank Donnay <[email protected]>
  • Loading branch information
hdonnay committed Jul 6, 2023
1 parent caba76e commit 86f7a86
Showing 1 changed file with 10 additions and 3 deletions.
13 changes: 10 additions & 3 deletions httptransport/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"mime"
"net/http"
"path"
"runtime/pprof"
"sort"
"strconv"
"strings"
Expand Down Expand Up @@ -126,16 +127,22 @@ var idPool = sync.Pool{
},
}

// WithRequestID sets up a per-request ID and annotates the logging context and
// profile labels.
func withRequestID(r *http.Request) *http.Request {
const key = `request_id`
const profile = `profile_id`
ctx := r.Context()
sctx := trace.SpanContextFromContext(ctx)
var tid string
if sctx.HasTraceID() {
ctx = zlog.ContextWithValues(ctx, key, sctx.TraceID().String())
tid = sctx.TraceID().String()
} else {
rng := idPool.Get().(*rand.Rand)
ctx = zlog.ContextWithValues(ctx, key, fmt.Sprintf("%016x", rng.Uint64()))
idPool.Put(rng)
defer idPool.Put(rng)
tid = fmt.Sprintf("%016x", rng.Uint64())
}
ctx = zlog.ContextWithValues(ctx, key, tid)
ctx = pprof.WithLabels(ctx, pprof.Labels(profile, tid))
return r.WithContext(ctx)
}

0 comments on commit 86f7a86

Please sign in to comment.