1

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)

}
CSJ
  • 2,709
  • 4
  • 24
  • 30
  • See [this answer](https://stackoverflow.com/a/54451891/13631587) for an easy way hook enter and exit from within the function. The answer logs on exit. Add a print statement to the beginning to the `timer` function to log on enter. – Charlie Tumahai Jun 07 '21 at 03:43
  • 4
    Note that not all functions have names. – Burak Serdar Jun 07 '21 at 03:48
  • Not in a nice, supported, compatible way that actually works and works they way you seem to thing it should work . – Volker Jun 07 '21 at 04:36
  • please look at `runtime` package, maybe there is something that can help you there. – mri1939 Jun 07 '21 at 08:20
  • @mri1939 yes, I am trying `runtime.Callers` , `runtime.FuncForPC` and `runtime.CallersFrames` and will update if I got some clue – CSJ Jun 07 '21 at 09:11

1 Answers1

3

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
``
CSJ
  • 2,709
  • 4
  • 24
  • 30
lumos0815
  • 3,908
  • 2
  • 25
  • 25