К основному содержанию
скилл

azure-monitor-opentelemetry-exporter-py — скилл для Claude Code

Скилл для низкоуровневой отправки трейсов, метрик и логов OpenTelemetry в Application Insights из Python. Пригодится, когда нужен свой конвейер телеметрии.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add microsoft/skills --skill azure-monitor-opentelemetry-exporter-py -a claude-code
Открыть на GitHub

Что делает azure-monitor-opentelemetry-exporter-py

Скилл описывает экспортёры AzureMonitorTraceExporter, AzureMonitorMetricExporter и AzureMonitorLogExporter из пакета azure-monitor-opentelemetry-exporter. Внутри — готовые примеры кода: подключение экспортёра к TracerProvider, MeterProvider и LoggerProvider, чтение строки подключения из окружения, аутентификация через DefaultAzureCredential.

Ставится пакет командой pip install azure-monitor-opentelemetry-exporter. Для работы нужна переменная APPLICATIONINSIGHTS_CONNECTION_STRING — она задаёт целевой ресурс Application Insights. Если в продакшене используется DefaultAzureCredential, дополнительно выставляют AZURE_TOKEN_CREDENTIALS=prod, чтобы сузить цепочку учётных данных до безопасных для продакшена.

Провайдеры телеметрии не работают как контекстные менеджеры. Скилл прямо советует сбрасывать буферы и останавливать провайдеры вручную при завершении процесса, иначе часть данных не дойдёт. Есть примеры сэмплирования через ApplicationInsightsSampler, офлайн-хранилища для повторной отправки и отключения этого хранилища. Для быстрой настройки с автоинструментацией авторы предлагают дистрибутив azure-monitor-opentelemetry, а этот пакет — для ручного конвейера и точного контроля над телеметрией.

Какие задачи решает

  • отправить трейсы OpenTelemetry в Application Insights
  • настроить аутентификацию экспортёра через Microsoft Entra ID
  • добавить метрики Python-приложения в Azure Monitor
  • подключить логи через LoggingHandler к провайдеру OpenTelemetry
  • включить офлайн-хранилище для повторной отправки при сбоях

Примеры запросов агенту

  • Покажи, как подключить AzureMonitorTraceExporter к TracerProvider с DefaultAzureCredential
  • Настрой AzureMonitorMetricExporter с интервалом экспорта 60000 мс
  • Как включить офлайн-хранилище для экспортёра трейсов?

Как установить azure-monitor-opentelemetry-exporter-py

1Через Skills CLI (Vercel)

npx skills add microsoft/skills --skill azure-monitor-opentelemetry-exporter-py -a claude-code

2Вручную: положить файлы

~/.claude/skills/azure-monitor-opentelemetry-exporter-py/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/azure-monitor-opentelemetry-exporter-py/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о azure-monitor-opentelemetry-exporter-py

Как установить azure-monitor-opentelemetry-exporter-py в Claude?

Выполните npx skills add microsoft/skills --skill azure-monitor-opentelemetry-exporter-py -a claude-code, затем проверьте, что файл появился по пути ~/.claude/skills/azure-monitor-opentelemetry-exporter-py/SKILL.md.

Что делает azure-monitor-opentelemetry-exporter-py?

Даёт примеры кода для экспортёров OpenTelemetry, которые шлют трейсы, метрики и логи в Application Insights. Рассчитан на ручной конвейер телеметрии, а не на автоинструментацию.

Чем этот пакет отличается от azure-monitor-opentelemetry?

Дистрибутив azure-monitor-opentelemetry подходит для быстрой настройки с автоинструментацией. Этот пакет берут, когда нужен свой конвейер OpenTelemetry и точный контроль над телеметрией.

Исходный текст

SKILL.md · MIT
---
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".
license: MIT
metadata:
  author: Microsoft
  version: "1.0.0"
  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/  # Required for all auth methods
