Home >Backend Development >Golang >How Can You Create an OpenTelemetry Span from a String TraceID?
To establish the parent-child relationship between spans, the headers must be utilized in situations where context propagation is not viable. In this scenario, a trace ID and span ID are contained within the message broker's headers, which allows the subscriber to create a new span with the parent trace ID.
The following steps can be taken to construct a context or span on the subscriber side using the trace ID:
<code class="go">func constructNewSpanContext(traceID string) (spanContext trace.SpanContext, err error) { traceID, err := trace.TraceIDFromHex(traceID) if err != nil { return trace.SpanContext{}, err } return trace.NewSpanContext(trace.SpanContextConfig{ TraceID: traceID, }), nil }</code>
<code class="go">spanContext, err := constructNewSpanContext(request.TraceID) if err != nil { log.Fatal(err) }</code>
<code class="go">requestContext := context.Background() requestContext = trace.ContextWithSpanContext(requestContext, spanContext)</code>
<code class="go">requestInLoopSpan, _ := otel.Tracer("requestInLoop").Start(requestContext, "requestInLoopSpan")</code>
By following these steps, you can successfully construct a new span on the subscriber side using the trace ID extracted from the message headers, ensuring the hierarchical relationship between the spans.
The above is the detailed content of How Can You Create an OpenTelemetry Span from a String TraceID?. For more information, please follow other related articles on the PHP Chinese website!