golang.org/x/exp@v0.0.0-20240506185415-9bf2ced13842/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  	"context"
     9  	"fmt"
    10  	"os"
    11  	"path/filepath"
    12  	"runtime"
    13  	"time"
    14  
    15  	"golang.org/x/exp/slog"
    16  )
    17  
    18  // Infof is an example of a user-defined logging function that wraps slog.
    19  // The log record contains the source position of the caller of Infof.
    20  func Infof(logger *slog.Logger, format string, args ...any) {
    21  	if !logger.Enabled(context.Background(), slog.LevelInfo) {
    22  		return
    23  	}
    24  	var pcs [1]uintptr
    25  	runtime.Callers(2, pcs[:]) // skip [Callers, Infof]
    26  	r := slog.NewRecord(time.Now(), slog.LevelInfo, fmt.Sprintf(format, args...), pcs[0])
    27  	_ = logger.Handler().Handle(context.Background(), r)
    28  }
    29  
    30  func Example_wrapping() {
    31  	replace := func(groups []string, a slog.Attr) slog.Attr {
    32  		// Remove time.
    33  		if a.Key == slog.TimeKey && len(groups) == 0 {
    34  			return slog.Attr{}
    35  		}
    36  		// Remove the directory from the source's filename.
    37  		if a.Key == slog.SourceKey {
    38  			source := a.Value.Any().(*slog.Source)
    39  			source.File = filepath.Base(source.File)
    40  		}
    41  		return a
    42  	}
    43  	logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{AddSource: true, ReplaceAttr: replace}))
    44  	Infof(logger, "message, %s", "formatted")
    45  
    46  	// Output:
    47  	// level=INFO source=example_wrap_test.go:44 msg="message, formatted"
    48  }