forked from tel-io/tel
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontext.go
More file actions
68 lines (53 loc) · 1.58 KB
/
Copy pathcontext.go
File metadata and controls
68 lines (53 loc) · 1.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package tel
import (
"context"
"github.com/tel-io/tel/v2/otlplog/logskd"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"go.opentelemetry.io/otel/trace"
)
type tKey struct{}
func WithContext(ctx context.Context, l Telemetry) context.Context {
if lp, ok := ctx.Value(tKey{}).(*Telemetry); ok {
if lp.Logger != l.Logger {
return ctx
}
}
return WrapContext(ctx, &l)
}
func WrapContext(ctx context.Context, l *Telemetry) context.Context {
return context.WithValue(ctx, tKey{}, l)
}
// FromCtx retrieves from ctx tel object
func FromCtx(ctx context.Context) *Telemetry {
if t, ok := ctx.Value(tKey{}).(*Telemetry); ok {
return t
}
v := Global().Copy()
v.Logger.WithOptions(
zap.WithCaller(true),
zap.AddCallerSkip(1),
zap.AddStacktrace(zapcore.WarnLevel),
).Warn("use null Telemetry")
v.PutFields(String("warn", "use null Telemetry"))
return &v
}
// UpdateTraceFields during session start good way to update tracing fields
// @prefix - for split different inter-service calls: kafka, grpc, db and etc
func UpdateTraceFields(ctx context.Context) {
span := trace.SpanFromContext(ctx)
if span == nil {
return
}
if span.SpanContext().HasTraceID() {
tele := FromCtx(ctx)
tele.PutSpan(span)
tele.PutFields(zap.Any(logskd.SpanKey, span))
}
}
// StartSpanFromContext start telemetry span witch create or continue existent trace
// for gracefully continue trace ctx should contain both span and tele
func StartSpanFromContext(ctx context.Context, name string, opts ...trace.SpanStartOption) (
trace.Span, context.Context) {
return FromCtx(ctx).StartSpan(ctx, name, opts...)
}