This is a tested production ready utility function for returning function name.
Note 1: We are handling the possibility of a nil pointer from FuncForPC
Note 2: optFuncLevel is just a friendly name for stack frame level. This gives us the flexibility of using this within another layer of utility functions.
A direct call from say main
would just pass 1 (or nothing since default), but if I am calling FunctionName
in a log enriching function, say PrettyLog()
that is called from regular code, I would call it as FunctionName(2)
in the call from PrettyLog, so the function name returned is the name of the caller of PrettyLog, not PrettyLog itself.
// FunctionName returns the function name of the caller
// optFuncLevel passes the function level to go back up.
// The default is 1, referring to the caller of this function
func FunctionName(optFuncLevel ...int) (funcName string) {
frameLevel := 1 // default to the caller's frame
if len(optFuncLevel) > 0 {
frameLevel = optFuncLevel[0]
}
if pc, _, _, ok := runtime.Caller(frameLevel); ok {
fPtr := runtime.FuncForPC(pc)
if fPtr == nil {
return
}
// Shorten full function name a bit
farr := strings.SplitN(fPtr.Name(), "/", 2)
if len(farr) < 2 {
return
}
return farr[1]
}
return
}
function
. What would you expect as a name ? – Forlorn