OpenTelemetry Traceparent HTTP Header

OpenTelemetry Traceparent header

What is traceparent header?

The traceparent HTTP header contains information about the incoming request in a distributed tracing system, for example:

# {version}-{trace_id}-{span_id}-{trace_flags}
traceparent: 00-80e1afed08e019fc1110464cfa66635c-7a085853722dc6d2-01

You can find the traceparent header in a HTTP response, for example, using Google Chrome tools:

Traceparent header

Using the header, you can extract a trace id to find the trace in a distributed tracing toolopen in new window, for example, on the screenshot above the trace id is 80e1afed08e019fc1110464cfa66635c.

Traceparent header format

The traceparent header uses the version-trace_id-parent_id-trace_flags format where:

  • version is always 00.
  • trace_id is a hex-encoded trace id.
  • span_id is a hex-encoded span id.
  • trace_flags is a hex-encoded 8-bit field that contains tracing flags such as sampling, trace level, etc.

Injecting traceparent header

Go

You can inject the traceparent header into http.ResponseWriter with the following middleware:

import (
	"go.opentelemetry.io/otel"
	"go.opentelemetry.io/otel/propagation"
)

type TraceparentHandler struct {
	next  http.Handler
	props propagation.TextMapPropagator
}

func NewTraceparentHandler(next http.Handler) *TraceparentHandler {
	return &TraceparentHandler{
		next:  next,
		props: otel.GetTextMapPropagator(),
	}
}

func (h *TraceparentHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	h.props.Inject(req.Context(), propagation.HeaderCarrier(w.Header()))
	h.next.ServeHTTP(w, req)
}

Make sure to run the middleware after the first span is created, for example:

var handler http.Handler

handler = router

// First, use otelhttp to start a trace.
handler = otelhttp.NewHandler(handler, "")

// Then, use the middleware to inject traceparent.
handler = httputil.NewTraceparentHandler(handler)

// Finally, serve requests.
http.ListenAndServe(":3000", handler)

Example

Need an example? Uptrace is an OpenTelemetry APMopen in new window that uses the TraceparentHandleropen in new window middleware to add the traceparent header to all HTTP responses.

  1. Navigate to Uptrace demoopen in new window and open Chrome Debug Console.

  2. In the "Network" tab, click on a HTTP request and open the "Headers" tab.

  3. Locate the Traceparent header and use it to find the trace.

Traceparent header

Last Updated: 8/2/2023, 12:36:21 PM
Get insights and updates in your inbox: