How to get the current function name

2019-01-12 21:55发布

问题:

For tracing purpose, I'd like to print out current function name, like the __FUNCTION__ macro in gcc.

So that when I have a function

func foo () {
   trace()
}

it will automatically print out Entering foo()... or something like that.

回答1:

Package runtime is your friend here:

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())
}


回答2:

For those looking at this question in 2017 some golang runtime functions have been added that seem to deal with the incorrect line number being printed.

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)
}

Playground: https://play.golang.org/p/z2kHQJoeUo



标签: go