Constructing Spans from Trace IDs in Opentelemetry
Context propagation is typically used to retrieve parent trace IDs and create spans as children. However, in scenarios where headers are employed for message exchange, alternative approaches are necessary.
To create a span from a string trace ID, you can follow these steps:
Construct a Function to Parse Trace and Span IDs:
func constructNewSpanContext(request NewRequest) (spanContext trace.SpanContext, err error) {
traceID, err := trace.TraceIDFromHex(request.TraceID)
if err != nil {
fmt.Println("error:", err)
}
spanID, err := trace.SpanIDFromHex(request.SpanID)
if err != nil {
fmt.Println("error:", err)
}
spanContextConfig := trace.SpanContextConfig{
TraceID: traceID,
SpanID: spanID,
TraceFlags: 01,
Remote: false,
}
spanContext = trace.NewSpanContext(spanContextConfig)
return spanContext, nil
}
This function extracts the trace and span IDs from the request and constructs a SpanContext object.
Inject SpanContext into Context:
spanContext, err := constructNewSpanContext(request)
if err != nil {
fmt.Println("ERROR:", err)
}
requestContext := context.Background()
requestContext = trace.ContextWithSpanContext(requestContext, spanContext)
The SpanContext is used to enrich the request context, indicating the continuation of the trace.
Create a New Span:
var requestInLoopSpan trace.Span
childContext, requestInLoopSpan := otel.Tracer("inboundmessage").Start(requestContext, "requestInLoopSpan")
requestInLoopSpan.AddEvent("processing....")
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3