summaryrefslogblamecommitdiff
path: root/middleware/logger.go
blob: 80117da50fc4305cdbc4b5308a94d37e39b9b018 (plain) (tree)















































                                                                                                 
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...,
			)
		})
	}
}