"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can You Create an OpenTelemetry Span from a String TraceID?

How Can You Create an OpenTelemetry Span from a String TraceID?

Published on 2024-11-05
Browse:428

How Can You Create an OpenTelemetry Span from a String TraceID?

Constructing 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.

Solution

The following steps can be taken to construct a context or span on the subscriber side using the trace ID:

  1. Define a function with the trace ID as an argument:
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
}
  1. Inside the channel, call the function to construct the span context:
spanContext, err := constructNewSpanContext(request.TraceID)
if err != nil {
    log.Fatal(err)
}
  1. Enrich a context with the constructed span context:
requestContext := context.Background()
requestContext = trace.ContextWithSpanContext(requestContext, spanContext)
  1. Create a new span using the enriched context:
requestInLoopSpan, _ := otel.Tracer("requestInLoop").Start(requestContext, "requestInLoopSpan")

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.

Latest tutorial More>

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