CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-opencensus-ext-azure

OpenCensus Azure Monitor Exporter for telemetry data (logs, metrics, and traces) to Azure Monitor.

Pending
Overview
Eval results
Files

trace-export.mddocs/

Trace Export

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.

Capabilities

Azure Exporter

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
        """

Basic Usage Example

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 here

Advanced Usage with HTTP Instrumentation

from 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"}

Span Type Mapping

The Azure exporter automatically maps OpenCensus spans to Azure Monitor telemetry types:

Server Spans (SpanKind.SERVER)

Server spans become Request telemetry in Azure Monitor:

  • Name: HTTP method + route (e.g., "GET /api/orders")
  • Duration: Span start to end time
  • Success: Based on HTTP status code or span status
  • Properties: All span attributes except HTTP-specific ones
  • URL: From http.url attribute
  • Response Code: From http.status_code attribute

Client Spans (SpanKind.CLIENT)

Client spans become RemoteDependency telemetry:

  • Name: HTTP method + path (e.g., "POST /validate")
  • Type: Component type (e.g., "HTTP", "SQL")
  • Target: Host and port from URL
  • Data: Full URL for HTTP calls
  • Success: Based on HTTP status code or span status
  • Properties: All span attributes except HTTP-specific ones

Internal Spans

Internal spans become RemoteDependency telemetry with type "INPROC":

  • Name: Span name
  • Type: "INPROC"
  • Success: Always true unless span has error status
  • Properties: All span attributes

Exception Handling

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 trace

HTTP Attribute Mapping

The exporter recognizes these OpenCensus HTTP attributes:

  • http.method → Request/dependency name prefix
  • http.url → Request URL or dependency data
  • http.route → Request name (preferred over path)
  • http.path → Request name (fallback)
  • http.status_code → Response code and success determination

Correlation and Context

The exporter automatically handles distributed tracing correlation:

  • Operation ID: Maps to OpenCensus trace ID
  • Parent ID: Maps to parent span ID
  • Operation Name: Derived from HTTP route for server spans
  • Links: W3C trace context links for cross-service correlation

Configuration Options

Trace exporter supports these specific options in addition to common options:

  • grace_period (float): Time to wait for clean shutdown (default: 5.0 seconds)
  • Automatic registration with atexit for graceful shutdown

Performance Considerations

  • Asynchronous Export: Spans are exported asynchronously to avoid blocking application
  • Batching: Multiple spans are sent in single HTTP requests
  • Local Storage: Optional persistence prevents data loss during connectivity issues
  • Sampling: Use OpenCensus sampling to control telemetry volume

Integration Examples

Django Integration

from 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'
            }
        }
    }
}

FastAPI Integration

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 response

Install with Tessl CLI

npx tessl i tessl/pypi-opencensus-ext-azure

docs

configuration.md

index.md

log-export.md

metrics-export.md

trace-export.md

tile.json