-
-
Notifications
You must be signed in to change notification settings - Fork 12
/
middleware.go
313 lines (260 loc) · 7.48 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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
package sloggin
import (
"context"
"log/slog"
"net/http"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"go.opentelemetry.io/otel/trace"
)
const (
customAttributesCtxKey = "slog-gin.custom-attributes"
requestIDCtx = "slog-gin.request-id"
)
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": {},
}
// Formatted with http.CanonicalHeaderKey
RequestIDHeaderKey = "X-Request-Id"
)
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 gin.HandlerFunc (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) gin.HandlerFunc {
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 gin.HandlerFunc (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) gin.HandlerFunc {
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 gin.HandlerFunc (middleware) that logs requests using slog.
func NewWithConfig(logger *slog.Logger, config Config) gin.HandlerFunc {
return func(c *gin.Context) {
start := time.Now()
path := c.Request.URL.Path
query := c.Request.URL.RawQuery
params := map[string]string{}
for _, p := range c.Params {
params[p.Key] = p.Value
}
requestID := c.GetHeader(RequestIDHeaderKey)
if config.WithRequestID {
if requestID == "" {
requestID = uuid.New().String()
c.Header(RequestIDHeaderKey, requestID)
}
c.Set(requestIDCtx, requestID)
}
// dump request body
br := newBodyReader(c.Request.Body, RequestBodyMaxSize, config.WithRequestBody)
c.Request.Body = br
// dump response body
bw := newBodyWriter(c.Writer, ResponseBodyMaxSize, config.WithResponseBody)
c.Writer = bw
c.Next()
status := c.Writer.Status()
method := c.Request.Method
host := c.Request.Host
route := c.FullPath()
end := time.Now()
latency := end.Sub(start)
userAgent := c.Request.UserAgent()
ip := c.ClientIP()
referer := c.Request.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, requestID))
}
// otel
baseAttributes = append(baseAttributes, extractTraceSpanID(c.Request.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 c.Request.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", bw.bytes))
if config.WithResponseBody {
responseAttributes = append(responseAttributes, slog.String("body", bw.body.String()))
}
// response headers
if config.WithResponseHeader {
kv := []any{}
for k, v := range c.Writer.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, ok := c.Get(customAttributesCtxKey); ok {
switch attrs := v.(type) {
case []slog.Attr:
attributes = append(attributes, attrs...)
}
}
for _, filter := range config.Filters {
if !filter(c) {
return
}
}
level := config.DefaultLevel
msg := "Incoming request"
if status >= http.StatusBadRequest && status < http.StatusInternalServerError {
level = config.ClientErrorLevel
msg = c.Errors.String()
} else if status >= http.StatusInternalServerError {
level = config.ServerErrorLevel
msg = c.Errors.String()
}
logger.LogAttrs(c.Request.Context(), level, msg, attributes...)
}
}
// GetRequestID returns the request identifier.
func GetRequestID(c *gin.Context) string {
requestID, ok := c.Get(requestIDCtx)
if !ok {
return ""
}
if id, ok := requestID.(string); ok {
return id
}
return ""
}
// AddCustomAttributes adds custom attributes to the request context.
func AddCustomAttributes(c *gin.Context, attr slog.Attr) {
v, exists := c.Get(customAttributesCtxKey)
if !exists {
c.Set(customAttributesCtxKey, []slog.Attr{attr})
return
}
switch attrs := v.(type) {
case []slog.Attr:
c.Set(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
}