golang.org/x/exp@v0.0.0-20240506185415-9bf2ced13842/slog/example_level_handler_test.go (about) 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 "os" 10 11 "golang.org/x/exp/slog" 12 "golang.org/x/exp/slog/internal/testutil" 13 ) 14 15 // A LevelHandler wraps a Handler with an Enabled method 16 // that returns false for levels below a minimum. 17 type LevelHandler struct { 18 level slog.Leveler 19 handler slog.Handler 20 } 21 22 // NewLevelHandler returns a LevelHandler with the given level. 23 // All methods except Enabled delegate to h. 24 func NewLevelHandler(level slog.Leveler, h slog.Handler) *LevelHandler { 25 // Optimization: avoid chains of LevelHandlers. 26 if lh, ok := h.(*LevelHandler); ok { 27 h = lh.Handler() 28 } 29 return &LevelHandler{level, h} 30 } 31 32 // Enabled implements Handler.Enabled by reporting whether 33 // level is at least as large as h's level. 34 func (h *LevelHandler) Enabled(_ context.Context, level slog.Level) bool { 35 return level >= h.level.Level() 36 } 37 38 // Handle implements Handler.Handle. 39 func (h *LevelHandler) Handle(ctx context.Context, r slog.Record) error { 40 return h.handler.Handle(ctx, r) 41 } 42 43 // WithAttrs implements Handler.WithAttrs. 44 func (h *LevelHandler) WithAttrs(attrs []slog.Attr) slog.Handler { 45 return NewLevelHandler(h.level, h.handler.WithAttrs(attrs)) 46 } 47 48 // WithGroup implements Handler.WithGroup. 49 func (h *LevelHandler) WithGroup(name string) slog.Handler { 50 return NewLevelHandler(h.level, h.handler.WithGroup(name)) 51 } 52 53 // Handler returns the Handler wrapped by h. 54 func (h *LevelHandler) Handler() slog.Handler { 55 return h.handler 56 } 57 58 // This example shows how to Use a LevelHandler to change the level of an 59 // existing Handler while preserving its other behavior. 60 // 61 // This example demonstrates increasing the log level to reduce a logger's 62 // output. 63 // 64 // Another typical use would be to decrease the log level (to LevelDebug, say) 65 // during a part of the program that was suspected of containing a bug. 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 // Output: 73 // level=WARN msg=printed 74 }