OpenTelemetry Traceparent HTTP Header
What is traceparent header?
The traceparent
HTTP header contains information about the incoming request in a 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
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 uses the TraceparentHandler
middleware to add the traceparent
header to all HTTP responses.
Uptrace is an open source DataDog competitor with an intuitive query builder, rich dashboards, alerting rules, and integrations for most languages and frameworks. It can process billions of spans and metrics on a single server and allows to monitor your applications at 10x lower cost.
Uptrace uses ClickHouse database to store traces, metrics, and logs. You can use it to monitor applications and set up automatic alerts to receive notifications via email, Slack, Telegram, and more.
You can get started with Uptrace by downloading a DEB/RPM package or a pre-compiled Go binary.