Files
workspace/code/base-project/base-go-v2/internal/api/middleware/logger.go
T
2025-11-11 16:35:32 +08:00

44 lines
950 B
Go

package middleware
import (
"base-go-v2/internal/logx"
"base-go-v2/internal/router"
"base-go-v2/internal/routinex"
"base-go-v2/internal/utils/idgen"
"time"
)
// TrackTime 记录开始时间到现在时间的耗时
func TrackTime(pre time.Time) time.Duration {
elapsed := time.Since(pre)
return elapsed
}
func LoggerMiddleware() router.HandlerFunc {
return func(c *router.Context) error {
start := time.Now() // 记录开始时间
// 生成 trackID 并存入 routinex
trackID := idgen.NextId()
routinex.Set(logx.TrackID, trackID)
// 执行业务逻辑,并捕获错误
err := c.Next()
// 请求结束后计算耗时
elapsed := TrackTime(start)
ip := c.RequestCtx.RemoteIP().String()
logx.Logger.Info("接口请求",
logx.String("path", string(c.RequestCtx.Path())),
logx.String("method", string(c.RequestCtx.Method())),
logx.String("ip", ip),
logx.Duration("elapsed", elapsed),
)
return err
}
}