何时使用log over fmt进行调试和打印错误? [英] When to use log over fmt for debugging and printing error?
问题描述
我知道我们可以使用 log
和 fmt
打印变量或错误.例如,如果我想打印变量,我可以这样做:
I know that we can print variable or error using log
and fmt
. for example if I want to print variable I can do this :
h := "world"
fmt.Printf("hello = %v\n", h)
log.Printf("halo = %v\n", h)
输出为:
hello = world
2016/12/30 09:13:12 halo = world
通常在错误处理中,我发现这样的日志
and usually in the error handling I found log like this
if err != nil {
log.Println("Error : something terrible happen -> ", err)
return err
}
但从上述情况来看,我也可以使用 fmt
来打印这样的错误
but from above case I could also use fmt
to print the error like this
fmt.Printf("Error : something terrible happen -> %v\n",err.Error())
使用 fmt
而不是 log
来打印错误是否是一种好习惯?然后我总是在调试时使用 fmt
而不是 log
来打印变量.
Is it a good practice to use fmt
instead of log
for printing the error?
And then I always use fmt
instead of log
for printing the variable when debugging.
推荐答案
使用以下事实在 log
和 fmt
之间进行选择:
Select between log
and fmt
using these facts:
-
log
函数默认情况下会打印到 stderr ,并且可以定向到任意作者.fmt.Printf
函数将打印到 stdout . -
log
函数可以打印时间戳,源代码位置和其他信息. -
log
函数和fmt.Printf
都是线程安全的,但是fmt.Printf
并发写操作可以在高于OS的情况下进行.交错.
- The
log
functions print to stderr by default and can directed to an arbitrary writer. Thefmt.Printf
function prints to stdout. - The
log
functions can print timestamp, source code location and other info. - The
log
functions andfmt.Printf
are both thread safe, but concurrent writes byfmt.Printf
above an OS dependent size can be interleaved.
三个子问题的答案是取决于".
The answer to the three sub questions are "it depends".
这篇关于何时使用log over fmt进行调试和打印错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!