gin中自定义路由日志的格式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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")
}

  

日志输出格式:

1
2
3
4
5
6
7
8
/*
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" "
 */

  

posted @   专职  阅读(241)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示