]> Cypherpunks.ru repositories - gostls13.git/blob - src/log/slog/example_wrap_test.go
b96de11320c67f35350e1928f41f16dc2dfb5b72
[gostls13.git] / 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                         a.Value = slog.StringValue(filepath.Base(a.Value.String()))
38                 }
39                 return a
40         }
41         logger := slog.New(slog.HandlerOptions{AddSource: true, ReplaceAttr: replace}.NewTextHandler(os.Stdout))
42         Infof(logger, "message, %s", "formatted")
43
44         // Output:
45         // level=INFO source=example_wrap_test.go:42 msg="message, formatted"
46 }