你怎么得到一个Golang程序来打印它刚刚调用的错误的行号?

Pin*_*hio 78 error-handling go

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

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

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

"啊好的,所以它抛出一个错误并做X ......"

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

Jim*_*imB 102

您可以在自定义Logger上设置Flags,或者将默认设置为include LlongfileLshortfile

// to change the flags on the default logger
log.SetFlags(log.LstdFlags | log.Lshortfile)
Run Code Online (Sandbox Code Playgroud)

  • 你必须把它放在`func init(){}`中 (5认同)
  • 是的,如果你使用自定义日志,你可以使用它像`var mylog = log.New(os.Stderr,"app:",log.LstdFlags | log.Lshortfile)`. (3认同)
  • @Pinocchio:那个错误是因为它无效Go,你不能在顶层进行裸函数调用.把它放在init()或其他一些入口点. (3认同)

One*_*One 78

精简版, 没有直接内置的东西但是,您可以使用最小的学习曲线来实现它 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")
    }
}
Run Code Online (Sandbox Code Playgroud)

playground

  • 虽然已经给出的答案整齐地解决了问题,但是您的解决方案提醒我存在一些非常棒的东西 - 运行时包!可爱的东西:) https://golang.org/pkg/runtime/ (10认同)

小智 7

如果您确实需要堆栈跟踪,请查看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)
}
Run Code Online (Sandbox Code Playgroud)

这是输出: golang 错误堆栈跟踪