Add internal/middleware/logger.go

This commit is contained in:
ata
2026-07-10 10:06:45 +00:00
committed by Gitee
parent 22f4fac069
commit 7cb671e6cc

View File

@@ -0,0 +1,44 @@
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(),
)
}
}