英文:
Gin outputs to a file
问题
我正在使用Gin来创建REST API服务器,Gin会将输出显示在控制台上,类似于这样:Gin控制台示例。
我想将Gin的输出保存到文件而不是控制台上。
我在Gin/mode.go中找到了以下代码:
// DefaultWriter is the default io.Writer used the Gin for debug output and
// middleware output like Logger() or Recovery().
// Note that both Logger and Recovery provides custom ways to configure their
// output io.Writer.
// To support coloring in Windows use:
// import "github.com/mattn/go-colorable"
// gin.DefaultWriter = colorable.NewColorableStdout()
var DefaultWriter io.Writer = os.Stdout
var DefaultErrorWriter io.Writer = os.Stderr
看起来我可以通过在我的代码中设置类似于
gin.DefaultWriter = something
来更改DefaultWriter和DefaultErrorWriter的行为。
但是我不知道如何编写那个'something'代码;它必须是一个将内容写入文件的函数,但是我不知道如何/从哪里开始。
所以,我的问题是:
- 我的方向正确吗?
- 如何编写那个'something'函数?如果您能提供一个示例,将非常有帮助。
谢谢。
英文:
I'm using Gin to make REST API server and Gin shows its output on a console like this: Gin console example
I'd like to make gin's output to a file instead of console.
What I've found is below code from Gin/mode.go
// DefaultWriter is the default io.Writer used the Gin for debug output and
// middleware output like Logger() or Recovery().
// Note that both Logger and Recovery provides custom ways to configure their
// output io.Writer.
// To support coloring in Windows use:
// import "github.com/mattn/go-colorable"
// gin.DefaultWriter = colorable.NewColorableStdout()
var DefaultWriter io.Writer = os.Stdout
var DefaultErrorWriter io.Writer = os.Stderr
Looks like I can change DefaultWriter and DefaultErrorWriter's behavior by setting like
gin.DefaultWriter = something
on my code.
But I have no idea how to write that 'something' code; it must be a function which writes to a file but have no idea how/where to start.
So, my questions are:
- Am I heading to the right direction?
- How to write that 'something' function? It would be very helpful if you can provide an example.
Thank you.
答案1
得分: 4
你可以使用os
包来创建一个文件。
file, fileErr := os.Create("file")
if fileErr != nil {
fmt.Println(fileErr)
return
}
gin.DefaultWriter = file
这段代码将创建一个文件并开始向其写入内容。
英文:
You can use os
package to create a file.
file, fileErr := os.Create("file")
if fileErr != nil {
fmt.Println(fileErr)
return
}
gin.DefaultWriter = file
This should create a file and start writing to it.
答案2
得分: 0
你可以尝试使用nohup命令来运行你的API。
- 运行构建命令来构建你的项目。
<name_of_project> 可以是任何名称
> go build -o ./build/<name_of_project>
- 运行构建的项目。<output_file> 的名称可以是任意的
> nohup ./build/<name_of_project> > <output_file>.out
这将把所有的日志语句打印到 .out 文件中。
英文:
You can try running your API via nohup command.
- Run the build command to build your project.
<name_of_project> can be anything
> go build -o ./build/<name_of_project>
- Run the build project. <output_file> name can be anything
> nohup ./build/<name_of_project> > <output_file>.out
This will print all the log statements in the .out file.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论