Source file
src/log/slog/example_level_handler_test.go
1
2
3
4
5 package slog_test
6
7 import (
8 "context"
9 "log/slog"
10 "log/slog/internal/slogtest"
11 "os"
12 )
13
14
15
16 type LevelHandler struct {
17 level slog.Leveler
18 handler slog.Handler
19 }
20
21
22
23 func NewLevelHandler(level slog.Leveler, h slog.Handler) *LevelHandler {
24
25 if lh, ok := h.(*LevelHandler); ok {
26 h = lh.Handler()
27 }
28 return &LevelHandler{level, h}
29 }
30
31
32
33 func (h *LevelHandler) Enabled(_ context.Context, level slog.Level) bool {
34 return level >= h.level.Level()
35 }
36
37
38 func (h *LevelHandler) Handle(ctx context.Context, r slog.Record) error {
39 return h.handler.Handle(ctx, r)
40 }
41
42
43 func (h *LevelHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
44 return NewLevelHandler(h.level, h.handler.WithAttrs(attrs))
45 }
46
47
48 func (h *LevelHandler) WithGroup(name string) slog.Handler {
49 return NewLevelHandler(h.level, h.handler.WithGroup(name))
50 }
51
52
53 func (h *LevelHandler) Handler() slog.Handler {
54 return h.handler
55 }
56
57
58
59
60
61
62
63
64
65 func ExampleHandler_levelHandler() {
66 th := slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{ReplaceAttr: slogtest.RemoveTime})
67 logger := slog.New(NewLevelHandler(slog.LevelWarn, th))
68 logger.Info("not printed")
69 logger.Warn("printed")
70
71
72
73 }
74
View as plain text