Repository navigation
Expand file tree
/
Copy pathmulti_handler.go
More file actions
75 lines (63 loc) · 1.68 KB
/
Copy pathmulti_handler.go
File metadata and controls
75 lines (63 loc) · 1.68 KB
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 logger
import (
"context"
"errors"
"log/slog"
"slices"
)
// multiHandler is a custom slog.Handler that writes to multiple handlers
type multiHandler struct {
handlers []slog.Handler
}
// newMultiHandler distributes records to multiple slog.Handler sequentially
func newMultiHandler(handlers ...slog.Handler) slog.Handler {
return &multiHandler{handlers: handlers}
}
// Enabled implements slog.Handler
func (h *multiHandler) Enabled(ctx context.Context, level slog.Level) bool {
for _, handler := range h.handlers {
if handler.Enabled(ctx, level) {
return true
}
}
return false
}
// Handle implements slog.Handler
func (h *multiHandler) Handle(ctx context.Context, r slog.Record) error {
var errs []error
// Distribute the record to all handlers sequentially
for _, handler := range h.handlers {
if handler.Enabled(ctx, r.Level) {
if err := handler.Handle(ctx, r.Clone()); err != nil {
errs = append(errs, err)
}
}
}
// Combine errors into a multiError
if len(errs) > 0 {
return errors.Join(errs...)
}
return nil
}
// WithAttrs implements slog.Handler
func (h *multiHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
if len(attrs) == 0 {
return h
}
newHandlers := make([]slog.Handler, len(h.handlers))
for i, handler := range h.handlers {
newHandlers[i] = handler.WithAttrs(slices.Clone(attrs))
}
return newMultiHandler(newHandlers...)
}
// WithGroup implements slog.Handler
func (h *multiHandler) WithGroup(name string) slog.Handler {
if name == "" {
return h
}
newHandlers := make([]slog.Handler, len(h.handlers))
for i, handler := range h.handlers {
newHandlers[i] = handler.WithGroup(name)
}
return newMultiHandler(newHandlers...)
}