Files
weichenandCursor bed0dbf076
ci / vet-and-test (push) Successful in 4s
ci / docker-checkout-hostgateway (push) Successful in 2s
Add a structured logger and collector so runs can be traced across processes.
Sync and async sinks, redaction, and a queryable HTTP service keep concurrent logs tied to a trace id.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-29 13:51:16 +00:00

40 lines
827 B
Go

package logsys
import "context"
type traceKey struct{}
// WithTrace 把追踪标识放进上下文。空标识不写入。
func WithTrace(ctx context.Context, id string) context.Context {
if ctx == nil {
ctx = context.Background()
}
if id == "" {
return ctx
}
return context.WithValue(ctx, traceKey{}, id)
}
// TraceFrom 读取追踪标识。不存在时返回空字符串。
func TraceFrom(ctx context.Context) string {
if ctx == nil {
return ""
}
id, _ := ctx.Value(traceKey{}).(string)
return id
}
// WithContext 返回带有上下文追踪标识的子 logger。上下文没有标识时原样返回副本。
func (l *Logger) WithContext(ctx context.Context) *Logger {
if l == nil {
return Nop()
}
id := TraceFrom(ctx)
if id == "" {
return l.clone()
}
n := l.clone()
n.traceID = id
return n
}