Source file src/log/slog/example_wrap_test.go

     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  	"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  	replace := func(groups []string, a slog.Attr) slog.Attr {
    31  		// Remove time.
    32  		if a.Key == slog.TimeKey && len(groups) == 0 {
    33  			return slog.Attr{}
    34  		}
    35  		// Remove the directory from the source's filename.
    36  		if a.Key == slog.SourceKey {
    37  			source := a.Value.Any().(*slog.Source)
    38  			source.File = filepath.Base(source.File)
    39  		}
    40  		return a
    41  	}
    42  	logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{AddSource: true, ReplaceAttr: replace}))
    43  	Infof(logger, "message, %s", "formatted")
    44  
    45  	// Output:
    46  	// level=INFO source=example_wrap_test.go:43 msg="message, formatted"
    47  }
    48  

View as plain text