logginghandler/logginghandler.go

47 lines
1.0 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/rs/zerolog"
"github.com/rs/zerolog/hlog"
2020-10-13 15:26:40 +02:00
)
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 {
uuid, ok := hlog.IDFromRequest(r)
if !ok {
return ""
}
return uuid.String()
2020-10-13 15:26:40 +02:00
}
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 {
return *hlog.FromRequest(r)
2020-10-13 15:26:40 +02:00
}
// Handler sets up all the logging.
func Handler(logger zerolog.Logger) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return hlog.NewHandler(logger)(
hlog.RemoteAddrHandler("remote")(
hlog.UserAgentHandler("user-agent")(
hlog.RefererHandler("referer")(
hlog.MethodHandler("method")(
hlog.RequestIDHandler("uuid", "X-Request-ID")(
hlog.URLHandler("request-url")(
next,
),
),
),
),
),
),
)
}
2020-10-13 15:26:40 +02:00
}