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