esbot/internal/http/logging.go

37 lines
861 B
Go

package http
import (
"net/http"
"time"
"github.com/rs/zerolog"
)
type responseWriter struct {
http.ResponseWriter
status int
wroteHeader bool
}
func wrapResponseWriter(w http.ResponseWriter) *responseWriter {
return &responseWriter{ResponseWriter: w}
}
func (w *responseWriter) WriteHeader(status int) {
if w.wroteHeader {
return
}
w.status = status
w.ResponseWriter.WriteHeader(status)
w.wroteHeader = true
}
func loggerMiddleware(logger zerolog.Logger, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
wrapped := wrapResponseWriter(w)
next.ServeHTTP(wrapped, r)
logger.Info().Int("status", wrapped.status).Dur("dur", time.Since(start)).Str("path", r.URL.Path).Str("method", r.Method).Str("path", r.URL.EscapedPath()).Msg("request processed")
})
}