linstrom/server-old/middlewares/injectLogger.go
2024-08-22 19:57:53 +02:00

20 lines
581 B
Go

package middlewares
import (
"context"
"net/http"
"github.com/rs/zerolog/log"
)
const CONTEXT_KEY_LOGRUS = ContextKey("logrus")
// Inject a logrus entry into the context that has the url path already set
func InjectLoggerMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
reqContext := r.Context()
logger := log.With().Ctx(r.Context()).Str("url-path", r.URL.RawPath).Logger()
newContext := context.WithValue(reqContext, CONTEXT_KEY_LOGRUS, &logger)
next.ServeHTTP(w, r.WithContext(newContext))
})
}