为什么我应该使用log.Println而不是fmt.Println?

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

Why should I use log.Println instead of fmt.Println?

问题

log.go(log包的实现)中可以看到:

167	// Println调用l.Output来打印日志。
168	// 参数的处理方式与fmt.Println相同。
169	func (l *Logger) Println(v ...interface{}) { l.Output(2, fmt.Sprintln(v...)) }

log.Println只是对fmt.Sprintln的一个函数包装,为什么我应该使用它而不是fmt.Printlnfmt.Sprintln

有什么实际的原因吗?

英文:

From log.go (the implementation of the log package) :

167	// Println calls l.Output to print to the logger.
168	// Arguments are handled in the manner of fmt.Println.
169	func (l *Logger) Println(v ...interface{}) { l.Output(2, fmt.Sprintln(v...)) }

log.Println is just a function wrapper for fmt.Sprintln , why should I use it instead of fmt.Println or fmt.Sprintln ?

Any practical reasons ?

答案1

得分: 180

两件事情是不同的:

  1. 通过log包打印是安全的,可以在并发的goroutine中使用(而普通的fmt不行)。

  2. log可以自动添加时间信息。

所以这是两个完全不同的东西。log用于记录日志,fmt用于格式化输出。(好吧,log使用相同的动词和标志,但这只是方便之处)。

英文:

Two things are different:

  1. Printing via package log is safe from concurrent goroutines (while plain fmt isn't)

  2. Log can add timing information automatically.

So these are two completely different things. log is for logging and fmt for formatting. (Okay, log uses the same verbs and flags, but that is just convenient).

huangapple
  • 本文由 发表于 2013年10月29日 07:22:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/19646889.html
匿名

发表评论

匿名网友

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

确定