40 lines
773 B
Go
40 lines
773 B
Go
package middleware
|
|
|
|
import (
|
|
"log/slog"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
// Logger 请求日志中间件,记录方法、路径、状态码、耗时
|
|
func Logger() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
start := time.Now()
|
|
path := c.Request.URL.Path
|
|
|
|
c.Next()
|
|
|
|
latency := time.Since(start)
|
|
status := c.Writer.Status()
|
|
query := RedactSensitiveQuery(c.Request.URL.RawQuery)
|
|
auth := c.GetHeader("Authorization")
|
|
authPrefix := ""
|
|
if auth != "" {
|
|
authPrefix = strings.SplitN(auth, " ", 2)[0]
|
|
}
|
|
|
|
slog.Info("请求",
|
|
"requestId", RequestID(c),
|
|
"method", c.Request.Method,
|
|
"path", path,
|
|
"query", query,
|
|
"status", status,
|
|
"latency", latency.String(),
|
|
"ip", c.ClientIP(),
|
|
"authType", authPrefix,
|
|
)
|
|
}
|
|
}
|