-
Notifications
You must be signed in to change notification settings - Fork 0
/
logger.go
61 lines (51 loc) · 1.18 KB
/
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package main
import (
"context"
"log/slog"
"net/http"
"github.com/google/uuid"
)
type ctxKey string
const (
slogFields ctxKey = "slog_fields"
)
type SlogContextHandler struct {
slog.Handler
}
func (s SlogContextHandler) Handle(c context.Context, r slog.Record) error {
if attrs, ok := c.Value(slogFields).([]slog.Attr); ok {
for _, v := range attrs {
r.AddAttrs(v)
}
}
return s.Handler.Handle(c, r)
}
func AppendCtx(c context.Context, attrs []slog.Attr) context.Context {
if c == nil {
c = context.Background()
}
if v, ok := c.Value(slogFields).([]slog.Attr); ok {
v = append(v, attrs...)
return context.WithValue(c, slogFields, v)
}
v := []slog.Attr{}
v = append(v, attrs...)
return context.WithValue(c, slogFields, v)
}
func logMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := AppendCtx(
r.Context(),
[]slog.Attr{
slog.String("request_id", uuid.New().String()),
slog.Group(
"request",
slog.String("url", r.URL.String()),
slog.String("method", r.Method),
slog.String("user_agent", r.UserAgent()),
),
},
)
next.ServeHTTP(w, r.WithContext(ctx))
})
}