diff --git a/cmd/nanomdm/main.go b/cmd/nanomdm/main.go index c0d14dd..033b491 100644 --- a/cmd/nanomdm/main.go +++ b/cmd/nanomdm/main.go @@ -213,7 +213,7 @@ func main() { // Currently this just makes a random string. This would be better // served by e.g. https://github.com/oklog/ulid or something like // https://opentelemetry.io/ someday. -func newTraceID() string { +func newTraceID(_ *http.Request) string { b := make([]byte, 8) rand.Read(b) return fmt.Sprintf("%x", b) diff --git a/http/http.go b/http/http.go index 531a7a0..81849d9 100644 --- a/http/http.go +++ b/http/http.go @@ -53,10 +53,13 @@ type ctxKeyTraceID struct{} // TraceLoggingMiddleware sets up a trace ID in the request context and // logs HTTP requests. -func TraceLoggingMiddleware(next http.Handler, logger log.Logger, newTrace func() string) http.HandlerFunc { +func TraceLoggingMiddleware(next http.Handler, logger log.Logger, newTrace func(*http.Request) string) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - ctx := context.WithValue(r.Context(), ctxKeyTraceID{}, newTrace()) - ctx = ctxlog.AddFunc(ctx, ctxlog.SimpleStringFunc("trace_id", ctxKeyTraceID{})) + ctx := r.Context() + if newTrace != nil { + ctx = context.WithValue(r.Context(), ctxKeyTraceID{}, newTrace(r)) + ctx = ctxlog.AddFunc(ctx, ctxlog.SimpleStringFunc("trace_id", ctxKeyTraceID{})) + } host, _, err := net.SplitHostPort(r.RemoteAddr) if err != nil {