Created
April 28, 2024 21:08
-
-
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).
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 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