linstrom/server/middlewares/injectLogrus.go

21 lines
552 B
Go
Raw Normal View History

2024-05-31 09:54:39 +00:00
package middlewares
import (
"context"
"net/http"
"github.com/sirupsen/logrus"
)
const CONTEXT_KEY_LOGRUS = ContextKey("logrus")
// Inject a logrus entry into the context that has the url path already set
func InjectLogrusMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
reqContext := r.Context()
entry := logrus.WithField("url-path", r.URL.Path)
newContext := context.WithValue(reqContext, CONTEXT_KEY_LOGRUS, entry)
next.ServeHTTP(w, r.WithContext(newContext))
})
}