goutils/middleware/zerolog.go
mStar 9d803a94ee
Add middlewares
- Builder for chaining multiple middlewares on top of a base handler
- Middleware for adding a map of values to the request context
- Middleware for adding zerolog logging to the request
2024-11-26 17:30:05 +01:00

32 lines
745 B
Go

package middleware
import (
"net/http"
"strings"
"time"
"github.com/rs/zerolog/hlog"
"github.com/rs/zerolog/log"
)
func LoggingMiddleware(handler http.Handler) http.Handler {
return ChainMiddlewares(handler,
hlog.NewHandler(log.Logger),
hlog.AccessHandler(func(r *http.Request, status, size int, duration time.Duration) {
if strings.HasPrefix(r.URL.Path, "/assets") {
return
}
hlog.FromRequest(r).Info().
Str("method", r.Method).
Stringer("url", r.URL).
Int("status", status).
Int("size", size).
Dur("duration", duration).
Send()
}),
hlog.RemoteAddrHandler("ip"),
hlog.UserAgentHandler("user_agent"),
hlog.RefererHandler("referer"),
hlog.RequestIDHandler("req_id", "Request-Id"),
)
}