做完了一部分,备份一下,防止以外删除
This commit is contained in:
52
pkg/logger/middleware.go
Normal file
52
pkg/logger/middleware.go
Normal file
@@ -0,0 +1,52 @@
|
||||
package logger
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
// Middleware 创建 Fiber 日志中间件
|
||||
// 记录所有 HTTP 请求到访问日志
|
||||
func Middleware() fiber.Handler {
|
||||
return func(c *fiber.Ctx) error {
|
||||
// 记录请求开始时间
|
||||
startTime := time.Now()
|
||||
c.Locals(constants.ContextKeyStartTime, startTime)
|
||||
|
||||
// 处理请求
|
||||
err := c.Next()
|
||||
|
||||
// 计算请求持续时间
|
||||
duration := time.Since(startTime)
|
||||
|
||||
// 获取请求 ID(由 requestid 中间件设置)
|
||||
requestID := ""
|
||||
if rid := c.Locals(constants.ContextKeyRequestID); rid != nil {
|
||||
requestID = rid.(string)
|
||||
}
|
||||
|
||||
// 获取用户 ID(由 auth 中间件设置)
|
||||
userID := ""
|
||||
if uid := c.Locals(constants.ContextKeyUserID); uid != nil {
|
||||
userID = uid.(string)
|
||||
}
|
||||
|
||||
// 记录访问日志
|
||||
accessLogger := GetAccessLogger()
|
||||
accessLogger.Info("",
|
||||
zap.String("method", c.Method()),
|
||||
zap.String("path", c.Path()),
|
||||
zap.Int("status", c.Response().StatusCode()),
|
||||
zap.Float64("duration_ms", float64(duration.Microseconds())/1000.0),
|
||||
zap.String("request_id", requestID),
|
||||
zap.String("ip", c.IP()),
|
||||
zap.String("user_agent", c.Get("User-Agent")),
|
||||
zap.String(constants.ContextKeyUserID, userID),
|
||||
)
|
||||
|
||||
return err
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user