Categories
Go

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

By Moazzam

Moazzam is a software developer working in the big apple. He has over a decade of experience in development. While most of his work involves developing web applications, he does development for Android and Windows Mobile in his spare time.

Leave a Reply

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