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
网友评论