OpenCensus Azure Monitor Exporter for telemetry data (logs, metrics, and traces) to Azure Monitor.
—
Distributed tracing export that sends OpenCensus span data to Azure Monitor for request tracking, dependency mapping, and performance analysis. The trace exporter enables comprehensive application performance monitoring through distributed tracing capabilities.
Exports OpenCensus trace spans to Azure Monitor, automatically detecting request vs. dependency spans and transforming them into appropriate Azure Monitor telemetry types.
class AzureExporter(BaseExporter, TransportMixin, ProcessorMixin):
"""
An exporter that sends traces to Microsoft Azure Monitor.
Automatically converts OpenCensus span data to Azure Monitor request
and dependency telemetry, including HTTP-specific attributes and
exception handling.
"""
def __init__(self, **options):
"""
Initialize the Azure trace exporter.
Args:
**options: Configuration options including connection_string,
instrumentation_key, export_interval, etc.
"""
def export(self, span_datas):
"""
Export span data items (inherited from BaseExporter).
Queues span data for asynchronous export to Azure Monitor.
Args:
span_datas (list): List of SpanData objects to queue for export
"""
def span_data_to_envelope(self, span_data):
"""
Convert span data to Azure Monitor telemetry envelope(s).
Args:
span_data (SpanData): OpenCensus span data object
Yields:
Envelope: Azure Monitor telemetry envelope(s)
"""
def emit(self, batch, event=None):
"""
Process and transmit a batch of spans.
Args:
batch (list): List of span data objects
event (QueueEvent, optional): Synchronization event
"""
def add_telemetry_processor(self, processor):
"""
Add a telemetry processor for filtering/modifying telemetry.
Args:
processor (callable): Function that takes and returns envelope
"""from opencensus.trace.tracer import Tracer
from opencensus.ext.azure.trace_exporter import AzureExporter
# Configure the exporter
exporter = AzureExporter(
connection_string="InstrumentationKey=your-instrumentation-key"
)
# Create tracer with Azure exporter
tracer = Tracer(exporter=exporter)
# Trace a simple operation
with tracer.span(name="process_order") as span:
span.add_attribute("order_id", "12345")
span.add_attribute("customer_id", "67890")
# Nested span for database operation
with tracer.span(name="database_query") as db_span:
db_span.add_attribute("query", "SELECT * FROM orders")
db_span.add_attribute("duration_ms", 45)
# Database operation here
# HTTP dependency span
with tracer.span(name="external_api_call") as api_span:
api_span.add_attribute("http.method", "POST")
api_span.add_attribute("http.url", "https://api.example.com/validate")
api_span.add_attribute("http.status_code", 200)
# API call herefrom opencensus.trace.tracer import Tracer
from opencensus.ext.azure.trace_exporter import AzureExporter
from opencensus.ext.requests.trace import RequestsInstrumentor
from opencensus.ext.flask.flask_middleware import FlaskMiddleware
# Configure exporter
exporter = AzureExporter(
connection_string="InstrumentationKey=your-instrumentation-key",
export_interval=10.0, # Export every 10 seconds
max_batch_size=50 # Batch up to 50 spans
)
# Flask application with automatic request tracing
app = Flask(__name__)
middleware = FlaskMiddleware(app, exporter=exporter)
# Automatic HTTP client tracing
RequestsInstrumentor().instrument()
@app.route('/api/orders/<order_id>')
def get_order(order_id):
# This request is automatically traced as a SERVER span
# Any requests.get() calls are traced as CLIENT spans
# Manual span for business logic
tracer = middleware.tracer
with tracer.span(name="order_processing") as span:
span.add_attribute("order_id", order_id)
# This HTTP call is automatically traced
response = requests.get(f"https://api.inventory.com/check/{order_id}")
return {"order": order_id, "status": "processed"}The Azure exporter automatically maps OpenCensus spans to Azure Monitor telemetry types:
Server spans become Request telemetry in Azure Monitor:
http.url attributehttp.status_code attributeClient spans become RemoteDependency telemetry:
Internal spans become RemoteDependency telemetry with type "INPROC":
Server spans with exceptions automatically generate both Request and Exception telemetry:
# Example: Exception in server span
with tracer.span(name="risky_operation") as span:
span.add_attribute("operation_type", "data_processing")
try:
# Risky operation
result = process_data()
except ValueError as e:
# Add exception details to span
span.add_attribute("error.name", "ValueError")
span.add_attribute("error.message", str(e))
span.add_attribute("stacktrace", traceback.format_exc())
span.set_status(Status(code=StatusCode.ERROR, message=str(e)))
raise
# This generates:
# 1. Request telemetry for the operation
# 2. Exception telemetry with stack traceThe exporter recognizes these OpenCensus HTTP attributes:
http.method → Request/dependency name prefixhttp.url → Request URL or dependency datahttp.route → Request name (preferred over path)http.path → Request name (fallback)http.status_code → Response code and success determinationThe exporter automatically handles distributed tracing correlation:
Trace exporter supports these specific options in addition to common options:
grace_period (float): Time to wait for clean shutdown (default: 5.0 seconds)atexit for graceful shutdownfrom opencensus.ext.django.middleware import OpencensusMiddleware
from opencensus.ext.azure.trace_exporter import AzureExporter
MIDDLEWARE = [
'opencensus.ext.django.middleware.OpencensusMiddleware',
# ... other middleware
]
OPENCENSUS = {
'TRACE': {
'EXPORTER': {
'CLASS_NAME': 'opencensus.ext.azure.trace_exporter.AzureExporter',
'OPTIONS': {
'connection_string': 'InstrumentationKey=your-key-here'
}
}
}
}from fastapi import FastAPI
from opencensus.ext.azure.trace_exporter import AzureExporter
from opencensus.trace.tracer import Tracer
from opencensus.trace.samplers import ProbabilitySampler
app = FastAPI()
# Configure tracer
exporter = AzureExporter(connection_string="InstrumentationKey=your-key-here")
tracer = Tracer(exporter=exporter, sampler=ProbabilitySampler(rate=1.0))
@app.middleware("http")
async def trace_requests(request, call_next):
with tracer.span(name=f"{request.method} {request.url.path}") as span:
span.add_attribute("http.method", request.method)
span.add_attribute("http.url", str(request.url))
response = await call_next(request)
span.add_attribute("http.status_code", response.status_code)
return responseInstall with Tessl CLI
npx tessl i tessl/pypi-opencensus-ext-azure