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

来自 日志,开始(日志包的实现) :

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 只是 fmt.Sprintln的函数包装器,为什么要用它来代替 fmt.Printlnfmt.Sprintln

有什么实际原因吗?

30669 次浏览

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).