-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlog.go
60 lines (48 loc) · 1.29 KB
/
log.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
package rx
import (
"context"
"os"
"sync/atomic"
"log/slog"
)
var LogLevel slog.LevelVar
type genLogHandler struct {
handler slog.Handler
level *slog.LevelVar
norec *atomic.Bool
buf []slog.Record
}
func newLogHandler() *genLogHandler {
return &genLogHandler{
handler: slog.NewTextHandler(os.Stderr, nil),
level: &LogLevel,
norec: new(atomic.Bool),
}
}
func (h genLogHandler) Enabled(_ context.Context, level slog.Level) bool {
return !h.norec.Load() || level >= h.level.Level()
}
// TODO(rdo) sharing buffer is nice, but instead should make sure attrs are set in shared elements too
func (h *genLogHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
return &genLogHandler{level: h.level, norec: h.norec, buf: h.buf,
handler: h.handler.WithAttrs(attrs),
}
}
func (h *genLogHandler) WithGroup(name string) slog.Handler {
return &genLogHandler{level: h.level, norec: h.norec, buf: h.buf,
handler: h.handler.WithGroup(name),
}
}
func (h *genLogHandler) Handle(ctx context.Context, r slog.Record) error {
if r.Level >= h.level.Level() {
return h.handler.Handle(ctx, r)
}
h.buf = append(h.buf, r)
return nil
}
func (h *genLogHandler) Discard() { h.buf = h.buf[:0] }
func (h *genLogHandler) Dump() {
for _, r := range h.buf {
h.handler.Handle(context.Background(), r)
}
}