SuperAPI AI 工具集

azure-monitor-opentelemetry-exporter-py

部署与运维

查看项目

更新于 10-16 02:06

技能介绍

Azure Monitor OpenTelemetry Exporter for Python 是一个低层导出器,用于将 OpenTelemetry 的追踪、指标和日志发送到 Application Insights。

用途 当需要自定义 OpenTelemetry 管道、对遥测数据进行细粒度控制时使用本导出器。若只需快速设置和自动插桩,应使用 azure-monitor-opentelemetry(distro)。

安装 pip install azure-monitor-opentelemetry-exporter

环境变量 APPLICATIONINSIGHTS_CONNECTION_STRING=InstrumentationKey=xxx;IngestionEndpoint=https://xxx.in.applicationinsights.azure.com/

主要能力 提供三种导出器:AzureMonitorTraceExporter 用于追踪/跨度,对应 Application Insights 的 requests、dependencies、exceptions 表;AzureMonitorMetricExporter 用于指标,对应 customMetrics、performanceCounters 表;AzureMonitorLogExporter 用于日志,对应 traces、customEvents 表。

使用方式 追踪导出器:从 opentelemetry 导入 trace,从 opentelemetry.sdk.trace 导入 TracerProvider,从 opentelemetry.sdk.trace.export 导入 BatchSpanProcessor,从 azure.monitor.opentelemetry.exporter 导入 AzureMonitorTraceExporter。创建导出器时可传入 connection_string,然后配置 tracer provider 并添加 BatchSpanProcessor。

指标导出器:从 opentelemetry 导入 metrics,从 opentelemetry.sdk.metrics 导入 MeterProvider,从 opentelemetry.sdk.metrics.export 导入 PeriodicExportingMetricReader,从 azure.monitor.opentelemetry.exporter 导入 AzureMonitorMetricExporter。创建导出器后,用 PeriodicExportingMetricReader 包装并设置导出间隔(如 export_interval_millis=60000),再配置 MeterProvider。

日志导出器:导入 logging,从 opentelemetry._logs 导入 set_logger_provider,从 opentelemetry.sdk._logs 导入 LoggerProvider、LoggingHandler,从 opentelemetry.sdk._logs.export 导入 BatchLogRecordProcessor,从 azure.monitor.opentelemetry.exporter 导入 AzureMonitorLogExporter。创建导出器后配置 LoggerProvider 并添加 BatchLogRecordProcessor,再通过 LoggingHandler 接入 Python logging。

连接字符串可从环境变量自动读取:导出器会读取 APPLICATIONINSIGHTS_CONNECTION_STRING。也可使用 Azure AD 认证:从 azure.identity 导入 DefaultAzureCredential,创建导出器时传入 credential。

采样:可使用 ApplicationInsightsSampler 进行一致采样,例如 sampling_ratio=0.1 表示采样 10% 的追踪。

离线存储:可配置 storage_directory 指定自定义存储路径,disable_offline_storage=False 启用重试(默认),设为 True 则失败时不重试。

主权云:可使用 AzureAuthorityHosts.AZURE_GOVERNMENT 等配置 Azure Government 等环境,并传入对应的 IngestionEndpoint。

配置选项 connection_string:Application Insights 连接字符串,默认从环境变量读取。credential:用于 AAD 认证的 Azure 凭据,默认 None。disable_offline_storage:禁用重试存储,默认 False。storage_directory:自定义存储路径,默认临时目录。

最佳实践 生产环境使用 BatchSpanProcessor(而非 SimpleSpanProcessor);使用 ApplicationInsightsSampler 实现跨服务一致采样;生产环境启用离线存储以提高可靠性;使用 AAD 认证而非插桩密钥;根据工作负载设置合适的导出间隔;除非需要自定义管道,否则使用 distro(azure-monitor-opentelemetry)。

限制 仅在任务明确匹配上述范围时使用本技能。不要将输出视为环境特定验证、测试或专家审查的替代。若缺少必要输入、权限、安全边界或成功标准,应停止并请求澄清。