Azure Resource Detector for OpenTelemetry

0.1.5 · active · verified Thu Apr 09

The `opentelemetry-resource-detector-azure` library provides an OpenTelemetry resource detector that automatically gathers Azure-specific metadata (e.g., cloud provider, region, resource ID) and adds it as attributes to exported telemetry data. It's part of the OpenTelemetry Python Contrib repository, currently at version 0.1.5, and follows the release cadence of the wider OpenTelemetry Python project, often receiving updates alongside core SDK releases.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the `AzureResourceDetector` and integrate it with the OpenTelemetry Python SDK. The detector automatically enriches telemetry with Azure-specific attributes. It requires Azure credentials (via environment variables or Managed Identity) to function correctly. The output on the console will include the automatically detected Azure resource attributes.

import os
from opentelemetry import trace
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import ConsoleSpanExporter, SimpleSpanProcessor
from opentelemetry.sdk.extension.resource.azure import AzureResourceDetector

# Configure Azure credentials via environment variables for testing purposes
# In a real Azure environment, Managed Identity is often preferred.
# For local testing, ensure these are set:
# os.environ['AZURE_CLIENT_ID'] = os.environ.get('AZURE_CLIENT_ID', '')
# os.environ['AZURE_TENANT_ID'] = os.environ.get('AZURE_TENANT_ID', '')
# os.environ['AZURE_CLIENT_SECRET'] = os.environ.get('AZURE_CLIENT_SECRET', '')

# Instantiate and register the Azure Resource Detector
# The detector makes network calls to Azure APIs, potentially adding startup latency.
# Resource attributes are collected at SDK initialization and are immutable.
resource = Resource.create([AzureResourceDetector()])

# Set up a TracerProvider with the detected resource
provider = TracerProvider(resource=resource)
processor = SimpleSpanProcessor(ConsoleSpanExporter())
provider.add_span_processor(processor)
trace.set_tracer_provider(provider)

# Get a tracer and create a simple span
tracer = trace.get_tracer(__name__)

with tracer.start_as_current_span("azure-resource-test-span") as span:
    span.set_attribute("my.custom.attribute", "hello")
    print("Span created. Check console for resource attributes from Azure.")

# Ensure all spans are processed and exported on shutdown
provider.shutdown()

view raw JSON →