Golang: Get the function caller’s name

Problem

Consider this code:

package main 

import "fmt"

func foo() {
    // foo() wants to know who called it
    fmt.Println("HI")
}

func main() {
    foo()
}

In the function foo, we want to get the name of the function (and preferably file name and number ) that called it.

Solution

We can get this information by traversing the stack trace (which Go’s “runtime” package has handy functions for:

func foo() {
    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 file name and line number
    fmt.Println(caller.FileLine(fpcs[0]-1))

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

Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *