How do you get the Golang program to print the error line number that it just caused?

I tried to issue errors in my Golang program using log.Fatal , but log.Fatal also does not print the line where log.Fatal was run. There is no way to access the line number called log.Fatal? that is, is there a way to get the line number when throwing an error?

I tried to do it, but did not know how to do it. The best I could get was a stack trace print , which I think is good, but might be a little too much. I also do not want to write debug.PrintStack() every time I need a line number, I am just surprised that there is no built-in function for this, for example log.FatalStackTrace() or something that is not a suit.

Also, the reason I don’t want to create my own tools for debugging / error handling is because I don’t want people to learn how to use my special costume handling code. I just want something standard where people can read my code later and look like

"ah ok, so he throws an error and makes X ..."

The less people find out about my code, the better :)

+55
go error-handling
Jul 17 '14 at 16:50
source share
2 answers

You can set flags on custom logger or by default to enable Llongfile or Lshortfile

 // to change the flags on the default logger log.SetFlags(log.LstdFlags | log.Lshortfile) 
+65
Jul 17 '14 at 17:26
source share

Short version there is nothing built into however you can implement it with a minimal learning curve using runtime.Caller

 func HandleError(err error) (b bool) { if err != nil { // notice that we're using 1, so it will actually log where // the error happened, 0 = this function, we don't want that. _, fn, line, _ := runtime.Caller(1) log.Printf("[error] %s:%d %v", fn, line, err) b = true } return } //this logs the function name as well. func FancyHandleError(err error) (b bool) { if err != nil { // notice that we're using 1, so it will actually log the where // the error happened, 0 = this function, we don't want that. pc, fn, line, _ := runtime.Caller(1) log.Printf("[error] in %s[%s:%d] %v", runtime.FuncForPC(pc).Name(), fn, line, err) b = true } return } func main() { if FancyHandleError(fmt.Errorf("it the end of the world")) { log.Print("stuff") } } 

playground

+47
Jul 17 '14 at 17:11
source share



All Articles