オプション
家 Skill DevOps と CI/CD azure-monitor-opentelemetry-exporter-py

azure-monitor-opentelemetry-exporter-py

microsoft/skills microsoft/skills

Python を使用して、OpenTelemetry のトレース、メトリクス、ログを Azure Application Insights にエクスポートします。

...すべて拡張します
0
更新された時間 2026年9月19日

Python用Azure Monitor OpenTelemetryエクスポートラー

Application InsightsにOpenTelemetryのトレース、メトリクス、ログを送信するための低レベルエクスポートラー。

インストール

pip install azure-monitor-opentelemetry-exporter

環境変数

APPLICATIONINSIGHTS_CONNECTION_STRING=InstrumentationKey=xxx;IngestionEndpoint=https://xxx.in.applicationinsights.azure.com/  # すべての認証方法で必須
AZURE_TOKEN_CREDENTIALS=prod # 本番環境でDefaultAzureCredentialを使用する場合のみ必須

🔑 認証とライフサイクル: これらのエクスポートラーは設計上、接続文字列を受け取りますが、AAD認証によるデータ取り込み(サポートされている場合)では、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を介してデータ取り込みを認証します。
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認証によるデータ取り込みを行います。
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認証によるデータ取り込みを行います。
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認証によるデータ取り込みを行います。
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=<特定の資格情報> を設定
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
)

サンプリング

一貫したサンプリングのために 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 非同期クライアントを混在させないこと。モジュールごとにモードを1つ選択してください。
  2. プロセス終了時にプロバイダーをフラッシュしてシャットダウンする。 プロセス終了時にシャットダウン/フラッシュ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

関連スキル

Verification &amp; Quality Assurance
更新された時間 2026年6月29日
base44-cli
更新された時間 2026年6月29日
klingai-upgrade-migration
更新された時間 2026年7月3日
Railway CLI Management
更新された時間 2026年7月2日
OR