github.com/shogo82148/std@v1.22.1-0.20240327122250-4e474527810c/log/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  	"github.com/shogo82148/std/log/slog"
     9  	"github.com/shogo82148/std/log/slog/internal/slogtest"
    10  	"github.com/shogo82148/std/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  // この例では、ログレベルを上げて、ロガーの出力を減らす方法を示しています。
    21  //
    22  // 別の一般的な使用方法は、(例えばLevelDebugに)ログレベルを下げて、
    23  // バグが含まれていると疑われるプログラムの一部分でログを出力することです。
    24  func ExampleHandler_levelHandler() {
    25  	th := slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{ReplaceAttr: slogtest.RemoveTime})
    26  	logger := slog.New(NewLevelHandler(slog.LevelWarn, th))
    27  	logger.Info("not printed")
    28  	logger.Warn("printed")
    29  
    30  	// Output:
    31  	// level=WARN msg=printed
    32  }