AZURE_TOKEN_CREDENTIALS=prod # Required only if DefaultAzureCredential is used in production
```

## Authentication & Lifecycle

> **🔑 Two rules apply to every code sample below:**
>
> 1. **Prefer `DefaultAzureCredential` for ingestion auth when supported.** `APPLICATIONINSIGHTS_CONNECTION_STRING` identifies the target Application Insights resource, and `credential=DefaultAzureCredential(...)` provides Microsoft Entra authentication.
>    - Local dev: `DefaultAzureCredential` works as-is.
>    - Production: set `AZURE_TOKEN_CREDENTIALS=prod` (or `AZURE_TOKEN_CREDENTIALS=<specific_credential>`) to constrain the credential chain to production-safe credentials.
> 2. **Providers are not context managers.** Flush and shut down telemetry providers explicitly at process exit so buffers are exported deterministically.
>
> Snippets may abbreviate this setup, but production code should always follow both rules.

## 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. **Call `provider.shutdown()` / `force_flush()` at process exit to flush telemetry — providers are not context managers.**
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

## Reference Files

| File | Contents |
|------|----------|
| [references/capabilities.md](references/capabilities.md) | Additional non-hero capabilities, operation-group coverage, and production checklists. |
| [references/non-hero-scenarios.md](references/non-hero-scenarios.md) | Dedicated non-hero examples for secondary/advanced scenarios. |

© Microsoft · MIT · microsoft/skills

Похожие скиллы

Всё по теме «Облака: AWS, Azure, GCP» →
azure-monitor MicrosoftDocs Скилл с экспертизой по Azure Monitor: диагностика, настройка AMA и DCR, Log Analytics, Application Insights, алерты и OpenTelemetry. CX Codex +1 352установок azure-iac-exporter официальный github Субагент анализирует существующие ресурсы Azure и подготавливает требования для шаблона IaC. Пригодится, когда нужно перенести конфигурацию в Bicep, ARM, Terraform или Pulumi. 186установок azure-monitor-audit devops-skills Настраивает аудит подписки Azure через Monitor, Log Analytics и журнал действий. Помогает собирать логи для SOC 2, HIPAA, PCI DSS и ISO 27001. CX Codex +1 313установок azure-container-apps MicrosoftDocs Скилл помогает разрабатывать и разбирать сбои в Azure Container Apps: от сетевых настроек и масштабирования до CI/CD и Java-микросервисов. CX Codex +1 1 300установок aspire-monitoring Microsoft Скилл для наблюдения за приложениями .NET Aspire: логи, трейсы, метрики, состояние ресурсов и отдельный дашборд. Помогает разобраться, что сломалось, до правок в коде. CX Codex +1 1 100установок opentelemetry devops-skills Скилл помогает настроить OpenTelemetry в сервисах: трейсы, метрики и логи в одном формате, без привязки к вендору. CX Codex +1 339установок

Из того же набора64

Весь набор →
azure-search-documents-ts Скилл для работы с Azure AI Search SDK на JavaScript: индексы, векторный и гибридный поиск, семантический ранкинг. Пригодится, когда агент пишет код поиска по Azure. 1установок azure-identity-ts Скилл подсказывает агенту, как настроить аутентификацию в Azure через библиотеку @azure/identity в TypeScript. Пригодится, когда в проекте появляется DefaultAzureCredential или managed identity. 1установок azure-appconfiguration-ts Скилл учит агента работать с Azure App Configuration из TypeScript: настройки, фичефлаги, ссылки на Key Vault и динамическое обновление. 1установок azure-ai-projects-ts Подсказывает агенту, как работать с Azure AI Projects SDK для JavaScript: агенты, подключения, деплойменты, датасеты, индексы и оценки. 1установок azure-messaging-webpubsubservice-py Скилл по Python SDK для Azure Web PubSub Service: рассылка сообщений по WebSocket, группы, токены доступа и управление подключениями. 1установок azure-ai-language-conversations-py Скилл для работы с Conversational Language Understanding через Python SDK: разбор интентов и сущностей в диалогах. Пригодится, если пишешь NLP-фичи на Azure. 1установок microsoft-azure-webjobs-extensions-authentication-events-dotnet Скилл для работы с кастомными событиями аутентификации Microsoft Entra ID в .NET: добавление claims в токены, сбор атрибутов, OTP. 1установок azure-security-keyvault-keys-dotnet Скилл для работы с ключами Azure Key Vault и Managed HSM из .NET: создание, ротация, шифрование, подпись. Пригодится, когда агент пишет код на C#. 1установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой