作者:手机用户2602935245 | 来源:互联网 | 2023-10-13 00:49
您可以使用最小的学习曲线来实现它 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")
}
}
您可以在自定义 Logger 上设置标志,或者默认设置为包含Llongfile
或Lshortfile
// to change the flags on the default logger
log.setflags(log.Lstdflags | log.Lshortfile)