何时使用log over fmt进行调试和打印错误? [英] When to use log over fmt for debugging and printing error?

查看:45
本文介绍了何时使用log over fmt进行调试和打印错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我们可以使用 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:

  • The log functions print to stderr by default and can directed to an arbitrary writer. The fmt.Printf function prints to stdout.
  • The log functions can print timestamp, source code location and other info.
  • The log functions and fmt.Printf are both thread safe, but concurrent writes by fmt.Printf above an OS dependent size can be interleaved.

三个子问题的答案是取决于".

The answer to the three sub questions are "it depends".

这篇关于何时使用log over fmt进行调试和打印错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