OpenTelemetry Traceparent HTTP Header

What is traceparent header?

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

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 trace id from it to find the trace in a distributed tracing toolopen in new window.

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 like this:

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)
}

You should 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)
Last Updated: