你如何让 Golang 程序打印它刚刚调用的错误的行号? [英] How do you get a Golang program to print the line number of the error it just called?

查看:44
本文介绍了你如何让 Golang 程序打印它刚刚调用的错误的行号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I was trying to throw errors in my Golang program with log.Fatal but, log.Fatal does not also print the line where the log.Fatal was ran. Is there no way of getting access to the line number that called log.Fatal? i.e. is there a way to get the line number when throwing an error?

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

I was trying to google this but was unsure how. The best thing I could get was printing the stack trace, which I guess is good but might be a little too much. I also don't want to write debug.PrintStack() every time I need the line number, I am just surprised there isn't any built in function for this like log.FatalStackTrace() or something that isn't costume.

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

Also, the reason I do not want to make my own debugging/error handling stuff is because I don't want people to have to learn how to use my special costume handling code. I just want something standard where people can read my code later and be like

嗯,好吧,所以它抛出一个错误并执行 X..."

"ah ok, so its throwing an error and doing X..."

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

The less people have to learn about my code the better :)

推荐答案

您可以在自定义 Logger 上设置标志,也可以默认包含 LlongfileLshortfile

You can set the Flags on either a custom Logger, or the default to include Llongfile or Lshortfile

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

这篇关于你如何让 Golang 程序打印它刚刚调用的错误的行号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