美文网首页
使用gin中间件记录访问日志

使用gin中间件记录访问日志

作者: wayyyy | 来源:发表于2022-05-15 04:09 被阅读0次
    package main
    
    import (
        "fmt"
        "github.com/gin-gonic/gin"
        "time"
    )
    
    func main() {
        r := gin.New()
        r.Use(AccessLog())
    
        handlers := func(c *gin.Context) {
            c.JSON(200, "index")
        }
    
        r.GET("/", handlers)
    
        r.Run(":8080")
    }
    
    func AccessLog() gin.HandlerFunc {
        return func(c *gin.Context) {
            startTime := time.Now()
            c.Next()
            latency := time.Since(startTime)
            referer := c.Request.Referer()
            if referer == "" {
                referer = "-"
            }
    
            accessStr := fmt.Sprintf("%s %s %s %s %s %s %d %d",
                c.ClientIP(),
                time.Now().UTC().Format("2006-01-02 15:04:05.000z"),
                c.Request.Method,
                c.Request.Host,
                referer,
                c.Request.URL,
                c.Writer.Status(),
                latency.Nanoseconds()/1000000)
    
            fmt.Println(accessStr)
        }
    }
    

    输出如下:
    127.0.0.1 2022-05-14 20:08:17.574z GET 127.0.0.1:8080 - / 200 0

    相关文章

      网友评论

          本文标题:使用gin中间件记录访问日志

          本文链接:https://www.haomeiwen.com/subject/lhsvurtx.html