Source file
src/log/slog/example_wrap_test.go
1
2
3
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
18
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[:])
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
32 if a.Key == slog.TimeKey && len(groups) == 0 {
33 return slog.Attr{}
34 }
35
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
46
47 }
48
View as plain text