This commit is contained in:
oneao committed 2025-08-29 17:33:27 +08:00
1 parent 50fdacac07
commit 48cd564201
13 files changed
+220 -122

No files matched your search

@@ -5,12 +5,35 @@ import (
"base-framework/pkg/router"
"base-framework/pkg/routinex"
"base-framework/pkg/utils/uid"
"time"
)
// TrackTime 记录开始时间到现在时间的耗时
func TrackTime(pre time.Time) time.Duration {
elapsed := time.Since(pre)
return elapsed
}
func Logger() router.HandlerFunc {
return func(c *router.Context) {
routinex.Set(logx.TrackID, uid.NextID())
start := time.Now() // 记录开始时间
c.Next()
// 生成 trackID 并存入 routinex
trackID := uid.NextID()
routinex.Set(logx.TrackID, trackID)
c.Next() // 执行业务逻辑
// 请求结束后计算耗时
elapsed := TrackTime(start)
logx.Logger.Info("请求结束",
logx.String("logType", "request"),
logx.Uint64("trackID", trackID),
logx.String("path", c.Request.URL.Path),
logx.String("method", c.Request.Method),
logx.Duration("elapsed", elapsed),
)
}
}
@@ -1,3 +1,7 @@
/**
保证多routine共用同一数据
*/
package routinex
import (
@@ -7,7 +11,7 @@ import (
"sync"
)
// ------------------- goroutine id -------------------
// CurGID 获取 routine 的id
func CurGID() uint64 {
var buf [64]byte
n := runtime.Stack(buf[:], false)
@@ -25,6 +29,7 @@ var (
instanceOnce sync.Once
)
// GetInstance 获取当前示例
func GetInstance() *RoutineLocal {
instanceOnce.Do(func() {
instance = &RoutineLocal{}
@@ -57,7 +62,7 @@ func Clear() {
GetInstance().data.Delete(CurGID())
}
// Go 封装函数,自动继承父 goroutine 数据
// Go 自动继承父 goroutine 数据,多 routine 的时候需要使用
func Go(f func()) {
parentGID := CurGID()
parentData, _ := GetInstance().data.Load(parentGID)