-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaccess_logger.go
44 lines (40 loc) · 1.26 KB
/
access_logger.go
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
40
41
42
43
44
package midfabs
import (
"log/slog"
"net/http"
"time"
)
// responseWriter encapsulates http.ResponseWriter along with an additional
// status int field. It is used in AccessLogger to capture response status
// before the encapsulated ResponseWriter calls WriteHeader.
type responseWriter struct {
http.ResponseWriter
status int
}
// WriteHeader sets rw's status before the encapsulated ResponseWriter calls
// WriteHeader.
func (rw *responseWriter) WriteHeader(statusCode int) {
rw.status = statusCode
rw.ResponseWriter.WriteHeader(statusCode)
}
// AccessLogger returns a middleware that uses slog logger to track request and
// response details.
func AccessLogger(logger *slog.Logger, prefix string) func(h http.Handler) http.Handler {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
rw := &responseWriter{ResponseWriter: w}
h.ServeHTTP(rw, r)
logger.Info(
prefix,
slog.Int("status", rw.status),
slog.Duration("duration", time.Since(start)),
slog.String("method", r.Method),
slog.String("proto", r.Proto),
slog.String("dest", r.URL.RequestURI()),
slog.String("src", r.RemoteAddr),
slog.String("agent", r.Header.Get("User-Agent")),
)
})
}
}