-
Notifications
You must be signed in to change notification settings - Fork 2
/
export_handler.go
65 lines (53 loc) · 1.2 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
package logging
import (
"context"
"log/slog"
)
type ExportFunc func(ctx context.Context, record slog.Record)
func NewExportHandler(ctx context.Context, next slog.Handler, cfg ExportConfig) slog.Handler {
handler := &ExportHandler{
next: next,
cfg: cfg,
ch: make(chan slog.Record, 1000),
}
go handler.run(ctx)
return handler
}
type ExportHandler struct {
next slog.Handler
cfg ExportConfig
ch chan slog.Record
}
func (e *ExportHandler) Enabled(ctx context.Context, level slog.Level) bool {
return e.next.Enabled(ctx, level)
}
func (e *ExportHandler) Handle(ctx context.Context, record slog.Record) error {
if record.Level >= e.cfg.MinLevel {
e.cfg.ExportFunc(ctx, record)
}
return e.next.Handle(ctx, record)
}
func (e *ExportHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
return &ExportHandler{
next: e.next.WithAttrs(attrs),
cfg: e.cfg,
ch: e.ch,
}
}
func (e *ExportHandler) WithGroup(name string) slog.Handler {
return &ExportHandler{
next: e.next.WithGroup(name),
cfg: e.cfg,
ch: e.ch,
}
}
func (e *ExportHandler) run(ctx context.Context) {
for {
select {
case <-ctx.Done():
return
case record := <-e.ch:
e.cfg.ExportFunc(ctx, record)
}
}
}