Go的日志包在默认格式化时发生了PANIC。

huangapple go评论80阅读模式
英文:

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
$ 

huangapple
  • 本文由 发表于 2012年5月13日 16:51:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/10570456.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定