is there any function in go that is similar like "_file_"
or "_line_"
in go, to know who is calling a specific function during run time? In C we have the "_file_"
line that can be called as macros. How to do this in go?
If you're using the log
package, you can instruct the logger to prefix the entries with various information. You'll likely be most interested in the Lshortfile
constant, which will result in prefixes along the lines of d.go:23
. Alternatively, there is Llongfile
which prints the file's full path (such as /a/b/c/d.go:23
).
If you don't want to use the log
package, you could also use runtime.Caller()
, which is what the log package uses internally. It's not as straight forward as the C macros, but you could hide it behind a function (and specify the correct call depth). You can see how the log package is implemented for an example (line 140).
(1) Write a brief function that calls runtime.Caller()
(2) Call that function everywhere you want to access the source code file and line number at run time.
Example:
import "runtime"
func file_line() string {
_, fileName, fileLine, ok := runtime.Caller(1)
var s string
if ok {
s = fmt.Sprintf("%s:%d", fileName, fileLine)
} else {
s = ""
}
return s
}
Note: pass 1 to Caller() so that it returns the number of the line where file_line() is called, instead of where runtime.Caller() is called.
fmt.Println(file_line()) // Prints this file and line number.
See the runtime
and runtime.debug
packages and in particular the Stack
, PrintStack
or Caller
functions.
Stack formats a stack trace of the calling goroutine into buf and returns the number of bytes written to buf. If all is true, Stack formats stack traces of all other goroutines into buf after the trace for the current goroutine.
If you are compiling with debug information, then this will should contain the line number in source
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With