-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexport_handler.go
84 lines (72 loc) · 1.56 KB
/
export_handler.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
package logging
import (
"context"
"log/slog"
)
type ExportHandlerConfig struct {
MinLevel slog.Level // Only export logs for this min log level.
BufferSize int // Logs channel size.
}
func NewExportHandler(cfg ExportHandlerConfig) *ExportHandler {
if cfg.BufferSize == 0 {
cfg.BufferSize = 1000
}
handler := &ExportHandler{
cfg: cfg,
ch: make(chan slog.Record, cfg.BufferSize),
}
return handler
}
// ExportHandler exports logs to separate channel available via Records()
type ExportHandler struct {
next slog.Handler
cfg ExportHandlerConfig
ch chan slog.Record
}
func (h *ExportHandler) Register(next slog.Handler) slog.Handler {
h.next = next
return h
}
func (h *ExportHandler) Records() <-chan slog.Record {
return h.ch
}
func (h *ExportHandler) Enabled(ctx context.Context, level slog.Level) bool {
if h.next == nil {
return true
}
return h.next.Enabled(ctx, level)
}
func (h *ExportHandler) Handle(ctx context.Context, record slog.Record) error {
if record.Level >= h.cfg.MinLevel {
select {
case <-ctx.Done():
return ctx.Err()
case h.ch <- record:
default:
}
}
if h.next == nil {
return nil
}
return h.next.Handle(ctx, record)
}
func (h *ExportHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
clone := &ExportHandler{
cfg: h.cfg,
ch: h.ch,
}
if h.next != nil {
clone.next = h.next.WithAttrs(attrs)
}
return clone
}
func (h *ExportHandler) WithGroup(name string) slog.Handler {
clone := &ExportHandler{
cfg: h.cfg,
ch: h.ch,
}
if h.next != nil {
clone.next = h.next.WithGroup(name)
}
return clone
}