-
-
Notifications
You must be signed in to change notification settings - Fork 20
/
pool.go
87 lines (71 loc) · 1.78 KB
/
pool.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package slogmulti
import (
"context"
"math/rand"
"time"
"log/slog"
"github.com/samber/lo"
)
var _ slog.Handler = (*PoolHandler)(nil)
type PoolHandler struct {
randSource rand.Source
handlers []slog.Handler
}
// Pool balances records between multiple slog.Handler in order to increase bandwidth.
// Uses a round robin strategy.
func Pool() func(...slog.Handler) slog.Handler {
return func(handlers ...slog.Handler) slog.Handler {
return &PoolHandler{
randSource: rand.NewSource(time.Now().UnixNano()),
handlers: handlers,
}
}
}
// Implements slog.Handler
func (h *PoolHandler) 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 *PoolHandler) Handle(ctx context.Context, r slog.Record) error {
if len(h.handlers) == 0 {
return nil
}
// round robin
rand := h.randSource.Int63() % int64(len(h.handlers))
handlers := append(h.handlers[rand:], h.handlers[:rand]...)
var err error
for i := range handlers {
if handlers[i].Enabled(ctx, r.Level) {
err = try(func() error {
return handlers[i].Handle(ctx, r.Clone())
})
if err == nil {
return nil
}
}
}
return err
}
// Implements slog.Handler
func (h *PoolHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
handers := lo.Map(h.handlers, func(h slog.Handler, _ int) slog.Handler {
return h.WithAttrs(attrs)
})
return Pool()(handers...)
}
// Implements slog.Handler
func (h *PoolHandler) WithGroup(name string) slog.Handler {
// https://cs.opensource.google/go/x/exp/+/46b07846:slog/handler.go;l=247
if name == "" {
return h
}
handers := lo.Map(h.handlers, func(h slog.Handler, _ int) slog.Handler {
return h.WithGroup(name)
})
return Pool()(handers...)
}