gin中自定义路由日志的格式
package main import ( "fmt" "github.com/gin-gonic/gin" "net/http" "time" ) func main() { router := gin.New() // LoggerWithFormatter middleware will write the logs to gin.DefaultWriter // By default gin.DefaultWriter = os.Stdout router.Use(gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string { // your custom format return fmt.Sprintf("%s - [%s] \"%s %s %s %d %s \"%s\" %s\"\n", param.ClientIP, // 客户端IP param.TimeStamp.Format(time.RFC3339), // 请求时间 param.Method, // 请求方法 param.Path, // 请求路径 param.Request.Proto, // 请求协议 param.StatusCode, // 请求状态码 param.Latency, // 请求时长 param.Request.UserAgent(), // 请求 param.ErrorMessage, ) })) router.Use(gin.Recovery()) router.GET("/ping", func(c *gin.Context) { c.String(200, "pong") }) router.POST("/string", func(context *gin.Context) { context.JSON(http.StatusOK, "OK") }) router.Run("192.168.110.20:3000") }
日志输出格式:
/* 192.168.110.20 - [2021-10-27T10:42:28+08:00] "GET /ping HTTP/1.1 200 563.7µs "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36" " 192.168.110.20 - [2021-10-27T10:42:57+08:00] "GET /ping HTTP/1.1 200 0s "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:78.0) Gecko/20100101 Firefox/78.0" " 192.168.110.20 - [2021-10-27T10:42:58+08:00] "GET /favicon.ico HTTP/1.1 404 0s "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:78.0) Gecko/20100101 Firefox/78.0" " 192.168.110.20 - [2021-10-27T10:44:00+08:00] "POST /string HTTP/1.1 200 592.2µs "PostmanRuntime/7.26.8" " 192.168.110.20 - [2021-10-27T10:44:24+08:00] "GET /ping HTTP/1.1 200 0s "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.54 Safari/537.36 Edg/95.0.1020.30" " 192.168.110.20 - [2021-10-27T10:44:37+08:00] "GET /favicon.ico HTTP/1.1 404 0s "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.54 Safari/537.36 Edg/95.0.1020.30" " */