github.com/searKing/golang/go@v1.2.117/log/slog/example_custom_levels_test.go (about)

     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
     6  
     7  import (
     8  	"context"
     9  	"fmt"
    10  	"log/slog"
    11  	"os"
    12  )
    13  
    14  // This example demonstrates using custom log levels and custom log level names.
    15  // In addition to the default log levels, it introduces Trace, Notice, and
    16  // Emergency levels. The ReplaceAttr changes the way levels are printed for both
    17  // the standard log levels and the custom log levels.
    18  func ExampleHandlerOptions_customLevels() {
    19  	getPid = func() int { return 0 } // set pid to zero for test
    20  	defer func() { getPid = os.Getpid }()
    21  
    22  	// Exported constants from a custom logging package.
    23  	const (
    24  		LevelTrace     = slog.Level(-8)
    25  		LevelDebug     = slog.LevelDebug
    26  		LevelInfo      = slog.LevelInfo
    27  		LevelNotice    = slog.Level(2)
    28  		LevelWarning   = slog.LevelWarn
    29  		LevelError     = slog.LevelError
    30  		LevelEmergency = slog.Level(12)
    31  	)
    32  	opt := &slog.HandlerOptions{
    33  		// Set a custom level to show all log output. The default value is
    34  		// LevelInfo, which would drop Debug and Trace logs.
    35  		Level: LevelTrace,
    36  
    37  		ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
    38  			// Remove time from the output for predictable test output.
    39  			if a.Key == slog.TimeKey {
    40  				return slog.Attr{}
    41  			}
    42  
    43  			// Customize the name of the level key and the output string, including
    44  			// custom level values.
    45  			if a.Key == slog.LevelKey {
    46  				// Rename the level key from "level" to "sev".
    47  				a.Key = "sev"
    48  
    49  				// Handle custom level values.
    50  				level := a.Value.Any().(slog.Level)
    51  
    52  				// This could also look up the name from a map or other structure, but
    53  				// this demonstrates using a switch statement to rename levels. For
    54  				// maximum performance, the string values should be constants, but this
    55  				// example uses the raw strings for readability.
    56  				switch {
    57  				case level < LevelDebug:
    58  					a.Value = slog.StringValue("TRACE")
    59  				case level < LevelInfo:
    60  					a.Value = slog.StringValue("DEBUG")
    61  				case level < LevelNotice:
    62  					a.Value = slog.StringValue("INFO")
    63  				case level < LevelWarning:
    64  					a.Value = slog.StringValue("NOTICE")
    65  				case level < LevelError:
    66  					a.Value = slog.StringValue("WARNING")
    67  				case level < LevelEmergency:
    68  					a.Value = slog.StringValue("ERROR")
    69  				default:
    70  					a.Value = slog.StringValue("EMERGENCY")
    71  				}
    72  			}
    73  
    74  			return a
    75  		},
    76  	}
    77  	{
    78  		fmt.Printf("----text----\n")
    79  		th := slog.NewTextHandler(os.Stdout, opt)
    80  
    81  		logger := slog.New(th)
    82  		ctx := context.Background()
    83  		logger.Log(ctx, LevelEmergency, "missing pilots")
    84  		logger.Error("failed to start engines", "err", "missing fuel")
    85  		logger.Warn("falling back to default value")
    86  		logger.Log(ctx, LevelNotice, "all systems are running")
    87  		logger.Info("initiating launch")
    88  		logger.Debug("starting background job")
    89  		logger.Log(ctx, LevelTrace, "button clicked")
    90  	}
    91  	{
    92  		fmt.Printf("----glog----\n")
    93  		th := NewGlogHandler(os.Stdout, opt)
    94  
    95  		logger := slog.New(th)
    96  		ctx := context.Background()
    97  		logger.Log(ctx, LevelEmergency, "missing pilots")
    98  		logger.Error("failed to start engines", "err", "missing fuel")
    99  		logger.Warn("falling back to default value")
   100  		logger.Log(ctx, LevelNotice, "all systems are running")
   101  		logger.Info("initiating launch")
   102  		logger.Debug("starting background job")
   103  		logger.Log(ctx, LevelTrace, "button clicked")
   104  	}
   105  	{
   106  		fmt.Printf("----glog_human----\n")
   107  		th := NewGlogHumanHandler(os.Stdout, opt)
   108  
   109  		logger := slog.New(th)
   110  		ctx := context.Background()
   111  		logger.Log(ctx, LevelEmergency, "missing pilots")
   112  		logger.Error("failed to start engines", "err", "missing fuel")
   113  		logger.Warn("falling back to default value")
   114  		logger.Log(ctx, LevelNotice, "all systems are running")
   115  		logger.Info("initiating launch")
   116  		logger.Debug("starting background job")
   117  		logger.Log(ctx, LevelTrace, "button clicked")
   118  	}
   119  
   120  	// Output:
   121  	// ----text----
   122  	// sev=EMERGENCY msg="missing pilots"
   123  	// sev=ERROR msg="failed to start engines" err="missing fuel"
   124  	// sev=WARNING msg="falling back to default value"
   125  	// sev=NOTICE msg="all systems are running"
   126  	// sev=INFO msg="initiating launch"
   127  	// sev=DEBUG msg="starting background job"
   128  	// sev=TRACE msg="button clicked"
   129  	// ----glog----
   130  	// EMERGENCY 0] missing pilots
   131  	// ERROR 0] failed to start engines, err=missing fuel
   132  	// WARNING 0] falling back to default value
   133  	// NOTICE 0] all systems are running
   134  	// INFO 0] initiating launch
   135  	// DEBUG 0] starting background job
   136  	// TRACE 0] button clicked
   137  	// ----glog_human----
   138  	// [EMERGENCY] [0] missing pilots
   139  	// [ERROR] [0] failed to start engines, err=missing fuel
   140  	// [WARNING] [0] falling back to default value
   141  	// [NOTICE] [0] all systems are running
   142  	// [INFO] [0] initiating launch
   143  	// [DEBUG] [0] starting background job
   144  	// [TRACE] [0] button clicked
   145  }