-
-
Notifications
You must be signed in to change notification settings - Fork 13
/
multi.go
66 lines (55 loc) 路 1.39 KB
/
multi.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
package slogmulti
import (
"context"
"log/slog"
"github.com/hashicorp/go-multierror"
"github.com/samber/lo"
)
var _ slog.Handler = (*FanoutHandler)(nil)
type FanoutHandler struct {
handlers []slog.Handler
}
// Fanout distributes records to multiple slog.Handler in parallel
func Fanout(handlers ...slog.Handler) slog.Handler {
return &FanoutHandler{
handlers: handlers,
}
}
// Implements slog.Handler
func (h *FanoutHandler) Enabled(ctx context.Context, l slog.Level) bool {
for i := range h.handlers {
if h.handlers[i].Enabled(ctx, l) {
return true
}
}
return false
}
// Implements slog.Handler
func (h *FanoutHandler) Handle(ctx context.Context, r slog.Record) error {
var result error
for i := range h.handlers {
if h.handlers[i].Enabled(ctx, r.Level) {
err := try(func() error {
return h.handlers[i].Handle(ctx, r.Clone())
})
if err != nil {
result = multierror.Append(result, err)
}
}
}
return result
}
// Implements slog.Handler
func (h *FanoutHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
handers := lo.Map(h.handlers, func(h slog.Handler, _ int) slog.Handler {
return h.WithAttrs(attrs)
})
return Fanout(handers...)
}
// Implements slog.Handler
func (h *FanoutHandler) WithGroup(name string) slog.Handler {
handers := lo.Map(h.handlers, func(h slog.Handler, _ int) slog.Handler {
return h.WithGroup(name)
})
return Fanout(handers...)
}