github.com/shogo82148/std@v1.22.1-0.20240327122250-4e474527810c/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_test
     6  
     7  import (
     8  	"github.com/shogo82148/std/log/slog"
     9  	"github.com/shogo82148/std/os"
    10  	"github.com/shogo82148/std/path/filepath"
    11  )
    12  
    13  func Example_wrapping() {
    14  	replace := func(groups []string, a slog.Attr) slog.Attr {
    15  		// Remove time.
    16  		if a.Key == slog.TimeKey && len(groups) == 0 {
    17  			return slog.Attr{}
    18  		}
    19  		// Remove the directory from the source's filename.
    20  		if a.Key == slog.SourceKey {
    21  			source := a.Value.Any().(*slog.Source)
    22  			source.File = filepath.Base(source.File)
    23  		}
    24  		return a
    25  	}
    26  	logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{AddSource: true, ReplaceAttr: replace}))
    27  	Infof(logger, "message, %s", "formatted")
    28  
    29  	// Output:
    30  	// level=INFO source=example_wrap_test.go:43 msg="message, formatted"
    31  }