Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

_file_ or _line_ similar in golang

Tags:

c

go

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?

like image 528
sateayam Avatar asked Jul 14 '13 14:07

sateayam


3 Answers

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).

like image 88
Kitsune Avatar answered Oct 24 '22 06:10

Kitsune


(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.
like image 14
Koala3 Avatar answered Oct 24 '22 05:10

Koala3


See the runtime and runtime.debug packages and in particular the Stack, PrintStack or Callerfunctions.

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

like image 2
Jeff Foster Avatar answered Oct 24 '22 04:10

Jeff Foster