| | |
| | |
| | |
| |
|
| | package slog_test |
| |
|
| | import ( |
| | "context" |
| | "fmt" |
| | "log/slog" |
| | "os" |
| | "path/filepath" |
| | "runtime" |
| | "time" |
| | ) |
| |
|
| | |
| | |
| | func Infof(logger *slog.Logger, format string, args ...any) { |
| | if !logger.Enabled(context.Background(), slog.LevelInfo) { |
| | return |
| | } |
| | var pcs [1]uintptr |
| | runtime.Callers(2, pcs[:]) |
| | r := slog.NewRecord(time.Now(), slog.LevelInfo, fmt.Sprintf(format, args...), pcs[0]) |
| | _ = logger.Handler().Handle(context.Background(), r) |
| | } |
| |
|
| | func Example_wrapping() { |
| | replace := func(groups []string, a slog.Attr) slog.Attr { |
| | |
| | if a.Key == slog.TimeKey && len(groups) == 0 { |
| | return slog.Attr{} |
| | } |
| | |
| | if a.Key == slog.SourceKey { |
| | source := a.Value.Any().(*slog.Source) |
| | source.File = filepath.Base(source.File) |
| | } |
| | return a |
| | } |
| | logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{AddSource: true, ReplaceAttr: replace})) |
| | Infof(logger, "message, %s", "formatted") |
| |
|
| | |
| | |
| | } |
| |
|