From 447a255d18a182668b0965481dffa09b2ca93eb1 Mon Sep 17 00:00:00 2001 From: Evgeniy Kulikov Date: Thu, 20 Aug 2020 02:28:16 +0300 Subject: [PATCH] Add func to debug requests - logging middleware - response writer with status code Signed-off-by: Evgeniy Kulikov --- api/router.go | 39 +++++++++++++++++++++++++++++++++++++-- 1 file changed, 37 insertions(+), 2 deletions(-) diff --git a/api/router.go b/api/router.go index 0f47817c..c947ac5d 100644 --- a/api/router.go +++ b/api/router.go @@ -79,6 +79,11 @@ type ( // mimeType represents various MIME type used API responses. mimeType string + + logResponseWriter struct { + http.ResponseWriter + statusCode int + } ) const ( @@ -93,6 +98,13 @@ const ( mimeXML mimeType = "application/xml" ) +var _ = logErrorResponse + +func (lrw *logResponseWriter) WriteHeader(code int) { + lrw.statusCode = code + lrw.ResponseWriter.WriteHeader(code) +} + func setRequestID(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // generate random UUIDv4 @@ -114,6 +126,24 @@ func setRequestID(h http.Handler) http.Handler { }) } +func logErrorResponse(l *zap.Logger) mux.MiddlewareFunc { + return func(h http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + lw := &logResponseWriter{ResponseWriter: w} + + // pass execution: + h.ServeHTTP(lw, r) + + // Ignore <300 status codes + if lw.statusCode >= http.StatusMultipleChoices { + l.Error("something went wrong", + zap.Int("status", lw.statusCode), + zap.String("method", mux.CurrentRoute(r).GetName())) + } + }) + } +} + func GetRequestID(v interface{}) string { switch t := v.(type) { case context.Context: @@ -128,8 +158,13 @@ func GetRequestID(v interface{}) string { func Attach(r *mux.Router, m MaxClients, h Handler, center *auth.Center, log *zap.Logger) { api := r.PathPrefix(SlashSeparator).Subrouter() - // Attach behaviors: RequestID, ... - api.Use(setRequestID) + api.Use( + // -- prepare request + setRequestID, + + // -- logging error requests + // logErrorResponse(log), + ) // Attach user authentication for all S3 routes. AttachUserAuth(api, center, log)