github.com/searKing/golang/go@v1.2.117/log/slog/example_wrap_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
     6  
     7  import (
     8  	"context"
     9  	"fmt"
    10  	"log/slog"
    11  	"os"
    12  	"path/filepath"
    13  	"runtime"
    14  	"time"
    15  )
    16  
    17  // Infof is an example of a user-defined logging function that wraps slog.
    18  // The log record contains the source position of the caller of Infof.
    19  func Infof(logger *slog.Logger, format string, args ...any) {
    20  	if !logger.Enabled(context.Background(), slog.LevelInfo) {
    21  		return
    22  	}
    23  	var pcs [1]uintptr
    24  	runtime.Callers(2, pcs[:]) // skip [Callers, Infof]
    25  	r := slog.NewRecord(time.Now(), slog.LevelInfo, fmt.Sprintf(format, args...), pcs[0])
    26  	_ = logger.Handler().Handle(context.Background(), r)
    27  }
    28  
    29  func Example_wrapping() {
    30  	getPid = func() int { return 0 } // set pid to zero for test
    31  	defer func() { getPid = os.Getpid }()
    32  	replace := func(groups []string, a slog.Attr) slog.Attr {
    33  		// Remove time.
    34  		if a.Key == slog.TimeKey && len(groups) == 0 {
    35  			return slog.Attr{}
    36  		}
    37  		// Remove the directory from the source's filename.
    38  		if a.Key == slog.SourceKey {
    39  			source := a.Value.Any().(*slog.Source)
    40  			source.File = filepath.Base(source.File)
    41  		}
    42  		return a
    43  	}
    44  	{
    45  		fmt.Printf("----text----\n")
    46  		logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{AddSource: true, ReplaceAttr: replace}))
    47  		Infof(logger, "message, %s", "formatted")
    48  	}
    49  	{
    50  		fmt.Printf("----glog----\n")
    51  		logger := slog.New(NewGlogHandler(os.Stdout, &slog.HandlerOptions{AddSource: true, ReplaceAttr: replace}))
    52  		Infof(logger, "message, %s", "formatted")
    53  	}
    54  	{
    55  		fmt.Printf("----glog_human----\n")
    56  		logger := slog.New(NewGlogHumanHandler(os.Stdout, &slog.HandlerOptions{AddSource: true, ReplaceAttr: replace}))
    57  		Infof(logger, "message, %s", "formatted")
    58  	}
    59  
    60  	// Output:
    61  	// ----text----
    62  	// level=INFO source=example_wrap_test.go:47 msg="message, formatted"
    63  	// ----glog----
    64  	// I 0 example_wrap_test.go:52] message, formatted
    65  	// ----glog_human----
    66  	// [INFO ] [0] [example_wrap_test.go:57](Example_wrapping) message, formatted
    67  
    68  }