-
-
Notifications
You must be signed in to change notification settings - Fork 20
/
failover.go
75 lines (61 loc) · 1.54 KB
/
failover.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
package slogmulti
import (
"context"
"log/slog"
"github.com/samber/lo"
)
var _ slog.Handler = (*FailoverHandler)(nil)
// @TODO: implement round robin strategy ?
type FailoverHandler struct {
handlers []slog.Handler
}
// Failover forward record to the first available slog.Handler
func Failover() func(...slog.Handler) slog.Handler {
return func(handlers ...slog.Handler) slog.Handler {
return &FailoverHandler{
handlers: handlers,
}
}
}
// Implements slog.Handler
func (h *FailoverHandler) 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 *FailoverHandler) Handle(ctx context.Context, r slog.Record) error {
var err 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 {
return nil
}
}
}
return err
}
// Implements slog.Handler
func (h *FailoverHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
handers := lo.Map(h.handlers, func(h slog.Handler, _ int) slog.Handler {
return h.WithAttrs(attrs)
})
return Failover()(handers...)
}
// Implements slog.Handler
func (h *FailoverHandler) 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 Failover()(handers...)
}