rs/zerolog

[Question] Extracting values from HTTP request Context

bentcoder opened this issue · 1 comments

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())))
    })
}

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)))
	})
}