-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlogger.go
More file actions
44 lines (37 loc) · 1011 Bytes
/
Copy pathlogger.go
File metadata and controls
44 lines (37 loc) · 1011 Bytes
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 httpmw
import (
"log/slog"
"net/http"
"time"
)
type RequestLoggerOptions struct {
Logger *slog.Logger
IncludeUserAgent bool
}
// RequestLogger writes a structured log entry for each completed request.
func RequestLogger(opts RequestLoggerOptions) Middleware {
logger := opts.Logger
if logger == nil {
logger = slog.Default()
}
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
startedAt := time.Now()
recorder := newResponseRecorder(w)
next.ServeHTTP(recorder, r)
fields := []any{
"method", r.Method,
"path", r.URL.Path,
"status", recorder.statusCode,
"bytes", recorder.bytesWritten,
"latency", time.Since(startedAt).String(),
"request_id", GetRequestID(r.Context()),
"client_ip", GetClientIP(r.Context()),
}
if opts.IncludeUserAgent {
fields = append(fields, "user_agent", r.UserAgent())
}
logger.Info("http request completed", fields...)
})
}
}