Google Cloud Trace

1.19.0 · active · verified Thu Apr 09

The Google Cloud Trace API client library for Python. This library primarily provides an OpenTelemetry Span Exporter to send traces from Python applications to Google Cloud Trace. It is part of the larger `google-cloud-python` monorepo, with frequent updates across various Google Cloud services. The current version is 1.19.0.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up OpenTelemetry with `google-cloud-trace` to send traces to Google Cloud Trace. It configures a `TracerProvider` with a service resource, registers the `CloudTraceSpanExporter`, and then creates a root span with a child span. Remember to replace 'your-gcp-project-id' with your actual GCP project ID or ensure the `GOOGLE_CLOUD_PROJECT` environment variable is set.

import os
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
from opentelemetry.sdk.resources import Resource
from google.cloud.trace_v2.exporters import CloudTraceSpanExporter

# Set the Google Cloud project ID (can also be picked up from GOOGLE_CLOUD_PROJECT environment variable)
project_id = os.environ.get('GOOGLE_CLOUD_PROJECT', 'your-gcp-project-id')

# 1. Configure OpenTelemetry TracerProvider with a Resource (important for service naming in Trace)
resource = Resource.create({"service.name": "my-python-app", "service.version": "1.0.0"})
provider = TracerProvider(resource=resource)

# 2. Add the Google Cloud Trace Span Exporter
# You can specify project_id here or rely on default credentials if GOOGLE_CLOUD_PROJECT is set
cloud_trace_exporter = CloudTraceSpanExporter(project_id=project_id)
provider.add_span_processor(SimpleSpanProcessor(cloud_trace_exporter))

# 3. Set the global tracer provider
trace.set_tracer_provider(provider)

# 4. Get a tracer and create spans
tracer = trace.get_tracer(__name__)

with tracer.start_as_current_span('my-application-span'):
    print('Doing some work...')
    with tracer.start_as_current_span('child-operation') as child_span:
        child_span.set_attribute('custom_key', 'custom_value')
        print('Doing child work...')
    print('Work finished.')

# In a real application, spans are typically sent asynchronously.
# For a short script, ensure exporter has time to send or explicitly shut down.
# provider.shutdown() # Uncomment in production to ensure all spans are exported before process exits.

view raw JSON →