This commit is contained in:
2025-11-05 23:52:48 +08:00
parent a1f7c09b2a
commit 5eeeeb5006
6 changed files with 51 additions and 18 deletions

View File

@@ -3,6 +3,7 @@ package logs
import (
"context"
"fmt"
"strings"
)
// contextKey 是用于在 context.Context 中存储值的私有类型,避免键冲突。
@@ -61,3 +62,29 @@ func AddFuncName(upstreamCtx context.Context, selfCtx context.Context, funcName
return newCtx
}
// DetachContext 创建一个“分离”的 Context。
// 新的 Context 会继承原始 Context 中的所有值(特别是用于日志追踪的 chainKey 和 compNameKey
// 但它会使用 context.Background() 作为其父级,从而“丢弃”原始 Context 的取消信号。
// 这对于需要在请求结束后继续执行的异步任务(如记录审计日志)至关重要,可以防止出现 "context canceled" 错误。
func DetachContext(ctx context.Context) context.Context {
detachedCtx := context.Background()
// 复制我们关心的、用于日志追踪的所有值
if val := ctx.Value(chainKey); val != nil {
detachedCtx = context.WithValue(detachedCtx, chainKey, val)
}
if val := ctx.Value(compNameKey); val != nil {
detachedCtx = context.WithValue(detachedCtx, compNameKey, val)
}
return detachedCtx
}
// 获取context中的调用链字符串
func GetTraceStr(ctx context.Context) string {
if trace, ok := ctx.Value(chainKey).([]string); ok {
return strings.Join(trace, "->")
}
return ""
}

View File

@@ -91,13 +91,13 @@ func GetLogger(ctx context.Context) *Logger {
return defaultLogger
}
chain, ok := val.([]string)
if !ok || len(chain) == 0 {
chain := GetTraceStr(ctx)
if chain == "" {
return defaultLogger
}
// 使用 With 方法创建带有 traceKey 字段的 Logger 副本
newSugaredLogger := defaultLogger.With(traceKey, strings.Join(chain, "->"))
newSugaredLogger := defaultLogger.With(traceKey, chain)
return &Logger{newSugaredLogger}
}
@@ -211,8 +211,11 @@ func (g *GormLogger) Trace(ctx context.Context, begin time.Time, fc func() (sql
"elapsed", fmt.Sprintf("%.3fms", float64(elapsed.Nanoseconds())/1e6),
}
// 获取带有调用链的 logger
logger := GetLogger(ctx)
// 附加调用链信息
chain := GetTraceStr(ctx)
if chain != "" {
fields = append(fields, traceKey, chain)
}
if err != nil {
// 如果是 "record not found" 错误且我们配置了跳过,则直接返回
@@ -220,18 +223,18 @@ func (g *GormLogger) Trace(ctx context.Context, begin time.Time, fc func() (sql
return
}
// 否则,记录为错误日志
logger.With(fields...).Errorf("[GORM] error: %s", err)
defaultLogger.With(fields...).Errorf("[GORM] error: %s", err)
return
}
// 如果查询时间超过慢查询阈值,则记录警告
if g.SlowThreshold != 0 && elapsed > g.SlowThreshold {
logger.With(fields...).Warnf("[GORM] slow query")
defaultLogger.With(fields...).Warnf("[GORM] slow query")
return
}
// 正常情况,记录 Debug 级别的 SQL 查询
logger.With(fields...).Debugf("[GORM] trace")
defaultLogger.With(fields...).Debugf("[GORM] trace")
// --- 逻辑修复结束 ---
}