我们在极速快三源码搭建项目的调试过程中,需要将一些自定义信息写入到log文件中,gin框架中提供了基础的Logger()方法,查看gin的文档,有如下信息:企 娥:217 1793 408
How to write log file
func main() {
// Disable Console Color, you don‘t need console color when writing the logs to file.
gin.DisableConsoleColor()
// Logging to a file.
f, _ := os.Create("gin.log")
gin.DefaultWriter = io.MultiWriter(f)
// Use the following code if you need to write the logs to file and console at the same time.
// gin.DefaultWriter = io.MultiWriter(f, os.Stdout)
router := gin.Default()
router.GET("/ping", func(c *gin.Context) {
c.String(200, "pong")
})
router.Run(":8080")
}
可以看到gin是通过DefaultWriter来确定日志写入的,查看代码(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 "/mattn/go-colorable"
// gin.DefaultWriter = colorable.NewColorableStdout()
var DefaultWriter io.Writer = os.Stdout
var DefaultErrorWriter io.Writer = os.Stderr
DefaultWriter是包外可见的变量,类型是io.Writer,在gin自己的Logger中调用方法如下:
fmt.Fprintf(out, "[GIN] %v |%s %3d %s| %13v | %15s |%s %-7s %s %s\n%s",
end.Format("2006/01/02 - 15:04:05"),
statusColor, statusCode, resetColor,
latency,
clientIP,
methodColor, method, resetColor,
path,
comment,
)
原文地址:http://blog.51cto.com/13840447/2133347