azure-monitor-opentelemetry-exporter-py
microsoft/skills
Exporta trazas, métricas y registros de OpenTelemetry a Azure Application Insights utilizando Python.
...Expandir todoExportador de OpenTelemetry de Azure Monitor para Python
Exportador de bajo nivel para enviar trazas, métricas y registros de OpenTelemetry a Application Insights.
Instalación
pip install azure-monitor-opentelemetry-exporter
Variables de entorno
APPLICATIONINSIGHTS_CONNECTION_STRING=InstrumentationKey=xxx;IngestionEndpoint=https://xxx.in.applicationinsights.azure.com/ # Obligatorio para todos los métodos de autenticación
AZURE_TOKEN_CREDENTIALS=prod # Obligatorio solo si se usa DefaultAzureCredential en producción
🔑 Autenticación y ciclo de vida: Estos exportadores toman una cadena de conexión por diseño, pero para la ingesta autenticada con AAD (donde esté soportado), se prefiere
DefaultAzureCredentialmediante el parámetrocredential=; consulte la sección de Autenticación de Azure AD. Cualquier cliente del SDK de Azure que cree junto con el exportador debe envolverse en bloqueswith/async with(y las credenciales asíncronas deazure.identity.aiotambién).
Cuándo usarlo
| Escenario | Uso |
|---|---|
| Configuración rápida, instrumentación automática | `azure-monitor-opentelemetry` (distribución) |
| Canalización de OpenTelemetry personalizada | `azure-monitor-opentelemetry-exporter` (este) |
| Control fino sobre la telemetría | `azure-monitor-opentelemetry-exporter` (este) |
Exportador de trazas
from azure.identity import DefaultAzureCredential
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter
# Lee APPLICATIONINSIGHTS_CONNECTION_STRING del entorno para identificar el recurso;
# DefaultAzureCredential autentica la ingesta a través de Microsoft Entra ID.
exporter = AzureMonitorTraceExporter(
credential=DefaultAzureCredential(),
)
# Configurar el proveedor de trazadores
trace.set_tracer_provider(TracerProvider())
trace.get_tracer_provider().add_span_processor(
BatchSpanProcessor(exporter)
)
# Usar el trazador
tracer = trace.get_tracer(__name__)
with tracer.start_as_current_span("my-span"):
print("Hello, World!")
Exportador de métricas
from azure.identity import DefaultAzureCredential
from opentelemetry import metrics
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
from azure.monitor.opentelemetry.exporter import AzureMonitorMetricExporter
# Lee APPLICATIONINSIGHTS_CONNECTION_STRING del entorno; ingesta autenticada con AAD a través de DefaultAzureCredential.
exporter = AzureMonitorMetricExporter(
credential=DefaultAzureCredential(),
)
# Configurar el proveedor de medidores
reader = PeriodicExportingMetricReader(exporter, export_interval_millis=60000)
metrics.set_meter_provider(MeterProvider(metric_readers=[reader]))
# Usar el medidor
meter = metrics.get_meter(__name__)
counter = meter.create_counter("requests_total")
counter.add(1, {"route": "/api/users"})
Exportador de registros
import logging
from azure.identity import DefaultAzureCredential
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
# Lee APPLICATIONINSIGHTS_CONNECTION_STRING del entorno; ingesta autenticada con AAD a través de DefaultAzureCredential.
exporter = AzureMonitorLogExporter(
credential=DefaultAzureCredential(),
)
# Configurar el proveedor de registradores
logger_provider = LoggerProvider()
logger_provider.add_log_record_processor(BatchLogRecordProcessor(exporter))
set_logger_provider(logger_provider)
# Añadir controlador al registro de Python
handler = LoggingHandler(level=logging.INFO, logger_provider=logger_provider)
logging.getLogger().addHandler(handler)
# Usar el registro
logger = logging.getLogger(__name__)
logger.info("This will be sent to Application Insights")
Desde variable de entorno
Los exportadores leen APPLICATIONINSIGHTS_CONNECTION_STRING automáticamente:
from azure.identity import DefaultAzureCredential
from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter
# Cadena de conexión del entorno; ingesta autenticada con AAD a través de DefaultAzureCredential.
exporter = AzureMonitorTraceExporter(
credential=DefaultAzureCredential(),
)
Autenticación de Azure AD
from azure.identity import DefaultAzureCredential, ManagedIdentityCredential
from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter
# Desarrollo local: DefaultAzureCredential. Producción: establecer AZURE_TOKEN_CREDENTIALS=prod o AZURE_TOKEN_CREDENTIALS=<credencial_específica>
credential = DefaultAzureCredential(require_envvar=True)
# O usar una credencial específica directamente en producción:
# Consulte https://learn.microsoft.com/python/api/overview/azure/identity-readme?view=azure-python#credential-classes
# credential = ManagedIdentityCredential()
exporter = AzureMonitorTraceExporter(
credential=credential
)
</credencial_específica>Muestreo
Utilice ApplicationInsightsSampler para un muestreo coherente:
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.sampling import ParentBasedTraceIdRatio
from azure.monitor.opentelemetry.exporter import ApplicationInsightsSampler
# Muestrear el 10 % de las trazas
sampler = ApplicationInsightsSampler(sampling_ratio=0.1)
trace.set_tracer_provider(TracerProvider(sampler=sampler))
Almacenamiento fuera de línea
Configure el almacenamiento fuera de línea para reintentos:
from azure.identity import DefaultAzureCredential
from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter
exporter = AzureMonitorTraceExporter(
credential=DefaultAzureCredential(),
storage_directory="/path/to/storage", # Ruta de almacenamiento personalizada
disable_offline_storage=False # Habilitar reintentos (predeterminado)
)
Desactivar almacenamiento fuera de línea
exporter = AzureMonitorTraceExporter(
credential=DefaultAzureCredential(),
disable_offline_storage=True # Sin reintentos en caso de fallo
)
Nubes soberanas
from azure.identity import AzureAuthorityHosts, DefaultAzureCredential
from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter
# Gobierno de Azure
credential = DefaultAzureCredential(authority=AzureAuthorityHosts.AZURE_GOVERNMENT)
exporter = AzureMonitorTraceExporter(
connection_string="InstrumentationKey=xxx;IngestionEndpoint=https://xxx.in.applicationinsights.azure.us/",
credential=credential
)
Tipos de exportador
| Exportador | Tipo de telemetría | Tabla de Application Insights |
|---|---|---|
| `AzureMonitorTraceExporter` | Trazas/Intervalos | solicitudes, dependencias, excepciones |
| `AzureMonitorMetricExporter` | Métricas | customMetrics, performanceCounters |
| `AzureMonitorLogExporter` | Registros | trazas, customEvents |
Opciones de configuración
| Parámetro | Descripción | Valor predeterminado |
|---|---|---|
| `connection_string` | Cadena de conexión de Application Insights | Desde variable de entorno |
| `credential` | Credencial de Azure para autenticación AAD | Ninguna |
| `disable_offline_storage` | Desactivar almacenamiento de reintentos | Falso |
| `storage_directory` | Ruta de almacenamiento personalizada | Directorio temporal |
Mejores prácticas
- Elija síncrono O asíncrono y mantenga la coherencia. No mezcle clientes síncronos
azure.xxxcon clientes asíncronosazure.xxx.aioen la misma ruta de llamada. Elija un modo por módulo. - Vacíe y apague los proveedores al finalizar el proceso. Llame a las API de apagado/vaciado (p. ej.,
tracer_provider.shutdown(),meter_provider.shutdown(),logger_provider.shutdown()) al finalizar el proceso para vaciar la telemetría antes de que termine el proceso. - Utilice BatchSpanProcessor para producción (no SimpleSpanProcessor)
- Utilice ApplicationInsightsSampler para un muestreo coherente entre servicios
- Habilite el almacenamiento fuera de línea para mayor fiabilidad en producción
- Utilice la autenticación de Microsoft Entra en lugar de las claves de instrumentación
- Establezca intervalos de exportación adecuados para su carga de trabajo
- Utilice la distribución (
azure-monitor-opentelemetry) a menos que necesite canalizaciones personalizadas
---
name: azure-monitor-opentelemetry-exporter-py
description: Export OpenTelemetry traces, metrics, and logs to Azure Application Insights using Python.
license: MIT
---
# 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/ # Required for all auth methods
AZURE_TOKEN_CREDENTIALS=prod # Required only if DefaultAzureCredential is used in production
```
> **🔑 Auth & lifecycle:** These exporters take a connection string by design, but for *AAD-authenticated ingestion* (where supported) prefer `DefaultAzureCredential` via the `credential=` parameter — see the [Azure AD Authentication](#azure-ad-authentication) section. Any Azure SDK clients you create alongside the exporter should be wrapped in `with`/`async with` blocks (and async credentials from `azure.identity.aio` likewise).
## 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 azure.identity import DefaultAzureCredential
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter
# Reads APPLICATIONINSIGHTS_CONNECTION_STRING from env to identify the resource;
# DefaultAzureCredential authenticates ingestion via Microsoft Entra ID.
exporter = AzureMonitorTraceExporter(
credential=DefaultAzureCredential(),
)
# 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 azure.identity import DefaultAzureCredential
from opentelemetry import metrics
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
from azure.monitor.opentelemetry.exporter import AzureMonitorMetricExporter
# Reads APPLICATIONINSIGHTS_CONNECTION_STRING from env; AAD-authenticated ingestion via DefaultAzureCredential.
exporter = AzureMonitorMetricExporter(
credential=DefaultAzureCredential(),
)
# 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 azure.identity import DefaultAzureCredential
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
# Reads APPLICATIONINSIGHTS_CONNECTION_STRING from env; AAD-authenticated ingestion via DefaultAzureCredential.
exporter = AzureMonitorLogExporter(
credential=DefaultAzureCredential(),
)
# 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.identity import DefaultAzureCredential
from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter
# Connection string from environment; AAD-authenticated ingestion via DefaultAzureCredential.
exporter = AzureMonitorTraceExporter(
credential=DefaultAzureCredential(),
)
```
## Azure AD Authentication
```python
from azure.identity import DefaultAzureCredential, ManagedIdentityCredential
from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter
# Local dev: DefaultAzureCredential. Production: set AZURE_TOKEN_CREDENTIALS=prod or AZURE_TOKEN_CREDENTIALS=<specific_credential>
credential = DefaultAzureCredential(require_envvar=True)
# Or use a specific credential directly in production:
# See https://learn.microsoft.com/python/api/overview/azure/identity-readme?view=azure-python#credential-classes
# credential = ManagedIdentityCredential()
exporter = AzureMonitorTraceExporter(
credential=credential
)
```
## 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.identity import DefaultAzureCredential
from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter
exporter = AzureMonitorTraceExporter(
credential=DefaultAzureCredential(),
storage_directory="/path/to/storage", # Custom storage path
disable_offline_storage=False # Enable retry (default)
)
```
## Disable Offline Storage
```python
exporter = AzureMonitorTraceExporter(
credential=DefaultAzureCredential(),
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. **Pick sync OR async and stay consistent.** Do not mix `azure.xxx` sync clients with `azure.xxx.aio` async clients in the same call path. Choose one mode per module.
2. **Flush and shut down providers at process exit.** Call the shutdown/flush APIs (e.g. `tracer_provider.shutdown()`, `meter_provider.shutdown()`, `logger_provider.shutdown()`) at process exit to flush telemetry before the process terminates.
3. **Use BatchSpanProcessor** for production (not SimpleSpanProcessor)
4. **Use ApplicationInsightsSampler** for consistent sampling across services
5. **Enable offline storage** for reliability in production
6. **Use Microsoft Entra authentication** instead of instrumentation keys
7. **Set export intervals** appropriate for your workload
8. **Use the distro** (`azure-monitor-opentelemetry`) unless you need custom pipelines
Todos los archivos
0 archivosInstalar azure-monitor-opentelemetry-exporter-py
Descarga y extrae los archivos de habilidades en tu directorio .claude/skills/.
Descargar ZIPClona el repositorio y copia los archivos de la habilidad a tu proyecto.
git clone https://github.com/microsoft/skills/tree/main/.github/plugins/azure-sdk-python/skills/azure-monitor-opentelemetry-exporter-py # Copy SKILL.md to your .claude/skills/ directory
Copiar





Hogar
