修bug
This commit is contained in:
@@ -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 ""
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user