-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
middleware.go
338 lines (281 loc) · 8.14 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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
package slogfiber
import (
"context"
"net/http"
"strings"
"sync"
"time"
"log/slog"
"github.com/gofiber/fiber/v2"
"github.com/google/uuid"
"github.com/valyala/fasthttp"
"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": {},
}
// 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 fiber.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) fiber.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 fiber.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) fiber.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 fiber.Handler (middleware) that logs requests using slog.
func NewWithConfig(logger *slog.Logger, config Config) fiber.Handler {
var (
once sync.Once
errHandler fiber.ErrorHandler
)
return func(c *fiber.Ctx) error {
once.Do(func() {
errHandler = c.App().ErrorHandler
})
start := time.Now()
path := c.Path()
query := string(c.Request().URI().QueryString())
requestID := c.Get(RequestIDHeaderKey)
if config.WithRequestID {
if requestID == "" {
requestID = uuid.New().String()
}
c.Context().SetUserValue("request-id", requestID)
c.Set("X-Request-ID", requestID)
}
err := c.Next()
if err != nil {
if err = errHandler(c, err); err != nil {
_ = c.SendStatus(fiber.StatusInternalServerError) //nolint:errcheck
}
}
status := c.Response().StatusCode()
method := c.Context().Method()
host := c.Hostname()
params := c.AllParams()
route := c.Route().Path
end := time.Now()
latency := end.Sub(start)
userAgent := c.Context().UserAgent()
referer := c.Get(fiber.HeaderReferer)
ip := c.Context().RemoteIP().String()
if len(c.IPs()) > 0 {
ip = c.IPs()[0]
}
baseAttributes := []slog.Attr{}
requestAttributes := []slog.Attr{
slog.Time("time", start.UTC()),
slog.String("method", string(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.Any("x-forwarded-for", c.IPs()),
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.UserContext(), config.WithTraceID, config.WithSpanID)...)
// request body
requestAttributes = append(requestAttributes, slog.Int("length", len((c.Body()))))
if config.WithRequestBody {
body := c.Body()
if len(body) > RequestBodyMaxSize {
body = body[:RequestBodyMaxSize]
}
requestAttributes = append(requestAttributes, slog.String("body", string(body)))
}
// request headers
if config.WithRequestHeader {
kv := []any{}
for k, v := range c.GetReqHeaders() {
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", string(userAgent)))
}
// response body
responseAttributes = append(responseAttributes, slog.Int("length", len(c.Response().Body())))
if config.WithResponseBody {
body := c.Response().Body()
if len(body) > ResponseBodyMaxSize {
body = body[:ResponseBodyMaxSize]
}
responseAttributes = append(responseAttributes, slog.String("body", string(body)))
}
// response headers
if config.WithResponseHeader {
kv := []any{}
for k, v := range c.GetRespHeaders() {
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 := c.Context().UserValue(customAttributesCtxKey); v != nil {
switch attrs := v.(type) {
case []slog.Attr:
attributes = append(attributes, attrs...)
}
}
for _, filter := range config.Filters {
if !filter(c) {
return err
}
}
logErr := err
if logErr == nil {
logErr = fiber.NewError(status)
}
level := config.DefaultLevel
msg := "Incoming request"
if status >= http.StatusInternalServerError {
level = config.ServerErrorLevel
msg = logErr.Error()
} else if status >= http.StatusBadRequest && status < http.StatusInternalServerError {
level = config.ClientErrorLevel
msg = logErr.Error()
}
logger.LogAttrs(c.UserContext(), level, msg, attributes...)
return err
}
}
// GetRequestID returns the request identifier.
func GetRequestID(c *fiber.Ctx) string {
return GetRequestIDFromContext(c.Context())
}
// GetRequestIDFromContext returns the request identifier from the context.
func GetRequestIDFromContext(ctx *fasthttp.RequestCtx) string {
requestID, ok := ctx.UserValue("request-id").(string)
if !ok {
return ""
}
return requestID
}
// AddCustomAttributes adds custom attributes to the request context.
func AddCustomAttributes(c *fiber.Ctx, attr slog.Attr) {
v := c.Context().UserValue(customAttributesCtxKey)
if v == nil {
c.Context().SetUserValue(customAttributesCtxKey, []slog.Attr{attr})
return
}
switch attrs := v.(type) {
case []slog.Attr:
c.Context().SetUserValue(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
}