From 186e00577dcddf4df4fb4425697d14545bc2542b Mon Sep 17 00:00:00 2001 From: Gabe Farrell Date: Wed, 30 Apr 2025 18:25:24 -0400 Subject: [PATCH] add status code and latency to request log --- middleware.go | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/middleware.go b/middleware.go index 71365d5..50a4cf5 100644 --- a/middleware.go +++ b/middleware.go @@ -36,10 +36,25 @@ func newRebuildStaleIdMapMiddleware(idMap *ConcurrentMap) func(http.HandlerFunc) } } +type statusResponseWriter struct { + http.ResponseWriter + status int +} + +func (w *statusResponseWriter) WriteHeader(code int) { + w.status = code + w.ResponseWriter.WriteHeader(code) +} + func loggerMiddleware(next http.HandlerFunc) http.HandlerFunc { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - log.Print(RequestString(r)) - next.ServeHTTP(w, r) + start := time.Now() + + srw := &statusResponseWriter{ResponseWriter: w, status: http.StatusOK} // default to 200 + next.ServeHTTP(srw, r) + + duration := time.Since(start) + log.Printf("%s - %d %s - %v", RequestString(r), srw.status, http.StatusText(srw.status), duration) }) }