如何获取当前的函数名称

lan*_*ng2 36 go

为了跟踪目的,我想打印出当前的函数名,就像__FUNCTION__gcc中的宏一样.

所以,当我有一个功能

func foo () {
   trace()
}
Run Code Online (Sandbox Code Playgroud)

它会自动打印出来Entering foo()...或类似的东西.

Vol*_*ker 55

运行时是你的朋友:

func trace() {
    pc := make([]uintptr, 10)  // at least 1 entry needed
    runtime.Callers(2, pc)
    f := runtime.FuncForPC(pc[0])
    file, line := f.FileLine(pc[0])
    fmt.Printf("%s:%d %s\n", file, line, f.Name())
}
Run Code Online (Sandbox Code Playgroud)


ksr*_*srb 28

对于那些在2017年查看这个问题的人,我们添加了一些golang运行时函数,这些函数似乎可以处理打印的错误行号.

func trace2() {
    pc := make([]uintptr, 15)
    n := runtime.Callers(2, pc)
    frames := runtime.CallersFrames(pc[:n])
    frame, _ := frames.Next()
    fmt.Printf("%s:%d %s\n", frame.File, frame.Line, frame.Function)
}
Run Code Online (Sandbox Code Playgroud)

游乐场:https://play.golang.org/p/z2kHQJoeUo


Ben*_*tly 8

这是一个不需要分配数组的更简单的版本。

func trace() (string, int, string) {
    pc, file, line, ok := runtime.Caller(1)
    if !ok { return "?", 0, "?" }

    fn := runtime.FuncForPC(pc)
    if fn == nil { return file, line, "?" }

    return file, line, fn.Name()
}
Run Code Online (Sandbox Code Playgroud)

  • 不确定这是否涵盖内联函数,参见。/sf/ask/2464908981/#comment105339231_38551362 (2认同)