Azure Monitor Opentelemetry Exporter Py

作者 microsoft354361d83247MIT收錄於 2026年10月8日更新於 2026年10月8日

Azure Monitor OpenTelemetry Exporter for Python. Use for low-level OpenTelemetry export to Application Insights. Triggers: "azure-monitor-opentelemetry-exporter", "AzureMonitorTraceExporter", "AzureMonitorMetricExporter", "AzureMonitorLogExporter".

AI 產生的概覽

指導 Python 開發者將 OpenTelemetry 追蹤、計量與記錄匯出至 Azure Application Insights。

功能
此技能提供使用 azure-monitor-opentelemetry-exporter Python 套件將 OpenTelemetry 遙測資料傳送至 Application Insights 的參考說明與程式碼範例。內容涵蓋追蹤、計量與記錄匯出器、使用 DefaultAzureCredential 進行驗證、取樣、離線儲存、主權雲端以及組態選項。它產出的是指引與範例片段,而非可執行指令碼。
適用情境
適用於在 Python 中建置需要低階控制、將遙測資料匯出至 Application Insights 的自訂 OpenTelemetry 管線時。也適用於為此類匯出器設定驗證、取樣或離線儲存的場景。
執行需求
需要 azure-monitor-opentelemetry-exporter Python 套件、azure-identity 套件以及 OpenTelemetry SDK 套件。需要 Application Insights 連接字串;若使用 Microsoft Entra 驗證,還需要 Azure 認證。需要連線至 Azure 擷取端點的網路存取。不隨附指令碼。

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 methodsAZURE_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

ScenarioUse
Quick setup, auto-instrumentationazure-monitor-opentelemetry (distro)
Custom OpenTelemetry pipelineazure-monitor-opentelemetry-exporter (this)
Fine-grained control over telemetryazure-monitor-opentelemetry-exporter (this)

Trace Exporter

python
from azure.identity import DefaultAzureCredentialfrom opentelemetry import tracefrom opentelemetry.sdk.trace import TracerProviderfrom opentelemetry.sdk.trace.export import BatchSpanProcessorfrom 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 providertrace.set_tracer_provider(TracerProvider())trace.get_tracer_provider().add_span_processor(    BatchSpanProcessor(exporter))
# Use tracertracer = trace.get_tracer(__name__)with tracer.start_as_current_span("my-span"):    print("Hello, World!")

Metric Exporter

python
from azure.identity import DefaultAzureCredentialfrom opentelemetry import metricsfrom opentelemetry.sdk.metrics import MeterProviderfrom opentelemetry.sdk.metrics.export import PeriodicExportingMetricReaderfrom azure.monitor.opentelemetry.exporter import AzureMonitorMetricExporter
# Reads APPLICATIONINSIGHTS_CONNECTION_STRING from env; AAD-authenticated ingestion via DefaultAzureCredential.exporter = AzureMonitorMetricExporter(    credential=DefaultAzureCredential(),)
# Configure meter providerreader = PeriodicExportingMetricReader(exporter, export_interval_millis=60000)metrics.set_meter_provider(MeterProvider(metric_readers=[reader]))
# Use metermeter = metrics.get_meter(__name__)counter = meter.create_counter("requests_total")counter.add(1, {"route": "/api/users"})

Log Exporter

python
import loggingfrom azure.identity import DefaultAzureCredentialfrom opentelemetry._logs import set_logger_providerfrom opentelemetry.sdk._logs import LoggerProvider, LoggingHandlerfrom opentelemetry.sdk._logs.export import BatchLogRecordProcessorfrom azure.monitor.opentelemetry.exporter import AzureMonitorLogExporter
# Reads APPLICATIONINSIGHTS_CONNECTION_STRING from env; AAD-authenticated ingestion via DefaultAzureCredential.exporter = AzureMonitorLogExporter(    credential=DefaultAzureCredential(),)
# Configure logger providerlogger_provider = LoggerProvider()logger_provider.add_log_record_processor(BatchLogRecordProcessor(exporter))set_logger_provider(logger_provider)
# Add handler to Python logginghandler = LoggingHandler(level=logging.INFO, logger_provider=logger_provider)logging.getLogger().addHandler(handler)
# Use logginglogger = 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 DefaultAzureCredentialfrom 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, ManagedIdentityCredentialfrom 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 TracerProviderfrom opentelemetry.sdk.trace.sampling import ParentBasedTraceIdRatiofrom azure.monitor.opentelemetry.exporter import ApplicationInsightsSampler
# Sample 10% of tracessampler = ApplicationInsightsSampler(sampling_ratio=0.1)
trace.set_tracer_provider(TracerProvider(sampler=sampler))

Offline Storage

Configure offline storage for retry:

python
from azure.identity import DefaultAzureCredentialfrom 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, DefaultAzureCredentialfrom azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter
# Azure Governmentcredential = DefaultAzureCredential(authority=AzureAuthorityHosts.AZURE_GOVERNMENT)exporter = AzureMonitorTraceExporter(    connection_string="InstrumentationKey=xxx;IngestionEndpoint=https://xxx.in.applicationinsights.azure.us/",    credential=credential)

Exporter Types

ExporterTelemetry TypeApplication Insights Table
AzureMonitorTraceExporterTraces/Spansrequests, dependencies, exceptions
AzureMonitorMetricExporterMetricscustomMetrics, performanceCounters
AzureMonitorLogExporterLogstraces, customEvents

Configuration Options

ParameterDescriptionDefault
connection_stringApplication Insights connection stringFrom env var
credentialAzure credential for AAD authNone
disable_offline_storageDisable retry storageFalse
storage_directoryCustom storage pathTemp 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

FileContents
references/capabilities.md [blocked]Additional non-hero capabilities, operation-group coverage, and production checklists.
references/non-hero-scenarios.md [blocked]Dedicated non-hero examples for secondary/advanced scenarios.

來源與署名

來源:microsoft/skills位於.github/plugins/azure-sdk-python/skills/azure-monitor-opentelemetry-exporter-py提交354361d

授權條款: MIT

內容歸原作者所有。SourceWeft 從公開儲存庫中收錄這些內容。

檢舉或申請下架