Source file src/log/slog/example_log_level_test.go

     1  // Copyright 2023 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  	"log"
     9  	"log/slog"
    10  	"log/slog/internal/slogtest"
    11  	"os"
    12  )
    13  
    14  // This example shows how to use slog.SetLogLoggerLevel to change the minimal level
    15  // of the internal default handler for slog package before calling slog.SetDefault.
    16  func ExampleSetLogLoggerLevel_log() {
    17  	defer log.SetFlags(log.Flags()) // revert changes after the example
    18  	log.SetFlags(0)
    19  	defer log.SetOutput(log.Writer()) // revert changes after the example
    20  	log.SetOutput(os.Stdout)
    21  
    22  	// Default logging level is slog.LevelInfo.
    23  	log.Print("log debug") // log debug
    24  	slog.Debug("debug")    // no output
    25  	slog.Info("info")      // INFO info
    26  
    27  	// Set the default logging level to slog.LevelDebug.
    28  	currentLogLevel := slog.SetLogLoggerLevel(slog.LevelDebug)
    29  	defer slog.SetLogLoggerLevel(currentLogLevel) // revert changes after the example
    30  
    31  	log.Print("log debug") // log debug
    32  	slog.Debug("debug")    // DEBUG debug
    33  	slog.Info("info")      // INFO info
    34  
    35  	// Output:
    36  	// log debug
    37  	// INFO info
    38  	// log debug
    39  	// DEBUG debug
    40  	// INFO info
    41  }
    42  
    43  // This example shows how to use slog.SetLogLoggerLevel to change the minimal level
    44  // of the internal writer that uses the custom handler for log package after
    45  // calling slog.SetDefault.
    46  func ExampleSetLogLoggerLevel_slog() {
    47  	// Set the default logging level to slog.LevelError.
    48  	currentLogLevel := slog.SetLogLoggerLevel(slog.LevelError)
    49  	defer slog.SetLogLoggerLevel(currentLogLevel) // revert changes after the example
    50  
    51  	defer slog.SetDefault(slog.Default()) // revert changes after the example
    52  	slog.SetDefault(slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{ReplaceAttr: slogtest.RemoveTime})))
    53  
    54  	log.Print("error") // level=ERROR msg=error
    55  
    56  	// Output:
    57  	// level=ERROR msg=error
    58  }
    59  

View as plain text