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