/
handler.go
68 lines (56 loc) · 1.82 KB
/
handler.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
package logger
import (
"context"
"log/slog"
)
// logHandler provides a wrapper around the slog handler to capture which
// log level is being logged for event handling.
type logHandler struct {
handler slog.Handler
events Events
}
func newLogHandler(handler slog.Handler, events Events) *logHandler {
return &logHandler{
handler: handler,
events: events,
}
}
// Enabled reports whether the handler handles records at the given level.
// The handler ignores records whose level is lower.
func (h *logHandler) Enabled(ctx context.Context, level slog.Level) bool {
return h.handler.Enabled(ctx, level)
}
// WithAttrs returns a new JSONHandler whose attributes consists
// of h's attributes followed by attrs.
func (h *logHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
return &logHandler{handler: h.handler.WithAttrs(attrs), events: h.events}
}
// WithGroup returns a new Handler with the given group appended to the receiver's
// existing groups. The keys of all subsequent attributes, whether added by With
// or in a Record, should be qualified by the sequence of group names.
func (h *logHandler) WithGroup(name string) slog.Handler {
return &logHandler{handler: h.handler.WithGroup(name), events: h.events}
}
// Handle looks to see if an event function needs to be executed for a given
// log level and then formats its argument Record.
func (h *logHandler) Handle(ctx context.Context, r slog.Record) error {
switch r.Level {
case slog.LevelDebug:
if h.events.Debug != nil {
h.events.Debug(ctx, toRecord(r))
}
case slog.LevelError:
if h.events.Error != nil {
h.events.Error(ctx, toRecord(r))
}
case slog.LevelWarn:
if h.events.Warn != nil {
h.events.Warn(ctx, toRecord(r))
}
case slog.LevelInfo:
if h.events.Info != nil {
h.events.Info(ctx, toRecord(r))
}
}
return h.handler.Handle(ctx, r)
}