linstrom/server-old/middlewares/injectLogger.go

21 lines
581 B
Go
Raw Normal View History

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