How to Construct Spans from Trace IDs in Non-HTTP Contexts?

Susan Sarandon
Release: 2024-10-28 03:06:31
Original
815 people have browsed it

How to Construct Spans from Trace IDs in Non-HTTP Contexts?

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:

  1. Extract the trace and span IDs from the headers.
  2. Use the trace.TraceIDFromHex() and trace.SpanIDFromHex() functions to convert the string IDs into appropriate types.
  3. Construct a trace.SpanContext by providing the extracted trace ID, span ID, and trace flags.
  4. Enrich the current context with the newly created span context using context.Background(), followed by trace.ContextWithSpanContext().
  5. Start a new span using the enriched context with a appropriate name.

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!