Skip to content

Instantly share code, notes, and snippets.

@polynomialspace
Created November 19, 2022 18:23
Show Gist options
  • Save polynomialspace/cf899d57f046191674148823365e3abd to your computer and use it in GitHub Desktop.
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
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())
}
@polynomialspace
Copy link
Author

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)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment