Google Cloud Propagator for OpenTelemetry

1.11.0 · active · verified Sat Apr 11

The `opentelemetry-propagator-gcp` library provides a TextMapPropagator for OpenTelemetry that handles the Google Cloud Trace context header (`x-cloud-trace-context`). It allows OpenTelemetry traces to be linked with existing traces in Google Cloud, facilitating interoperability. This library is part of the `opentelemetry-operations-python` project, is actively maintained, and follows a regular release cadence, typically monthly or bi-monthly, aligned with other OpenTelemetry SDK updates.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to register the `CloudTracePropagator` and then use the global `TextMapPropagator` to extract trace context from incoming headers and inject it into outgoing headers. This is crucial for maintaining trace continuity across services within and outside Google Cloud.

from opentelemetry import propagators
from opentelemetry.propagators.gcp import CloudTracePropagator
from opentelemetry.propagators.composite import CompositePropagator
from opentelemetry.trace import set_tracer_provider, get_tracer_provider
from opentelemetry.sdk.trace import TracerProvider

# 1. Set a TracerProvider (required for context to be active for injection)
set_tracer_provider(TracerProvider())

# 2. Register the CloudTracePropagator globally
#    Often combined with W3CTraceContextPropagator for broader compatibility.
propagators.set_global_textmap_propagator(
    CompositePropagator([
        CloudTracePropagator(),
        # Add W3CTraceContextPropagator() here if you also need W3C Trace Context
    ])
)

# --- Example: Extracting context from an incoming request ---
# Simulate an incoming request with 'x-cloud-trace-context' header
incoming_headers = {
    "x-cloud-trace-context": "105445aa78532f73a8123c72b2600000/0000000000000001;o=1"
}

# Extract the context using the globally registered propagator
context = propagators.get_global_textmap_propagator().extract(incoming_headers)

print(f"Extracted context from incoming headers: {context}")

# --- Example: Injecting context for an outgoing request ---
outgoing_headers = {}

# Create an active span to ensure there's a trace context to inject
tracer = get_tracer_provider().get_tracer(__name__)
with tracer.start_as_current_span("my-root-span"):
    # Inject the current trace context into outgoing headers
    propagators.get_global_textmap_propagator().inject(outgoing_headers)

print(f"Injected headers for outgoing request: {outgoing_headers}")

# Expected output for outgoing_headers will contain 'x-cloud-trace-context'

view raw JSON →