-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandler.go
More file actions
60 lines (50 loc) · 1.41 KB
/
handler.go
File metadata and controls
60 lines (50 loc) · 1.41 KB
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
package oops
import (
"context"
"errors"
"log/slog"
)
// attrField is the field used to log oops error attributes.
var attrField = "oops"
// Handler logs oops errors with additional context.
type Handler struct {
slog.Handler
}
// NewOopsHandler creates a handler that logs oops errors with additional context.
func NewOopsHandler(handler slog.Handler) slog.Handler {
return &Handler{
Handler: handler,
}
}
func (h Handler) WithAttrs(attrs []slog.Attr) slog.Handler {
return &Handler{Handler: h.Handler.WithAttrs(attrs)}
}
func (h Handler) WithGroup(name string) slog.Handler {
return &Handler{Handler: h.Handler.WithGroup(name)}
}
// Handle implements slog.Handler.
func (h Handler) Handle(ctx context.Context, record slog.Record) error {
newRecord := slog.NewRecord(record.Time, record.Level, record.Message, record.PC)
record.Attrs(func(attr slog.Attr) bool {
if err, ok := attr.Value.Any().(error); ok {
var oops *Error
if errors.As(err, &oops) {
newRecord.AddAttrs(slog.Any(attr.Key, oops.err))
if attrs := oops.LogAttrs(); len(attrs) > 0 {
newRecord.AddAttrs(slog.Any(attrField, attrs))
}
} else {
newRecord.AddAttrs(attr)
}
return true
}
newRecord.AddAttrs(attr)
return true
})
return h.Handler.Handle(ctx, newRecord)
}
// SetAttrField overrides the field used to oops error attributes.
// default is "oops".
func SetAttrField(field string) {
attrField = field
}