OpenTelemetry Traceparent HTTP Header [Go]
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:
Using the header, you can extract a trace id to find the trace in a distributed tracing tool, 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 always00
.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
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 = NewTraceparentHandler(handler)
// Finally, serve requests.
http.ListenAndServe(":3000", handler)
Example
Need an example? Uptrace is an OpenTelemetry APM that uses the TraceparentHandler middleware to add the traceparent
header to all HTTP responses.
- Navigate to Uptrace demo and open Chrome Debug Console.
- In the "Network" tab, click on a HTTP request and open the "Headers" tab.
- Locate the
Traceparent
header and use it to find the trace.