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

View as plain text