logginghandler/logginghandler.go

45 lines
1.1 KiB
Go
Raw Normal View History

2021-01-18 11:46:22 +01:00
// Package logginghandler is a simple, zerolog based, request logging http middleware.
// It also sets `X-Request-ID` in the request and response headers.
2020-10-13 15:26:40 +02:00
package logginghandler
import (
"net/http"
"github.com/google/uuid"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)
2021-01-18 11:46:22 +01:00
// GetUUID gets the requests UUID from a request.
2020-10-13 15:26:40 +02:00
func GetUUID(r *http.Request) string {
return r.Header.Get("X-Request-ID")
}
2021-01-18 11:46:22 +01:00
// Logger returns a logger with the UUID set.
2020-10-13 15:26:40 +02:00
func Logger(r *http.Request) zerolog.Logger {
logger := log.With().Str("uuid", GetUUID(r)).Logger()
return logger
}
2021-01-18 11:46:22 +01:00
// Handler is the http middleware handler.
2020-10-13 15:26:40 +02:00
func Handler(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
uuid := uuid.New().String()
r.Header.Set("X-Request-ID", uuid)
logger := Logger(r)
logger.Info().
Str("uuid", uuid).
Str("method", r.Method).
Str("user-agent", r.UserAgent()).
Str("proto", r.Proto).
Str("referer", r.Referer()).
Str("request-url", r.URL.String()).
Str("remote", r.RemoteAddr).
Msg("")
w.Header().Set("X-Request-ID", uuid)
next.ServeHTTP(w, r)
})
}