你如何让 Golang 程序打印它刚刚调用的错误的行号?

新手上路,请多包涵

我试图在我的 Golang 程序中抛出错误 log.Fatal 但是, log.Fatal 也没有打印 log.Fatal .有没有办法访问调用 log.Fatal 的行号?即有没有办法在抛出错误时获取行号?

我试图用谷歌搜索这个但不确定如何。我能得到的最好的东西是 打印堆栈跟踪,我想这很好,但可能有点太多了。我也不想写 debug.PrintStack() 每次我需要行号时,我很惊讶没有任何内置函数,比如 log.FatalStackTrace() 或类似的东西服装。

另外,我不想自己做调试/错误处理的原因是因为我不想让人们必须学习如何使用我的特殊服装处理代码。我只想要一些标准的东西,人们可以在以后阅读我的代码并像

“啊好吧,所以它抛出错误并执行 X……”

了解我的代码的人越少越好 :)

原文由 Charlie Parker 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.3k
2 个回答

您可以在自定义记录器上设置标志,或默认设置为包括 LlongfileLshortfile

 // to change the flags on the default logger
log.SetFlags(log.LstdFlags | log.Lshortfile)

原文由 JimB 发布,翻译遵循 CC BY-SA 3.0 许可协议

精简版,没有直接内置的东西,但是您可以使用 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.
        _, filename, line, _ := runtime.Caller(1)
        log.Printf("[error] %s:%d %v", filename, 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, filename, line, _ := runtime.Caller(1)

        log.Printf("[error] in %s[%s:%d] %v", runtime.FuncForPC(pc).Name(), filename, line, err)
        b = true
    }
    return
}

func main() {
    if FancyHandleError(fmt.Errorf("it's the end of the world")) {
        log.Print("stuff")
    }
}

操场

原文由 OneOfOne 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题