How to propagate trace ID in Cloud Pub/Sub

wqwq
1 min readJan 23, 2024

To initiate Opentelemetry in a microservice environment, it is often necessary to propagate information like trace IDs, among others. I intend to document this methodology in this article.

Premise

Propagation is the method to move context. Context has a lot of data like trace ID. What we have to understand is this context is not equal to the context in Golang. Actually, we use the context in Golang to propagate. It is just useful in Golang to propagate the context.

Implementation

Overview

The ‘inject’ method in OpenTelemetry is commonly used to propagate context. Conversely, to retrieve context from a service that has received propagation, the ‘extract’ method in OpenTelemetry is typically employed. The process can be summarized as follows

Inject

By using context in Golang, we can inject trace ID into the context in Golang.

// global setting
otel.SetTextMapPropagator(propagation.TraceContext{})

// Inject
otel.GetTextMapPropagator().Inject(ctx, propagation.MapCarrier(msg.Attributes))

Extract

The trace ID is located in the attribute field of the PubMessage struct.

// Extract
ctx := otel.GetTextMapPropagator().Extract(ctx, propagation.MapCarrier(msg.Attributes))

--

--