如何将fmt.Print和log.Print保存到Golang中的同一文件中

Hao*_* Ge 2 shell go

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

Dav*_*rth 6

记录器写入STDERR,而fmt.PrintXXX函数写入STDOUT.

你有两个选择:

1)将STDERR捕获到文件中.
像shell一样使用Bash:

go run file > output 2>&1
Run Code Online (Sandbox Code Playgroud)

2)将记录器的输出设置为os.Stdout

然后你就像正常一样运行go run file > output,记录器和fmt都转到同一个地方.

log.SetOutput(os.StdOut)
Run Code Online (Sandbox Code Playgroud)