選項
首頁首頁 Skill 開發營運和 CI/CD azure-monitor-opentelemetry-exporter-py

azure-monitor-opentelemetry-exporter-py

microsoft/skills microsoft/skills

使用 Python 將 OpenTelemetry 跟蹤、指標和日誌匯出到 Azure Application Insights。

...展開全部
0
更新時間 2026-09-19

Azure Monitor OpenTelemetry Python 匯出器

用於將 OpenTelemetry 跟蹤、指標和日誌傳送到 Application Insights 的低階匯出器。

安裝

pip install azure-monitor-opentelemetry-exporter

環境變數

APPLICATIONINSIGHTS_CONNECTION_STRING=InstrumentationKey=xxx;IngestionEndpoint=https://xxx.in.applicationinsights.azure.com/  # 所有身份驗證方法必需
AZURE_TOKEN_CREDENTIALS=prod # 僅在生產環境中使用 DefaultAzureCredential 時必需

🔑 身份驗證與生命週期: 這些匯出器在設計上接受連線字串,但對於 AAD 身份驗證的 ingestion(在支援的場景中),建議透過 credential= 引數使用 DefaultAzureCredential — 請參閱 Azure AD 身份驗證部分。您與匯出器一起建立的任何 Azure SDK 客戶端都應包裝在 with/async with 塊中(來自 azure.identity.aio 的非同步憑據也是如此)。

使用場景

場景使用
快速設定,自動儀器化`azure-monitor-opentelemetry` (發行版)
自定義 OpenTelemetry 管道`azure-monitor-opentelemetry-exporter` (本庫)
對遙測資料進行細粒度控制`azure-monitor-opentelemetry-exporter` (本庫)

跟蹤匯出器

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

# 從環境變數讀取 APPLICATIONINSIGHTS_CONNECTION_STRING 以標識資源;
# DefaultAzureCredential 透過 Microsoft Entra ID 對 ingestion 進行身份驗證。
exporter = AzureMonitorTraceExporter(
    credential=DefaultAzureCredential(),
)

# 配置跟蹤器提供程式
trace.set_tracer_provider(TracerProvider())
trace.get_tracer_provider().add_span_processor(
    BatchSpanProcessor(exporter)
)

# 使用跟蹤器
tracer = trace.get_tracer(__name__)
with tracer.start_as_current_span("my-span"):
    print("Hello, World!")

指標匯出器

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

# 從環境變數讀取 APPLICATIONINSIGHTS_CONNECTION_STRING;透過 DefaultAzureCredential 進行 AAD 身份驗證的 ingestion。
exporter = AzureMonitorMetricExporter(
    credential=DefaultAzureCredential(),
)

# 配置度量提供程式
reader = PeriodicExportingMetricReader(exporter, export_interval_millis=60000)
metrics.set_meter_provider(MeterProvider(metric_readers=[reader]))

# 使用度量器
meter = metrics.get_meter(__name__)
counter = meter.create_counter("requests_total")
counter.add(1, {"route": "/api/users"})

日誌匯出器

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

# 從環境變數讀取 APPLICATIONINSIGHTS_CONNECTION_STRING;透過 DefaultAzureCredential 進行 AAD 身份驗證的 ingestion。
exporter = AzureMonitorLogExporter(
    credential=DefaultAzureCredential(),
)

# 配置日誌提供程式
logger_provider = LoggerProvider()
logger_provider.add_log_record_processor(BatchLogRecordProcessor(exporter))
set_logger_provider(logger_provider)

# 新增到 Python 日誌處理程式
handler = LoggingHandler(level=logging.INFO, logger_provider=logger_provider)
logging.getLogger().addHandler(handler)

# 使用日誌記錄
logger = logging.getLogger(__name__)
logger.info("This will be sent to Application Insights")

從環境變數

匯出器自動讀取 APPLICATIONINSIGHTS_CONNECTION_STRING

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

# 來自環境的連線字串;透過 DefaultAzureCredential 進行 AAD 身份驗證的 ingestion。
exporter = AzureMonitorTraceExporter(
    credential=DefaultAzureCredential(),
)

Azure AD 身份驗證

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

# 本地開發:DefaultAzureCredential。生產環境:設定 AZURE_TOKEN_CREDENTIALS=prod 或 AZURE_TOKEN_CREDENTIALS=<specific_credential>
credential = DefaultAzureCredential(require_envvar=True)
# 或者在生產環境中直接使用特定的憑據:
# 請參閱 https://learn.microsoft.com/python/api/overview/azure/identity-readme?view=azure-python#credential-classes
# credential = ManagedIdentityCredential()

exporter = AzureMonitorTraceExporter(
    credential=credential
)
</specific_credential>

取樣

使用 ApplicationInsightsSampler 進行一致的取樣:

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

# 取樣 10% 的跟蹤
sampler = ApplicationInsightsSampler(sampling_ratio=0.1)

trace.set_tracer_provider(TracerProvider(sampler=sampler))

離線儲存

配置用於重試的離線儲存:

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

exporter = AzureMonitorTraceExporter(
    credential=DefaultAzureCredential(),
    storage_directory="/path/to/storage",  # 自定義儲存路徑
    disable_offline_storage=False  # 啟用重試(預設)
)

禁用離線儲存

exporter = AzureMonitorTraceExporter(
    credential=DefaultAzureCredential(),
    disable_offline_storage=True  # 失敗時不重試
)

主權雲

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
)

匯出器型別

匯出器遙測型別Application Insights 表
`AzureMonitorTraceExporter`跟蹤/跨度requests, dependencies, exceptions
`AzureMonitorMetricExporter`指標customMetrics, performanceCounters
`AzureMonitorLogExporter`日誌traces, customEvents

配置選項

引數描述預設值
`connection_string`Application Insights 連線字串來自環境變數
`credential`用於 AAD 身份驗證的 Azure 憑據None
`disable_offline_storage`禁用重試儲存False
`storage_directory`自定義儲存路徑臨時目錄

最佳實踐

  1. 選擇同步或非同步並保持一致。 不要在同一呼叫路徑中混合使用 azure.xxx 同步客戶端和 azure.xxx.aio 非同步客戶端。每個模組選擇一種模式。
  2. 在程序退出時重新整理並關閉提供程式。 在程序退出時呼叫 shutdown/flush API(例如 tracer_provider.shutdown()meter_provider.shutdown()logger_provider.shutdown()),以便在程序終止前重新整理遙測資料。
  3. 生產環境中使用 BatchSpanProcessor(而非 SimpleSpanProcessor)
  4. 使用 ApplicationInsightsSampler 以實現跨服務的一致性取樣
  5. 啟用離線儲存 以提高生產環境的可靠性
  6. 使用 Microsoft Entra 身份驗證 替代儀器化金鑰
  7. 設定適合您工作負載的匯出間隔
  8. 除非需要自定義管道,否則使用發行版 (azure-monitor-opentelemetry)
在 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

所有檔案

0 個檔案

安裝 azure-monitor-opentelemetry-exporter-py

將技能檔案下載並解壓至你的 .claude/skills/ 目錄。

下載 ZIP

複製儲存庫並將技能檔案複製到您的專案中。

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

複製 複製
快速設定: 將技能資料夾複製到 .claude/skills/ 目錄。Claude 將自動檢測並使用該技能。
儲存庫 microsoft/skills

相關技能

klingai-upgrade-migration
更新時間 2026-07-03
Verification &amp; Quality Assurance
更新時間 2026-06-29
base44-cli
更新時間 2026-06-29
Railway CLI Management
更新時間 2026-07-02
OR