1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
package server
import (
"log/slog"
"net/http"
"time"
)
type statusRecorder struct {
http.ResponseWriter
status int
}
func (r *statusRecorder) WriteHeader(code int) {
r.ResponseWriter.WriteHeader(code)
r.status = code
}
func logRequests(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
recorder := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
next.ServeHTTP(recorder, r)
attrs := []slog.Attr{
slog.String("method", r.Method),
slog.String("path", r.URL.Path),
slog.Int("status", recorder.status),
slog.Duration("duration", time.Since(start)),
slog.String("remote", r.RemoteAddr),
}
if xff := r.Header.Get("x-forwarded-for"); xff != "" {
attrs = append(attrs, slog.String("x-forwarded-for", xff))
}
slog.LogAttrs(r.Context(), slog.LevelInfo, "request", attrs...)
})
}
|