Skip to content

Instantly share code, notes, and snippets.

@omerkaya1
Created April 28, 2024 21:08
Show Gist options
  • Save omerkaya1/e7db05bda70b29bfdb7b206903433ca4 to your computer and use it in GitHub Desktop.
Save omerkaya1/e7db05bda70b29bfdb7b206903433ca4 to your computer and use it in GitHub Desktop.
A function to retrieve caller information (function name, file containing it and a code line number wher it was called).
package caller
// Info generates caller metadata:
// - func name (trimmed of leading path parts) - e.g. somepkg.(*SomeStruct).SomeMethod
// - file name - e.g. /go/src/github.com/someone/someproject/file.go
// - line - e.g. 23
func Info(depth, skip int) (string, string, int) {
var (
pcs [depth]uintptr
fn, file string
line int
n = runtime.Callers(skip, pcs[:])
f, ok = runtime.CallersFrames(pcs[:n]).Next()
)
if ok {
fn, file, line = f.Function, f.File, f.Line
if i := strings.LastIndexByte(fn, '/'); i != -1 {
fn = fn[i+1:]
}
}
return fn, file, line
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment