Debian Codegraph @

src/log/slog/example_level_handler_test.go

raw
1 // Copyright 2022 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package slog_test
6
7 import (
8 "context"
9 "log/slog"
10 "os"
11 )
12
13 // A LevelHandler wraps a Handler with an Enabled method
14 // that returns false for levels below a minimum.
15 type LevelHandler struct {
16 level slog.Leveler
17 handler slog.Handler
18 }
19
20 // NewLevelHandler returns a LevelHandler with the given level.
21 // All methods except Enabled delegate to h.
22 func NewLevelHandler(level slog.Leveler, h slog.Handler) *LevelHandler {
23 // Optimization: avoid chains of LevelHandlers.
24 if lh, ok := h.(*LevelHandler); ok {
25 h = lh.Handler()
26 }
27 return &LevelHandler{level, h}
28 }
29
30 // Enabled implements Handler.Enabled by reporting whether
31 // level is at least as large as h's level.
32 func (h *LevelHandler) Enabled(_ context.Context, level slog.Level) bool {
33 return level >= h.level.Level()
34 }
35
36 // Handle implements Handler.Handle.
37 func (h *LevelHandler) Handle(ctx context.Context, r slog.Record) error {
38 return h.handler.Handle(ctx, r)
39 }
40
41 // WithAttrs implements Handler.WithAttrs.
42 func (h *LevelHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
43 return NewLevelHandler(h.level, h.handler.WithAttrs(attrs))
44 }
45
46 // WithGroup implements Handler.WithGroup.
47 func (h *LevelHandler) WithGroup(name string) slog.Handler {
48 return NewLevelHandler(h.level, h.handler.WithGroup(name))
49 }
50
51 // Handler returns the Handler wrapped by h.
52 func (h *LevelHandler) Handler() slog.Handler {
53 return h.handler
54 }
55
56 // This example shows how to Use a LevelHandler to change the level of an
57 // existing Handler while preserving its other behavior.
58 //
59 // This example demonstrates increasing the log level to reduce a logger's
60 // output.
61 //
62 // Another typical use would be to decrease the log level (to LevelDebug, say)
63 // during a part of the program that was suspected of containing a bug.
64 func ExampleHandler_levelHandler() {
65 removeTime := func(groups []string, a slog.Attr) slog.Attr {
66 if a.Key == slog.TimeKey && len(groups) == 0 {
67 return slog.Attr{}
68 }
69 return a
70 }
71 th := slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{ReplaceAttr: removeTime})
72 logger := slog.New(NewLevelHandler(slog.LevelWarn, th))
73 logger.Info("not printed")
74 logger.Warn("printed")
75
76 // Output:
77 // level=WARN msg=printed
78 }