Search code examples
godecorator

get decorated function name in golang


I am trying to log decorated function name before and after calling it as below.

Is it possible to get the decorated function name f1 in decorator to make it shows entering f1 and leaving f1.

package main

import (
    "fmt"
)

func f1() {
    fmt.Println("f1")
}

func decorator(f func()) {
    fmt.Println("entering f.name")
    f()
    fmt.Println("leaving f.name")
}

func main() {
    decorator(f1)

}

Solution

  • you can use the reflect and runtime package for that

    package main
    
    import (
    "fmt"
      "reflect"
      "runtime"
    )
    
    func f1() {
      fmt.Println("f1")
    }
    
    func decorator(f func()) {
      name := runtime.FuncForPC(reflect.ValueOf(f).Pointer()).Name()
      fmt.Printf("entering f.name:%s\n",name)
      f()
      fmt.Printf("leaving f.name:%s\n",name)
    }
    
    func main() {
      decorator(f1)
    }
    
    entering f.name:main.f1
    f1
    leaving f.name:main.f1
    ``