how to save fmt.Print and log.Print into same file in Golang

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

how to save fmt.Print and log.Print into same file in Golang

问题

在shell中,我使用go run file > output命令,但只有fmt.Print的输出保存到了output文件中。所有的log.Print仍然输出到屏幕上!在我在互联网上搜索之后,我发现可以为日志设置输出目录,但是如何将日志和fmt同时保存到同一个文件中呢?

英文:

In shell, I use go run file > output, but only fmt.Print are saved into output. All the log.Print still output to the screen! And after I searched on the Internet, I found I can set ouput directory for log, but how can I save both log and fmt in the same file?

答案1

得分: 6

日志记录器将日志写入 STDERR,而 fmt.PrintXXX 函数将日志写入 STDOUT。

你有两个选择:

  1. 将 STDERR 输出到文件中。
    类似 Bash 的 shell 使用以下命令:

    go run file > output 2>&1

  2. 将日志记录器的 Output 设置为 os.Stdout

然后你可以像平常一样运行 go run file > output,日志记录器和 fmt 都会输出到同一个地方。

log.SetOutput(os.StdOut)
英文:

The logger writes to STDERR while fmt.PrintXXX functions write to STDOUT.

You have two choices:

  1. Capture STDERR to the file.
    Bash like shells use:

    go run file > output 2>&1

  2. Set the logger's Output to os.Stdout

Then you run like normal go run file > output and both the logger and fmt go to the same place.

log.SetOutput(os.StdOut)

huangapple
  • 本文由 发表于 2015年12月16日 00:16:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/34294151.html
匿名

发表评论

匿名网友

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

确定