59 lines
1.5 KiB
Go
59 lines
1.5 KiB
Go
package webutils
|
|
|
|
import (
|
|
"net/http"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/rs/zerolog/hlog"
|
|
"github.com/rs/zerolog/log"
|
|
)
|
|
|
|
func BuildLoggingMiddleware(extras map[string]string) HandlerBuilder {
|
|
return func(h http.Handler) http.Handler {
|
|
return ChainMiddlewares(h,
|
|
hlog.NewHandler(log.Logger),
|
|
hlog.AccessHandler(func(r *http.Request, status, size int, duration time.Duration) {
|
|
if strings.HasPrefix(r.URL.Path, "/assets") {
|
|
return
|
|
}
|
|
logger := hlog.FromRequest(r).Info().
|
|
Str("method", r.Method).
|
|
Stringer("url", r.URL).
|
|
Int("status", status).
|
|
Int("size", size).
|
|
Dur("duration", duration)
|
|
for k, v := range extras {
|
|
logger = logger.Str(k, v)
|
|
}
|
|
logger.Send()
|
|
}),
|
|
hlog.RemoteAddrHandler("ip"),
|
|
hlog.UserAgentHandler("user_agent"),
|
|
hlog.RefererHandler("referer"),
|
|
hlog.RequestIDHandler("req_id", "Request-Id"),
|
|
)
|
|
}
|
|
}
|
|
|
|
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"),
|
|
)
|
|
}
|