How to log messages to the console and a file both in golang?

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

How to log messages to the console and a file both in golang?

问题

我可以将所有消息定向到log.txt文件中:

logFile, err := os.OpenFile("log.txt", os.O_CREATE|os.O_APPEND|os.O_RDWR, 0666)
if err != nil {
    panic(err)
}
log.SetOutput(logFile)

但是我如何在控制台中获取日志消息呢?

英文:

I can direct all messages to log.txt file:

logFile, err := os.OpenFile("log.txt", os.O_CREATE | os.O_APPEND | os.O_RDWR, 0666)
if err != nil {
	panic(err)
}
log.SetOutput(logFile)

But how can I get log messages in console too?

答案1

得分: 110

使用io.MultiWriter

> MultiWriter创建一个写入器,将其写入复制到所有提供的写入器中,类似于Unix的tee(1)命令

logFile, err := os.OpenFile("log.txt", os.O_CREATE | os.O_APPEND | os.O_RDWR, 0666)
if err != nil {
    panic(err)
}
mw := io.MultiWriter(os.Stdout, logFile)
log.SetOutput(mw)

唯一的更改是

mw := io.MultiWriter(os.Stdout, logFile)
英文:

Use an io.MultiWriter

> MultiWriter creates a writer that duplicates its writes to all the provided writers, similar to the Unix tee(1) command

logFile, err := os.OpenFile("log.txt", os.O_CREATE | os.O_APPEND | os.O_RDWR, 0666)
if err != nil {
    panic(err)
}
mw := io.MultiWriter(os.Stdout, logFile)
log.SetOutput(mw)

The only change was

mw := io.MultiWriter(os.Stdout, logFile)

huangapple
  • 本文由 发表于 2016年4月19日 21:13:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/36719525.html
匿名

发表评论

匿名网友

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

确定