2

Is there a way to include the name of the current function I am in? I'd like to include it in my debug logs rather than hard coding the func name which is a pain after a while.

Thanks.

farhany
  • 1,243
  • 2
  • 17
  • 29
  • 1
    key skill of any good productive software developer is to master the art of google fu ... do a search on : golang current function name – Scott Stensland Sep 25 '18 at 23:03

1 Answers1

6

You can do this using 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()
}

Outputs (package.function)

main.foo

Ullaakut
  • 3,554
  • 2
  • 19
  • 34
  • This is perfect. Thank you! – farhany Sep 25 '18 at 23:08
  • Rather than use the result of runtime.Callers, runtime.CallersFrames should be used as shown here: https://stackoverflow.com/a/46289376/5250939 and described in the doc: https://godoc.org/runtime#Callers – Bo Sunesen Jan 07 '19 at 10:16
  • Why are we subtracting 1 from the PC here? I tested with(/out) the -1 but the result is weirdly the same: `caller := runtime.FuncForPC(fpcs[0] - 1) ` – systrigger Oct 28 '19 at 00:23