Last active
April 11, 2024 16:36
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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