forked from samber/slog-multi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patherrors.go
45 lines (36 loc) · 909 Bytes
/
errors.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
package main
import (
"context"
"reflect"
"log/slog"
)
func errorFormattingMiddleware(ctx context.Context, record slog.Record, next func(context.Context, slog.Record) error) error {
attrs := []slog.Attr{}
record.Attrs(func(attr slog.Attr) bool {
key := attr.Key
value := attr.Value
kind := attr.Value.Kind()
if key == "error" && kind == slog.KindAny {
if err, ok := value.Any().(error); ok {
errType := reflect.TypeOf(err).String()
msg := err.Error()
attrs = append(
attrs,
slog.Group("error",
slog.String("type", errType),
slog.String("message", msg),
),
)
} else {
attrs = append(attrs, attr)
}
} else {
attrs = append(attrs, attr)
}
return true
})
// new record with formatted error
record = slog.NewRecord(record.Time, record.Level, record.Message, record.PC)
record.AddAttrs(attrs...)
return next(ctx, record)
}