37 lines
644 B
Go
37 lines
644 B
Go
package middleware
|
|
|
|
import (
|
|
"log"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
// RequestLogging 请求日志中间件
|
|
func RequestLogging() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
start := time.Now()
|
|
|
|
// 处理请求
|
|
c.Next()
|
|
|
|
// 记录日志
|
|
duration := time.Since(start)
|
|
statusCode := c.Writer.Status()
|
|
method := c.Request.Method
|
|
path := c.Request.URL.Path
|
|
clientIP := c.ClientIP()
|
|
|
|
logLevel := "[INFO]"
|
|
if statusCode >= 500 {
|
|
logLevel = "[ERROR]"
|
|
} else if statusCode >= 400 {
|
|
logLevel = "[WARN]"
|
|
}
|
|
|
|
log.Printf("%s %s %s %d %v %s",
|
|
logLevel, method, path, statusCode, duration, clientIP,
|
|
)
|
|
}
|
|
}
|