当前函数名称

far*_*any 2 go

有没有办法包含我所在的当前函数的名称?我想将它包含在我的调试日志中,而不是硬编码 func 名称,这在一段时间后会很痛苦。

谢谢。

Ull*_*kut 6

您可以使用 runtime.Callers

package main

import (
    "fmt"
    "runtime"
)

func printFuncName() {
    fpcs := make([]uintptr, 1)

    // Skip 2 levels to get the caller
    n := runtime.Callers(2, fpcs)
    if n == 0 {
        fmt.Println("MSG: NO CALLER")
    }

    caller := runtime.FuncForPC(fpcs[0] - 1)
    if caller == nil {
        fmt.Println("MSG CALLER WAS NIL")
    }

    // Print the name of the function
    fmt.Println(caller.Name())
}

func foo() {
    printFuncName()
}

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

输出(包.函数)

main.foo