Closed bentcoder closed 2 years ago
Managed.
package middleware
import (
"context"
"net/http"
"github.com/rs/xid"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)
type requestID string
const requestIDKey = requestID("request_id")
func RequestID(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
id := xid.New().String()
log.Logger.UpdateContext(func(c zerolog.Context) zerolog.Context {
return c.Str(string(requestIDKey), id)
})
w.Header().Set("X-Request-ID", id)
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), requestIDKey, id)))
})
}
Hi,
Wondering if I missed something or this feature doesn't exist.
Is there a way to pass
r.Context()
to logger and let it automatically extract value so that each log entry would have... "request_id":"SOME-UUID" ...
? As you can see below, each of my HTTP request would have an ID in context.Thanks