_file_ or _line_ similar in golang

Is there any function in go that looks like "_file_" or "_line_" in go to find out who calls a particular function at runtime? In C, we have the string "_file_" , which can be called macros. How to do it in go?

+8
c go
source share
3 answers

If you use the log package, you can tell the registrar the prefix of entries with various information . Most likely, you are most interested in the Lshortfile constant, which will lead to prefixes along the d.go:23 lines. In addition, there is an Llongfile that prints the full path of the file (for example, /a/b/c/d.go:23 ).

If you do not want to use the log package, you can also use runtime.Caller() , which is what the log package uses internally. It's not as straightforward as C macros, but you can hide it behind a function (and specify the correct call depth). You can see how the log package for example is implemented (line 140).

+14
source share

(1) Write a short function calling runtime.Caller ()

(2) Call this function wherever 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 line number where the file_line () function is called, and not where runtime.Caller () is called.

 fmt.Println(file_line()) // Prints this file and line number. 
+7
source share

See the runtime and runtime.debug and, in particular, the Stack , PrintStack or Caller functions .

The stack formats the stack trace of the caller goroutine in buf and returns the number of bytes written to buf. If everything is correct, Stack formats the stacks of all other goroutines in buf after tracing the current goroutine.

If you compile debugging information, this will contain the line number in the source

+2
source share

All Articles