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

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

问题描述

我试图在我的Golang程序中使用 log.Fatal 错误,但是, 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?

我试图google这个但不确定如何。我可以得到的最好的事情是打印堆栈跟踪,我猜这是好的,但也可能有点太许多。我也不想在每次需要行号时写入 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 :)

推荐答案

您可以在自定义记录器上设置标志,也可以将默认值设置为 Llongfile Lshortfile

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天全站免登陆