home / skills / sickn33 / antigravity-awesome-skills / azure-monitor-opentelemetry-exporter-py

azure-monitor-opentelemetry-exporter-py skill

/skills/azure-monitor-opentelemetry-exporter-py

This skill helps you configure and export traces, metrics, and logs to Application Insights using Azure Monitor OpenTelemetry exporter.

npx playbooks add skill sickn33/antigravity-awesome-skills --skill azure-monitor-opentelemetry-exporter-py

Review the files below or copy the command above to add this skill to your agents.

Files (1)
SKILL.md
6.2 KB
---
name: azure-monitor-opentelemetry-exporter-py
description: |
  Azure Monitor OpenTelemetry Exporter for Python. Use for low-level OpenTelemetry export to Application Insights.
  Triggers: "azure-monitor-opentelemetry-exporter", "AzureMonitorTraceExporter", "AzureMonitorMetricExporter", "AzureMonitorLogExporter".
package: azure-monitor-opentelemetry-exporter
---

# Azure Monitor OpenTelemetry Exporter for Python

Low-level exporter for sending OpenTelemetry traces, metrics, and logs to Application Insights.

## Installation

```bash
pip install azure-monitor-opentelemetry-exporter
```

## Environment Variables

```bash
APPLICATIONINSIGHTS_CONNECTION_STRING=InstrumentationKey=xxx;IngestionEndpoint=https://xxx.in.applicationinsights.azure.com/
```

## When to Use

| Scenario | Use |
|----------|-----|
| Quick setup, auto-instrumentation | `azure-monitor-opentelemetry` (distro) |
| Custom OpenTelemetry pipeline | `azure-monitor-opentelemetry-exporter` (this) |
| Fine-grained control over telemetry | `azure-monitor-opentelemetry-exporter` (this) |

## Trace Exporter

```python
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter

# Create exporter
exporter = AzureMonitorTraceExporter(
    connection_string="InstrumentationKey=xxx;..."
)

# Configure tracer provider
trace.set_tracer_provider(TracerProvider())
trace.get_tracer_provider().add_span_processor(
    BatchSpanProcessor(exporter)
)

# Use tracer
tracer = trace.get_tracer(__name__)
with tracer.start_as_current_span("my-span"):
    print("Hello, World!")
```

## Metric Exporter

```python
from opentelemetry import metrics
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
from azure.monitor.opentelemetry.exporter import AzureMonitorMetricExporter

# Create exporter
exporter = AzureMonitorMetricExporter(
    connection_string="InstrumentationKey=xxx;..."
)

# Configure meter provider
reader = PeriodicExportingMetricReader(exporter, export_interval_millis=60000)
metrics.set_meter_provider(MeterProvider(metric_readers=[reader]))

# Use meter
meter = metrics.get_meter(__name__)
counter = meter.create_counter("requests_total")
counter.add(1, {"route": "/api/users"})
```

## Log Exporter

```python
import logging
from opentelemetry._logs import set_logger_provider
from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler
from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
from azure.monitor.opentelemetry.exporter import AzureMonitorLogExporter

# Create exporter
exporter = AzureMonitorLogExporter(
    connection_string="InstrumentationKey=xxx;..."
)

# Configure logger provider
logger_provider = LoggerProvider()
logger_provider.add_log_record_processor(BatchLogRecordProcessor(exporter))
set_logger_provider(logger_provider)

# Add handler to Python logging
handler = LoggingHandler(level=logging.INFO, logger_provider=logger_provider)
logging.getLogger().addHandler(handler)

# Use logging
logger = logging.getLogger(__name__)
logger.info("This will be sent to Application Insights")
```

## From Environment Variable

Exporters read `APPLICATIONINSIGHTS_CONNECTION_STRING` automatically:

```python
from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter

# Connection string from environment
exporter = AzureMonitorTraceExporter()
```

## Azure AD Authentication

```python
from azure.identity import DefaultAzureCredential
from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter

exporter = AzureMonitorTraceExporter(
    credential=DefaultAzureCredential()
)
```

## Sampling

Use `ApplicationInsightsSampler` for consistent sampling:

```python
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.sampling import ParentBasedTraceIdRatio
from azure.monitor.opentelemetry.exporter import ApplicationInsightsSampler

# Sample 10% of traces
sampler = ApplicationInsightsSampler(sampling_ratio=0.1)

trace.set_tracer_provider(TracerProvider(sampler=sampler))
```

