Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the current function name

Tags:

go

For tracing purpose, I'd like to print out current function name, like the __FUNCTION__ macro in gcc.

So that when I have a function

func foo () {    trace() } 

it will automatically print out Entering foo()... or something like that.

like image 928
lang2 Avatar asked Sep 19 '14 06:09

lang2


1 Answers

[Note: Go 1.7+ recommends using runtime.CallersFrames instead of runtime.FuncForPC; another answer has an updated example].

Package runtime is your friend here:

func trace() {     pc := make([]uintptr, 10)  // at least 1 entry needed     runtime.Callers(2, pc)     f := runtime.FuncForPC(pc[0])     file, line := f.FileLine(pc[0])     fmt.Printf("%s:%d %s\n", file, line, f.Name()) } 
like image 61
Volker Avatar answered Sep 29 '22 02:09

Volker