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.
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) {
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)
29 func Example_wrapping() {
30 replace := func(groups []string, a slog.Attr) slog.Attr {
32 if a.Key == slog.TimeKey && len(groups) == 0 {
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()))
41 logger := slog.New(slog.HandlerOptions{AddSource: true, ReplaceAttr: replace}.NewTextHandler(os.Stdout))
42 Infof(logger, "message, %s", "formatted")
45 // level=INFO source=example_wrap_test.go:42 msg="message, formatted"