-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
middleware.go
292 lines (243 loc) · 7.61 KB
/
middleware.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
package slogchi
import (
"context"
"log/slog"
"net/http"
"strconv"
"strings"
"time"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"go.opentelemetry.io/otel/trace"
)
type customAttributesCtxKeyType struct{}
var customAttributesCtxKey = customAttributesCtxKeyType{}
var (
TraceIDKey = "trace_id"
SpanIDKey = "span_id"
RequestIDKey = "id"
RequestBodyMaxSize = 64 * 1024 // 64KB
ResponseBodyMaxSize = 64 * 1024 // 64KB
HiddenRequestHeaders = map[string]struct{}{
"authorization": {},
"cookie": {},
"set-cookie": {},
"x-auth-token": {},
"x-csrf-token": {},
"x-xsrf-token": {},
}
HiddenResponseHeaders = map[string]struct{}{
"set-cookie": {},
}
)
type Config struct {
DefaultLevel slog.Level
ClientErrorLevel slog.Level
ServerErrorLevel slog.Level
WithUserAgent bool
WithRequestID bool
WithRequestBody bool
WithRequestHeader bool
WithResponseBody bool
WithResponseHeader bool
WithSpanID bool
WithTraceID bool
Filters []Filter
}
// New returns a `func(http.Handler) http.Handler` (middleware) that logs requests using slog.
//
// Requests with errors are logged using slog.Error().
// Requests without errors are logged using slog.Info().
func New(logger *slog.Logger) func(http.Handler) http.Handler {
return NewWithConfig(logger, Config{
DefaultLevel: slog.LevelInfo,
ClientErrorLevel: slog.LevelWarn,
ServerErrorLevel: slog.LevelError,
WithUserAgent: false,
WithRequestID: true,
WithRequestBody: false,
WithRequestHeader: false,
WithResponseBody: false,
WithResponseHeader: false,
WithSpanID: false,
WithTraceID: false,
Filters: []Filter{},
})
}
// NewWithFilters returns a `func(http.Handler) http.Handler` (middleware) that logs requests using slog.
//
// Requests with errors are logged using slog.Error().
// Requests without errors are logged using slog.Info().
func NewWithFilters(logger *slog.Logger, filters ...Filter) func(http.Handler) http.Handler {
return NewWithConfig(logger, Config{
DefaultLevel: slog.LevelInfo,
ClientErrorLevel: slog.LevelWarn,
ServerErrorLevel: slog.LevelError,
WithUserAgent: false,
WithRequestID: true,
WithRequestBody: false,
WithRequestHeader: false,
WithResponseBody: false,
WithResponseHeader: false,
WithSpanID: false,
WithTraceID: false,
Filters: filters,
})
}
// NewWithConfig returns a `func(http.Handler) http.Handler` (middleware) that logs requests using slog.
func NewWithConfig(logger *slog.Logger, config Config) 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()
path := r.URL.Path
query := r.URL.RawQuery
// dump request body
br := newBodyReader(r.Body, RequestBodyMaxSize, config.WithRequestBody)
r.Body = br
// dump response body
ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
var bw *bodyWriter
if config.WithResponseBody {
bw = newBodyWriter(ResponseBodyMaxSize)
ww.Tee(bw)
}
defer func() {
params := map[string]string{}
for i, k := range chi.RouteContext(r.Context()).URLParams.Keys {
params[k] = chi.RouteContext(r.Context()).URLParams.Values[i]
}
status := ww.Status()
method := r.Method
host := r.Host
route := chi.RouteContext(r.Context()).RoutePattern()
end := time.Now()
latency := end.Sub(start)
userAgent := r.UserAgent()
ip := r.RemoteAddr
referer := r.Referer()
baseAttributes := []slog.Attr{}
requestAttributes := []slog.Attr{
slog.Time("time", start.UTC()),
slog.String("method", method),
slog.String("host", host),
slog.String("path", path),
slog.String("query", query),
slog.Any("params", params),
slog.String("route", route),
slog.String("ip", ip),
slog.String("referer", referer),
}
responseAttributes := []slog.Attr{
slog.Time("time", end.UTC()),
slog.Duration("latency", latency),
slog.Int("status", status),
}
if config.WithRequestID {
baseAttributes = append(baseAttributes, slog.String(RequestIDKey, middleware.GetReqID(r.Context())))
}
// otel
baseAttributes = append(baseAttributes, extractTraceSpanID(r.Context(), config.WithTraceID, config.WithSpanID)...)
// request body
requestAttributes = append(requestAttributes, slog.Int("length", br.bytes))
if config.WithRequestBody {
requestAttributes = append(requestAttributes, slog.String("body", br.body.String()))
}
// request headers
if config.WithRequestHeader {
kv := []any{}
for k, v := range r.Header {
if _, found := HiddenRequestHeaders[strings.ToLower(k)]; found {
continue
}
kv = append(kv, slog.Any(k, v))
}
requestAttributes = append(requestAttributes, slog.Group("header", kv...))
}
if config.WithUserAgent {
requestAttributes = append(requestAttributes, slog.String("user-agent", userAgent))
}
// response body
responseAttributes = append(responseAttributes, slog.Int("length", ww.BytesWritten()))
if config.WithResponseBody {
responseAttributes = append(responseAttributes, slog.String("body", bw.body.String()))
}
// response headers
if config.WithResponseHeader {
kv := []any{}
for k, v := range w.Header() {
if _, found := HiddenResponseHeaders[strings.ToLower(k)]; found {
continue
}
kv = append(kv, slog.Any(k, v))
}
responseAttributes = append(responseAttributes, slog.Group("header", kv...))
}
attributes := append(
[]slog.Attr{
{
Key: "request",
Value: slog.GroupValue(requestAttributes...),
},
{
Key: "response",
Value: slog.GroupValue(responseAttributes...),
},
},
baseAttributes...,
)
// custom context values
if v := r.Context().Value(customAttributesCtxKey); v != nil {
switch attrs := v.(type) {
case []slog.Attr:
attributes = append(attributes, attrs...)
}
}
for _, filter := range config.Filters {
if !filter(ww, r) {
return
}
}
level := config.DefaultLevel
if status >= http.StatusInternalServerError {
level = config.ServerErrorLevel
} else if status >= http.StatusBadRequest && status < http.StatusInternalServerError {
level = config.ClientErrorLevel
}
logger.LogAttrs(r.Context(), level, strconv.Itoa(status)+": "+http.StatusText(status), attributes...)
}()
next.ServeHTTP(ww, r)
})
}
}
// AddCustomAttributes adds custom attributes to the request context.
func AddCustomAttributes(r *http.Request, attr slog.Attr) {
v := r.Context().Value(customAttributesCtxKey)
if v == nil {
*r = *r.WithContext(context.WithValue(r.Context(), customAttributesCtxKey, []slog.Attr{attr}))
return
}
switch attrs := v.(type) {
case []slog.Attr:
*r = *r.WithContext(context.WithValue(r.Context(), customAttributesCtxKey, append(attrs, attr)))
}
}
func extractTraceSpanID(ctx context.Context, withTraceID bool, withSpanID bool) []slog.Attr {
if !(withTraceID || withSpanID) {
return []slog.Attr{}
}
span := trace.SpanFromContext(ctx)
if !span.IsRecording() {
return []slog.Attr{}
}
attrs := []slog.Attr{}
spanCtx := span.SpanContext()
if withTraceID && spanCtx.HasTraceID() {
traceID := trace.SpanFromContext(ctx).SpanContext().TraceID().String()
attrs = append(attrs, slog.String(TraceIDKey, traceID))
}
if withSpanID && spanCtx.HasSpanID() {
spanID := spanCtx.SpanID().String()
attrs = append(attrs, slog.String(SpanIDKey, spanID))
}
return attrs
}