Google Cloud Resource Detector for OpenTelemetry

1.11.0a0 · active · verified Mon Apr 06

The `opentelemetry-resourcedetector-gcp` library provides support for automatically detecting resource information for applications running on Google Cloud Platform services such as Google Compute Engine (GCE), Google Kubernetes Engine (GKE), Cloud Run, and Cloud Functions. It integrates with the OpenTelemetry Python SDK to enrich telemetry data (traces, metrics, logs) with environment-specific metadata. The current version is 1.11.0a0, with pre-releases happening frequently, indicating active development.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the OpenTelemetry `TracerProvider` with `GoogleCloudResourceDetector`. The detector runs automatically when `get_aggregated_resources` is called, querying the GCP metadata server to identify the environment and populate standard OpenTelemetry resource attributes. Ensure the code runs within a Google Cloud environment (e.g., GCE, GKE, Cloud Run) for effective detection. The example then creates a basic span, which will inherit the detected resource attributes.

import os
from opentelemetry import trace
from opentelemetry.sdk.resources import get_aggregated_resources
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import ConsoleSpanExporter, SimpleSpanProcessor
from opentelemetry.resourcedetector.gcp_resource_detector import GoogleCloudResourceDetector

# The detector automatically queries the GCP metadata server.
# Ensure your application is running in a GCP environment for full detection.
resource = get_aggregated_resources(
    [GoogleCloudResourceDetector(raise_on_error=True)]
)

# Create a TracerProvider with the detected resource
tracer_provider = TracerProvider(resource=resource)
trace.set_tracer_provider(tracer_provider)

# For demonstration, export to console. In a real application, use a GCP exporter.
span_processor = SimpleSpanProcessor(ConsoleSpanExporter())
tracer_provider.add_span_processor(span_processor)

tracer = trace.get_tracer(__name__)

with tracer.start_as_current_span("my-gcp-operation") as span:
    span.set_attribute("custom.attribute", "value")
    print(f"Span created with detected resource attributes: {resource.attributes}")
    # In a real application, this would be exported to Cloud Trace or another backend

print("Resource detection example complete.")

view raw JSON →