Created
November 19, 2022 18:23
-
-
Save polynomialspace/cf899d57f046191674148823365e3abd to your computer and use it in GitHub Desktop.
An example of mild log tracing capabilities with x/exp/slog; https://go.dev/play/p/U-R1tFhuI13
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
package main | |
import ( | |
"fmt" | |
"os" | |
"runtime" | |
log "golang.org/x/exp/slog" | |
) | |
func trace() string { | |
pc, file, line, _ := runtime.Caller(1) | |
return fmt.Sprintf("%s:%d:%s", file, line, runtime.FuncForPC(pc).Name()) | |
} | |
func funcName() string { | |
pc, file, _, _ := runtime.Caller(1) | |
return fmt.Sprintf("%s:%s", file, runtime.FuncForPC(pc).Name()) | |
} | |
func foo(l *log.Logger) { | |
l = l.With("func", funcName()) | |
l.Info("lol") | |
} | |
func main() { | |
l := log.New(log.NewJSONHandler(os.Stdout)) | |
foo(l) | |
l.Info("lmao", "line", trace()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You could also potentially do the
defer f()()
pattern seen here but I'm half awake and not sure how to impl this cleanly (ie. ideally this would all be wrapped up in a single line and still give you the With() context in other logs in the func)