opção
LarLar Skill DevOps e CI/CD azure-monitor-opentelemetry-exporter-py

azure-monitor-opentelemetry-exporter-py

microsoft/skills microsoft/skills

Exporte rastros, métricas e registros do OpenTelemetry para o Azure Application Insights usando Python.

...Expandir tudo
0
Tempo atualizado 19 de Setembro de 2026

Exportador OpenTelemetry do Azure Monitor para Python

Exportador de baixo nível para enviar rastros, métricas e registros do OpenTelemetry para o Application Insights.

Instalação

pip install azure-monitor-opentelemetry-exporter

Variáveis de Ambiente

APPLICATIONINSIGHTS_CONNECTION_STRING=InstrumentationKey=xxx;IngestionEndpoint=https://xxx.in.applicationinsights.azure.com/  # Obrigatório para todos os métodos de autenticação
AZURE_TOKEN_CREDENTIALS=prod # Obrigatório apenas se DefaultAzureCredential for usado em produção

🔑 Autenticação e ciclo de vida: Esses exportadores aceitam uma string de conexão por design, mas para ingestão autenticada pelo AAD (onde suportado), prefira DefaultAzureCredential por meio do parâmetro credential= — consulte a seção de Autenticação do Azure AD. Quaisquer clientes do SDK do Azure que você criar junto com o exportador devem ser envolvidos em blocos with/async with (e credenciais assíncronas de azure.identity.aio, da mesma forma).

Quando Usar

CenárioUso
Configuração rápida, instrumentação automática`azure-monitor-opentelemetry` (distro)
Canal personalizado do OpenTelemetry`azure-monitor-opentelemetry-exporter` (este)
Controle fino sobre a telemetria`azure-monitor-opentelemetry-exporter` (este)

Exportador de Rastros

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

# Lê APPLICATIONINSIGHTS_CONNECTION_STRING do ambiente para identificar o recurso;
# DefaultAzureCredential autentica a ingestão por meio do Microsoft Entra ID.
exporter = AzureMonitorTraceExporter(
    credential=DefaultAzureCredential(),
)

# Configura o provedor de rastreadores
trace.set_tracer_provider(TracerProvider())
trace.get_tracer_provider().add_span_processor(
    BatchSpanProcessor(exporter)
)

# Usa o rastreador
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

# Lê APPLICATIONINSIGHTS_CONNECTION_STRING do ambiente; ingestão autenticada pelo AAD via DefaultAzureCredential.
exporter = AzureMonitorMetricExporter(
    credential=DefaultAzureCredential(),
)

# Configura o provedor de medidores
reader = PeriodicExportingMetricReader(exporter, export_interval_millis=60000)
metrics.set_meter_provider(MeterProvider(metric_readers=[reader]))

# Usa o 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

# Lê APPLICATIONINSIGHTS_CONNECTION_STRING do ambiente; ingestão autenticada pelo AAD via DefaultAzureCredential.
exporter = AzureMonitorLogExporter(
    credential=DefaultAzureCredential(),
)

# Configura o provedor de loggers
logger_provider = LoggerProvider()
logger_provider.add_log_record_processor(BatchLogRecordProcessor(exporter))
set_logger_provider(logger_provider)

# Adiciona manipulador ao logging do Python
handler = LoggingHandler(level=logging.INFO, logger_provider=logger_provider)
logging.getLogger().addHandler(handler)

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

A partir de Variável de Ambiente

Os exportadores leem APPLICATIONINSIGHTS_CONNECTION_STRING automaticamente:

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

# String de conexão do ambiente; ingestão autenticada pelo AAD via DefaultAzureCredential.
exporter = AzureMonitorTraceExporter(
    credential=DefaultAzureCredential(),
)

Autenticação do Azure AD

from azure.identity import DefaultAzureCredential, ManagedIdentityCredential
from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter

# Desenvolvimento local: DefaultAzureCredential. Produção: defina AZURE_TOKEN_CREDENTIALS=prod ou AZURE_TOKEN_CREDENTIALS=<credencial_específica>
credential = DefaultAzureCredential(require_envvar=True)
# Ou use uma credencial específica diretamente em produção:
# 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>

Amostragem

Use ApplicationInsightsSampler para amostragem consistente:

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

# Amostra 10% dos rastros
sampler = ApplicationInsightsSampler(sampling_ratio=0.1)

trace.set_tracer_provider(TracerProvider(sampler=sampler))

Armazenamento Offline

Configure o armazenamento offline para retry:

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

exporter = AzureMonitorTraceExporter(
    credential=DefaultAzureCredential(),
    storage_directory="/caminho/para/armazenamento",  # Caminho de armazenamento personalizado
    disable_offline_storage=False  # Habilita retry (padrão)
)

Desabilitar Armazenamento Offline

exporter = AzureMonitorTraceExporter(
    credential=DefaultAzureCredential(),
    disable_offline_storage=True  # Sem retry em caso de falha
)

Nuvens Soberanas

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

# Governo do 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

ExportadorTipo de TelemetriaTabela do Application Insights
`AzureMonitorTraceExporter`Rastros/Intervalosrequests, dependencies, exceptions
`AzureMonitorMetricExporter`MétricascustomMetrics, performanceCounters
`AzureMonitorLogExporter`Registrostraces, customEvents

Opções de Configuração

ParâmetroDescriçãoPadrão
`connection_string`String de conexão do Application InsightsDa variável de ambiente
`credential`Credencial do Azure para autenticação AADNenhuma
`disable_offline_storage`Desabilitar armazenamento de retryFalso
`storage_directory`Caminho de armazenamento personalizadoDiretório temporário

Melhores Práticas

  1. Escolha síncrono OU assíncrono e mantenha a consistência. Não misture clientes síncronos azure.xxx com clientes assíncronos azure.xxx.aio no mesmo caminho de chamada. Escolha um modo por módulo.
  2. Limpe e desligue os provedores ao final do processo. Chame as APIs de encerramento/limpeza (por exemplo, tracer_provider.shutdown(), meter_provider.shutdown(), logger_provider.shutdown()) ao final do processo para despejar a telemetria antes que o processo termine.
  3. Use BatchSpanProcessor para produção (não SimpleSpanProcessor)
  4. Use ApplicationInsightsSampler para amostragem consistente entre serviços
  5. Habilite o armazenamento offline para confiabilidade em produção
  6. Use autenticação do Microsoft Entra em vez de chaves de instrumentação
  7. Defina intervalos de exportação adequados à sua carga de trabalho
  8. Use o distro (azure-monitor-opentelemetry) a menos que você precise de canais personalizados
Ver no GitHub
---
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 os arquivos

0 arquivos

Instalar azure-monitor-opentelemetry-exporter-py

Baixe e extraia os arquivos de habilidade para o diretório .claude/skills/.

Baixar ZIP

Clone o repositório e copie os arquivos da habilidade para o seu projeto.

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 Copiar
Configuração rápida: Copie a pasta de habilidades para .claude/skills/ O Claude detectará e usará automaticamente a habilidade
Repositório microsoft/skills

Habilidades relacionadas

Verification &amp; Quality Assurance
Tempo atualizado 29 de Junho de 2026
base44-cli
Tempo atualizado 29 de Junho de 2026
klingai-upgrade-migration
Tempo atualizado 3 de Julho de 2026
Railway CLI Management
Tempo atualizado 2 de Julho de 2026
OR