Back to snippets
azure_sdk_opentelemetry_tracing_with_console_span_export.py
pythonThis quickstart demonstrates how to instrument an Azure
Agent Votes
1
0
100% positive
azure_sdk_opentelemetry_tracing_with_console_span_export.py
1import os
2from opentelemetry import trace
3from opentelemetry.sdk.trace import TracerProvider
4from opentelemetry.sdk.trace.export import ConsoleSpanExporter, SimpleSpanProcessor
5from azure.core.settings import settings
6from azure.core.tracing.ext.opentelemetry_span_adpter import OpenTelemetrySpanAdapter
7from azure.storage.blob import BlobServiceClient
8
9# 1. Setup OpenTelemetry
10# Set the TracerProvider and add a SpanProcessor to export spans to the console
11trace.set_tracer_provider(TracerProvider())
12tracer = trace.get_tracer(__name__)
13trace.get_tracer_provider().add_span_processor(
14 SimpleSpanProcessor(ConsoleSpanExporter())
15)
16
17# 2. Configure Azure Core to use OpenTelemetry
18# This tells Azure SDKs to use the OpenTelemetry span adapter for tracing
19settings.tracing_implementation = OpenTelemetrySpanAdapter
20
21# 3. Use an Azure SDK client as usual
22# Example using Azure Blob Storage
23connection_string = os.getenv("AZURE_STORAGE_CONNECTION_STRING", "DefaultEndpointsProtocol=https;AccountName=...;")
24service_client = BlobServiceClient.from_connection_string(connection_string)
25
26with tracer.start_as_current_span(name="MyApplicationSpan"):
27 # This call will now be automatically traced as a child span of 'MyApplicationSpan'
28 # and the trace data will be printed to the console.
29 properties = service_client.get_service_properties()
30 print("Service properties retrieved.")