我试图使用log.Fatal
在我的Golang程序中抛出错误,但log.Fatal
也不打印log.Fatal
运行的行。有没有办法访问调用log.Fatal的行号?即,在抛出错误时有没有办法获取行号?
我试图谷歌这个,但不确定如何。我能得到的最好的东西是printing the stack trace,我觉得这很好,但可能有点太多了。每次我需要行号时,我也不想写debug.PrintStack()
,我很惊讶没有任何内置函数,如log.FatalStackTrace()
或不是服装的东西。< / p>
另外,我不想自己进行调试/错误处理的原因是因为我不希望人们必须学习如何使用我的特殊服装处理代码。我只想要一些标准的东西,人们可以在以后阅读我的代码,就像
“啊好的,所以它抛出错误并做X ......”
人们越少了解我的代码越好:)
答案 0 :(得分:92)
您可以在自定义记录器上设置标志,或者默认设置为Llongfile
or Lshortfile
// to change the flags on the default logger
log.SetFlags(log.LstdFlags | log.Lshortfile)
答案 1 :(得分:66)
简短版本,没有直接构建在中,但您可以使用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's the end of the world")) {
log.Print("stuff")
}
}
答案 2 :(得分:0)
如果您确实需要堆栈跟踪,请查看https://github.com/ztrue/tracerr
我创建此程序包的目的是为了使堆栈跟踪和源代码片段都能更快地调试并记录错误,并提供更多详细信息。
这是一个代码示例:
package main
import (
"io/ioutil"
"github.com/ztrue/tracerr"
)
func main() {
if err := read(); err != nil {
tracerr.PrintSourceColor(err)
}
}
func read() error {
return readNonExistent()
}
func readNonExistent() error {
_, err := ioutil.ReadFile("/tmp/non_existent_file")
// Add stack trace to existing error, no matter if it's nil.
return tracerr.Wrap(err)
}