u
This commit is contained in:
1 parent
b116690769
commit
1d6bb2b7f5
23 files changed
+922
-116
No files matched your search
@@ -0,0 +1,43 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"base-go-v2/internal/logx"
|
||||
"base-go-v2/internal/router"
|
||||
"base-go-v2/internal/routinex"
|
||||
"base-go-v2/internal/utils/uid"
|
||||
"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 := uid.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
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user