Files
LaodingBot/internal/logger/trace.go

33 lines
545 B
Go
Raw Normal View History

package logger
import (
"context"
"fmt"
"math/rand"
"time"
)
type traceIDKey struct{}
func NewTraceID() string {
now := time.Now().UTC().UnixNano()
randPart := rand.Int63()
return fmt.Sprintf("tr-%x-%x", now, randPart)
}
func WithTraceID(ctx context.Context, traceID string) context.Context {
if traceID == "" {
return ctx
}
return context.WithValue(ctx, traceIDKey{}, traceID)
}
func TraceIDFromContext(ctx context.Context) string {
if ctx == nil {
return ""
}
v := ctx.Value(traceIDKey{})
s, _ := v.(string)
return s
}