Skip to content

Instantly share code, notes, and snippets.

@wjkoh
Last active April 11, 2024 16:36
Show Gist options
  • Save wjkoh/f0186f0dfa5e63c27e6970b1406e0514 to your computer and use it in GitHub Desktop.
Save wjkoh/f0186f0dfa5e63c27e6970b1406e0514 to your computer and use it in GitHub Desktop.
go/slog: How to wrap slog's functions and report the correct source line number
const (
LevelCritical = slog.Level(12)
)
// Critical is an example of a user-defined logging function that wraps slog.
// The log record contains the source position of the caller of Critical.
func Critical(msg string, args ...any) {
if !slog.Default().Enabled(context.Background(), LevelCritical) {
return
}
var pcs [1]uintptr
runtime.Callers(2, pcs[:]) // skip [Callers, Infof]
r := slog.NewRecord(time.Now(), LevelCritical, msg, pcs[0])
r.Add(args...)
_ = slog.Default().Handler().Handle(context.Background(), r)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment