diff options
Diffstat (limited to 'middleware/logger.go')
-rw-r--r-- | middleware/logger.go | 48 |
1 files changed, 48 insertions, 0 deletions
diff --git a/middleware/logger.go b/middleware/logger.go new file mode 100644 index 0000000..80117da --- /dev/null +++ b/middleware/logger.go @@ -0,0 +1,48 @@ +package middleware + +import ( + "log/slog" + "net/http" + "time" + + "go.neonxp.ru/mux" +) + +type wrappedResponse struct { + http.ResponseWriter + statusCode int +} + +func (w *wrappedResponse) WriteHeader(code int) { + w.statusCode = code + w.ResponseWriter.WriteHeader(code) +} + +func Logger(logger *slog.Logger) mux.Middleware { + return func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requestID := GetRequestID(r) + args := []any{ + slog.String("proto", r.Proto), + slog.String("method", r.Method), + slog.String("request_uri", r.RequestURI), + slog.String("request_id", requestID), + } + logger.InfoContext( + r.Context(), + "start request", + args..., + ) + t := time.Now() + wr := &wrappedResponse{ResponseWriter: w, statusCode: http.StatusOK} + next.ServeHTTP(wr, r) + args = append(args, slog.String("response_time", time.Since(t).String())) + args = append(args, slog.Int("response_status", wr.statusCode)) + logger.InfoContext( + r.Context(), + "finish request", + args..., + ) + }) + } +} |