Get function name

Dean’s suggestion is great if you’re looking for a call stack in a format that’s good for anyone familiar with Go stack traces. If you’re looking just for the calling function’s name, you can do something like this:

package main

import (
        "fmt"
        "runtime"
)

func main() {
        fmt.Println("from main:", CallerName(0))
        func2()
}

func func2() {
        fmt.Println("from func2:", CallerName(0))
        fmt.Println(CallerName(0), "called by", CallerName(1))
}

func CallerName(skip int) string {
        pc, _, _, ok := runtime.Caller(skip + 1)
        if !ok {
                return ""
        }
        f := runtime.FuncForPC(pc)
        if f == nil {
                return ""
        }
        return f.Name()
}

Note that this will contain the “fully-qualified” function name. Functions in the main package are just main.<func name>, but non-main packages will have something like the full package name (e.g. (*github.com/account/project/package.Type).Func)

2 Likes