## Offline Storage

Configure offline storage for retry:

```python
from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter

exporter = AzureMonitorTraceExporter(
    connection_string="...",
    storage_directory="/path/to/storage",  # Custom storage path
    disable_offline_storage=False  # Enable retry (default)
)
```

## Disable Offline Storage

```python
exporter = AzureMonitorTraceExporter(
    connection_string="...",
    disable_offline_storage=True  # No retry on failure
)
```

## Sovereign Clouds

```python
from azure.identity import AzureAuthorityHosts, DefaultAzureCredential
from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter

# Azure Government
credential = DefaultAzureCredential(authority=AzureAuthorityHosts.AZURE_GOVERNMENT)
exporter = AzureMonitorTraceExporter(
    connection_string="InstrumentationKey=xxx;IngestionEndpoint=https://xxx.in.applicationinsights.azure.us/",
    credential=credential
)
```

## Exporter Types

| Exporter | Telemetry Type | Application Insights Table |
|----------|---------------|---------------------------|
| `AzureMonitorTraceExporter` | Traces/Spans | requests, dependencies, exceptions |
| `AzureMonitorMetricExporter` | Metrics | customMetrics, performanceCounters |
| `AzureMonitorLogExporter` | Logs | traces, customEvents |

## Configuration Options

| Parameter | Description | Default |
|-----------|-------------|---------|
| `connection_string` | Application Insights connection string | From env var |
| `credential` | Azure credential for AAD auth | None |
| `disable_offline_storage` | Disable retry storage | False |
| `storage_directory` | Custom storage path | Temp directory |

## Best Practices

1. **Use BatchSpanProcessor** for production (not SimpleSpanProcessor)
2. **Use ApplicationInsightsSampler** for consistent sampling across services
3. **Enable offline storage** for reliability in production
4. **Use AAD authentication** instead of instrumentation keys
5. **Set export intervals** appropriate for your workload
6. **Use the distro** (`azure-monitor-opentelemetry`) unless you need custom pipelines

Overview

This skill provides a low-level OpenTelemetry exporter for Python that sends traces, metrics, and logs to Azure Application Insights. It supports direct configuration via connection string, Azure AD credentials, and optional offline storage for reliable delivery. Use it when you need fine-grained control over an OpenTelemetry pipeline rather than automatic distro instrumentation.

How this skill works

The exporter implements Trace, Metric, and Log exporters compatible with OpenTelemetry SDKs and can be wired into BatchSpanProcessor, PeriodicExportingMetricReader, and BatchLogRecordProcessor. It reads the Application Insights connection string from an environment variable by default and also accepts azure-identity credentials for AAD authentication. Features include sampling support, offline retry storage, export interval configuration, and sovereign cloud endpoints.

When to use it

  • You need a custom OpenTelemetry pipeline instead of automatic distro instrumentation
  • You want to send traces, metrics, and logs directly to Application Insights tables
  • You require Azure AD authentication rather than instrumentation keys
  • You need offline storage or retry behavior for intermittent network failures
  • You want consistent sampling across services using ApplicationInsightsSampler

Best practices

  • Use BatchSpanProcessor for production workloads, not SimpleSpanProcessor
  • Prefer AAD credentials (DefaultAzureCredential) over static instrumentation keys for improved security
  • Enable offline storage for reliable retry and configure a dedicated storage_directory
  • Apply ApplicationInsightsSampler for consistent sampling ratios across services
  • Tune metric export intervals to balance latency and ingestion cost

Example use cases

  • Integrate custom trace spans into an existing OpenTelemetry TracerProvider and export to Application Insights
  • Export application metrics with PeriodicExportingMetricReader to Application Insights customMetrics
  • Route Python logging through OpenTelemetry Log SDK and send records to Application Insights traces or customEvents
  • Deploy in sovereign cloud or government environments using custom ingestion endpoints and AzureAuthorityHosts
  • Enable offline storage on edge or intermittent-connectivity services to buffer telemetry and retry delivery

FAQ

How does the exporter get the connection string?

By default it reads APPLICATIONINSIGHTS_CONNECTION_STRING from the environment; you can also pass connection_string explicitly to the exporter constructor.

Can I use Azure AD instead of an instrumentation key?

Yes. Pass an azure.identity credential (for example DefaultAzureCredential) to the exporter to authenticate via AAD and avoid using instrumentation keys.