-
-
Notifications
You must be signed in to change notification settings - Fork 20
/
multi.go
73 lines (61 loc) · 1.56 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
67
68
69
70
71
72
73
package slogmulti
import (
"context"
"errors"
"log/slog"
"slices"
"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 errs []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 {
errs = append(errs, err)
}
}
}
// If errs is empty, or contains only nil errors, this returns nil
return errors.Join(errs...)
}
// Implements slog.Handler
func (h *FanoutHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
handlers := lo.Map(h.handlers, func(h slog.Handler, _ int) slog.Handler {
return h.WithAttrs(slices.Clone(attrs))
})
return Fanout(handlers...)
}
// Implements slog.Handler
func (h *FanoutHandler) WithGroup(name string) slog.Handler {
// https://cs.opensource.google/go/x/exp/+/46b07846:slog/handler.go;l=247
if name == "" {
return h
}
handlers := lo.Map(h.handlers, func(h slog.Handler, _ int) slog.Handler {
return h.WithGroup(name)
})
return Fanout(handlers...)
}