David Aiken
David Aiken

Reputation: 194

how do you log function call return values in golang

I want to know the return values at time of exit from a golang function. The golang defer mechanism is helpful, but it evaluates arguments at the time the defer statement is registered rather than when it is executed. I can work with this using an anonymous function which accesses the return values:

func try() (int i) {
  defer func() {fmt.Printf("%d", i)}()
  i = 10
  return i+1
}

func main() {
  try()
}

This would work ok, i think, but I would like to handle this in a generic manner, perhaps something like:

func try(in string) (out int) {
  enter("%s", in);exit("%d", out)
}

or, even better, use reflection to output the arguments/return values at time of entry/exit. I'm assuming runtime performance isn't critical :).

Is there a good way to do this? Shaba Abhiram's handy Tracey lib does go a long way towards this but stops short of printing the return values.

Upvotes: 2

Views: 2246

Answers (2)

captncraig
captncraig

Reputation: 23078

You are correct in assesing that the arguments to a deferred function are evaluated at the point the defer is queued, not when it is executed.

Your method of making an anonymous function that refers to named returns is valid. Another approach is to pass in the address of the return values:

func try() (i int) {
    defer printReturns(time.Now(), &i)
    time.Sleep(10 * time.Millisecond)
    i = 10
    return i + 1
}

func printReturns(start time.Time, rets ...interface{}) {
    fmt.Println(time.Now().Sub(start))
    for _,ret := range rets{
        fmt.Println(ret)
    }
}

The problem with this approach is that your logging function now has a pointer instead of the real type and must unwrap the pointers to do anything with them. But if you are using reflect, that is not horribly difficult.

Upvotes: 3

OneOfOne
OneOfOne

Reputation: 99234

The closest thing you will get to do it without adding a lot of printf's is using godebug, which pretty much adds the printfs for you.

Upvotes: 2

Related Questions