/
t3
/
iam-server
Обзор
Документация
Войти
/
t3
/
iam-server
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
master
internal/api/logging.go
49 строк
1 KB
Ivan
end-to-end logging
25 июл 2026, 00:10
25 июл 2026, 00:10
9eec47f
Код
Авторство
О чём код?
package api import ( "log/slog" "net/http" "time" ) // statusRecorder wraps http.ResponseWriter to capture the status code and byte count. type statusRecorder struct { http.ResponseWriter status int written int64 } func (r *statusRecorder) WriteHeader(code int) { r.status = code r.ResponseWriter.WriteHeader(code) } func (r *statusRecorder) Write(b []byte) (int, error) { if r.status == 0 { r.status = http.StatusOK } n, err := r.ResponseWriter.Write(b) r.written += int64(n) return n, err } // LoggingMiddleware logs every request with method, path, status, duration, bytes, and request_id. func LoggingMiddleware(logger *slog.Logger) func(http.Handler) http.Handler { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { start := time.Now() sr := &statusRecorder{ResponseWriter: w, status: http.StatusOK} next.ServeHTTP(sr, r) logger.Info("request", "method", r.Method, "path", r.URL.Path, "status", sr.status, "bytes", sr.written, "duration", time.Since(start).String(), "request_id", RequestIDFromContext(r.Context()), ) }) } }