github.com/searKing/golang/go@v1.2.117/log/slog/example_logvaluer_group_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  	"fmt"
     9  	"log/slog"
    10  	"os"
    11  
    12  	"github.com/searKing/golang/go/log/slog/internal/slogtest"
    13  )
    14  
    15  type Name struct {
    16  	First, Last string
    17  }
    18  
    19  // LogValue implements slog.LogValuer.
    20  // It returns a group containing the fields of
    21  // the Name, so that they appear together in the log output.
    22  func (n Name) LogValue() slog.Value {
    23  	return slog.GroupValue(
    24  		slog.String("first", n.First),
    25  		slog.String("last", n.Last))
    26  }
    27  
    28  func ExampleLogValuer_group() {
    29  	getPid = func() int { return 0 } // set pid to zero for test
    30  	defer func() { getPid = os.Getpid }()
    31  	n := Name{"Perry", "Platypus"}
    32  
    33  	{
    34  		fmt.Printf("----text----\n")
    35  		logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{ReplaceAttr: slogtest.RemoveTime}))
    36  		logger.Info("mission accomplished", "agent", n)
    37  	}
    38  	{
    39  		fmt.Printf("----glog----\n")
    40  		logger := slog.New(NewGlogHandler(os.Stdout, &slog.HandlerOptions{ReplaceAttr: slogtest.RemoveTime}))
    41  		logger.Info("mission accomplished", "agent", n)
    42  	}
    43  	{
    44  		fmt.Printf("----glog_human----\n")
    45  		logger := slog.New(NewGlogHumanHandler(os.Stdout, &slog.HandlerOptions{ReplaceAttr: slogtest.RemoveTime}))
    46  		logger.Info("mission accomplished", "agent", n)
    47  	}
    48  
    49  	// Output:
    50  	// ----text----
    51  	// level=INFO msg="mission accomplished" agent.first=Perry agent.last=Platypus
    52  	// ----glog----
    53  	// I 0] mission accomplished, agent.first=Perry, agent.last=Platypus
    54  	// ----glog_human----
    55  	// [INFO ] [0] mission accomplished, agent.first=Perry, agent.last=Platypus
    56  }