45 lines
817 B
Go
45 lines
817 B
Go
package middleware
|
|
|
|
import (
|
|
"log"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
// Logger 结构化日志中间件,记录请求 ID、方法、路径、状态码、耗时、客户端 IP
|
|
func Logger() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
start := time.Now()
|
|
path := c.Request.URL.Path
|
|
if raw := c.Request.URL.RawQuery; raw != "" {
|
|
path = path + "?" + raw
|
|
}
|
|
|
|
c.Next()
|
|
|
|
cost := time.Since(start)
|
|
rid := GetRequestID(c)
|
|
status := c.Writer.Status()
|
|
|
|
// 根据状态码选择日志级别标记
|
|
level := "INFO"
|
|
if status >= 500 {
|
|
level = "ERROR"
|
|
} else if status >= 400 {
|
|
level = "WARN"
|
|
}
|
|
|
|
log.Printf("[%s] req_id=%s | %s %s | %d | %s | ip=%s | size=%d",
|
|
level,
|
|
rid,
|
|
c.Request.Method,
|
|
path,
|
|
status,
|
|
cost.String(),
|
|
c.ClientIP(),
|
|
c.Writer.Size(),
|
|
)
|
|
}
|
|
}
|