英文:
PANIC in default formatting with Go's log package
问题
当使用log.Println
在Go中进行登录时,我经常会得到以下错误信息:
2012/05/13 16:45:50 evaluating %v(PANIC=3)
我不确定我做错了什么,我猜想可能是在我的某个Stringer
接口实现中,fmt.Println
捕获了一个由我自己生成的panic,以避免由于日志记录失败而导致程序崩溃。
我该如何找出发生了什么?为什么会出现这个错误信息?
英文:
When logging in Go with log.Println
, I frequently get
2012/05/13 16:45:50 evaluating %v(PANIC=3)
I'm not sure how to determine what I've done wrong, I assume that somewhere fmt.Println
has caught a panic generated by one of my own Stringer
interface implementations, so as not to crash my program due to logging failure.
How do I work out what's going on? Why am I getting this erroneous message?
答案1
得分: 3
你是对的,String
方法中发生了一次panic。但这与log
包无关。Println
使用了%v
,而%v
表示运行String
方法。在String
方法中发生panic会调用catchPanic
。在你的输出中,3
是panic的值。
英文:
You are right, there is a panic in a String
method. But it has nothing to do with the log
package. Println
uses %v
, and %v
means running String
method. Having a panic in the String
method invokes catchPanic
. Here in your output 3
is the value of your panic.
答案2
得分: 1
没有代码进行检查很难说。为了调试它,也许尝试将log.Println("evaluating", foo)
替换为log.Printf("evaluating %#v\n", foo)
。它的工作方式有点不同:
package main
import "log"
type t int
func (t) String() string {
panic(3)
}
func main() {
var v t = 42
log.Println("evaluating", v)
log.Printf("evaluating %#v\n", v)
}
运行结果:
2012/05/13 11:19:49 evaluating %v(PANIC=3)
2012/05/13 11:19:49 evaluating 42
英文:
W/o the code to inspect it's hard to say. To debug it, perhaps try replacing log.Println("evaluating", foo)
with log.Printf("evaluating %#v\n", foo)
. It works a bit differently:
package main
import "log"
type t int
func (t) String() string {
panic(3)
}
func main() {
var v t = 42
log.Println("evaluating", v)
log.Printf("evaluating %#v\n", v)
}
$ go run main.go
2012/05/13 11:19:49 evaluating %v(PANIC=3)
2012/05/13 11:19:49 evaluating 42
$
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论