rs / zerolog

Zero Allocation JSON Logger
MIT License
10.62k stars 572 forks source link

[Question] Extracting values from HTTP request Context #495

Closed bentcoder closed 2 years ago

bentcoder commented 2 years ago

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

package middleware

import (
    "context"
    "net/http"

    "github.com/google/uuid"
)

type ctxID string

const CtxIDKey = ctxID("request_id")

func RequestID(h http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        h.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), CtxIDKey, uuid.New().String())))
    })
}
bentcoder commented 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)))
    })
}