Constructing Spans from Trace IDs in Non-HTTP Contexts
When propagating traces using headers in non-HTTP contexts, you need to manually construct spans using the provided trace and span IDs. Here's how to achieve this:
Subscriber Side:
Inside a function that handles incoming messages with trace and span headers:
Example:
<code class="go">func handleIncomingMessage(request NewRequest) { traceID, err := trace.TraceIDFromHex(request.TraceID) if err != nil { fmt.Println("error: ", err) return } spanID, err := trace.SpanIDFromHex(request.SpanID) if err != nil { fmt.Println("error: ", err) return } spanContext := trace.NewSpanContext(trace.SpanContextConfig{ TraceID: traceID, SpanID: spanID, TraceFlags: 01, Remote: false, }) ctx := context.Background() ctx = trace.ContextWithSpanContext(ctx, spanContext) _, span := otel.Tracer("requestInLoop").Start(ctx, "requestInLoopSpan") span.AddEvent("processing....") }</code>
In this example, NewRequest is a custom type that contains the trace and span IDs. The handleIncomingMessage function takes a NewRequest struct as input and creates a span with the provided trace and span IDs.
Note: Ensure that new spans are not created if the IsRemote field of the provided span context is set to true, as this indicates that the span was already exported remotely.
The above is the detailed content of How to Construct Spans from Trace IDs in Non-HTTP Contexts?. For more information, please follow other related articles on the PHP Chinese website!