
关于
Azure Monitor OpenTelemetry Python 发行版。一行代码即可完成 Application Insights 设置和自动检测。
name: azure-monitor-opentelemetry-py description: Azure Monitor OpenTelemetry Distro for Python。用于一行代码设置 Application Insights 自动检测。 risk: unknown source: community date_added: '2026-02-27'
Azure Monitor OpenTelemetry Distro for Python
一行代码设置 Application Insights 与 OpenTelemetry 自动检测。
安装
pip install azure-monitor-opentelemetry
环境变量
APPLICATIONINSIGHTS_CONNECTION_STRING=InstrumentationKey=xxx;IngestionEndpoint=https://xxx.in.applicationinsights.azure.com/
快速开始
from azure.monitor.opentelemetry import configure_azure_monitor
# One-line setup - reads connection string from environment
configure_azure_monitor()
# Your application code...
显式配置
from azure.monitor.opentelemetry import configure_azure_monitor
configure_azure_monitor(
connection_string="InstrumentationKey=xxx;IngestionEndpoint=https://xxx.in.applicationinsights.azure.com/"
)
与 Flask 集成
from flask import Flask
from azure.monitor.opentelemetry import configure_azure_monitor
configure_azure_monitor()
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello, World!"
if __name__ == "__main__":
app.run()
与 Django 集成
# settings.py
from azure.monitor.opentelemetry import configure_azure_monitor
configure_azure_monitor()
# Django settings...
与 FastAPI 集成
from fastapi import FastAPI
from azure.monitor.opentelemetry import configure_azure_monitor
configure_azure_monitor()
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
自定义追踪
from opentelemetry import trace
from azure.monitor.opentelemetry import configure_azure_monitor
configure_azure_monitor()
tracer = trace.get_tracer(__name__)
with tracer.start_as_current_span("my-operation") as span:
span.set_attribute("custom.attribute", "value")
# Do work...
自定义指标
from opentelemetry import metrics
from azure.monitor.opentelemetry import configure_azure_monitor
configure_azure_monitor()
meter = metrics.get_meter(__name__)
counter = meter.create_counter("my_counter")
counter.add(1, {"dimension": "value"})
自定义日志
import logging
from azure.monitor.opentelemetry import configure_azure_monitor
configure_azure_monitor()
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
logger.info("This will appear in Application Insights")
logger.error("Errors are captured too", exc_info=True)
采样
from azure.monitor.opentelemetry import configure_azure_monitor
# Sample 10% of requests
configure_azure_monitor(
sampling_ratio=0.1
)
云角色名称
为 Application Map 设置云角色名称:
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry.sdk.resources import Resource, SERVICE_NAME
configure_azure_monitor(
resource=Resource.create({SERVICE_NAME: "my-service-name"})
)
禁用特定检测
from azure.monitor.opentelemetry import configure_azure_monitor
configure_azure_monitor(
instrumentations=["flask", "requests"] # Only enable these
)
启用实时指标
from azure.monitor.opentelemetry import configure_azure_monitor
configure_azure_monitor(
enable_live_metrics=True
)
Azure AD 认证
from azure.monitor.opentelemetry import configure_azure_monitor
from azure.identity import DefaultAzureCredential
configure_azure_monitor(
credential=DefaultAzureCredential()
)
包含的自动检测
| 库 | 遥测类型 | |---------|---------------| | Flask | 追踪 | | Django | 追踪 | | FastAPI | 追踪 | | Requests | 追踪 | | urllib3 | 追踪 | | httpx | 追踪 | | aiohttp | 追踪 | | psycopg2 | 追踪 | | pymysql | 追踪 | | pymongo | 追踪 | | redis | 追踪 |
配置选项
| 参数 | 描述 | 默认值 |
|-----------|-------------|---------|
| connection_string | Application Insights 连接字符串 | 从环境变量 |
| credential | 用于 AAD 认证的 Azure 凭据 | None |
| sampling_ratio | 采样率(0.0 到 1.0) | 1.0 |
| resource | OpenTelemetry Resource | 自动检测 |
| instrumentations | 要启用的检测列表 | 全部 |
| enable_live_metrics | 启用实时指标流 | False |
最佳实践
- 尽早调用 configure_azure_monitor() — 在导入被检测的库之前
- 在生产环境中使用环境变量存储连接字符串
- 设置云角色名称用于多服务应用
- 在高流量应用中启用采样
- 使用结构化日志以获得更好的日志分析查询
- 为 span 添加自定义属性以便更好地调试
- 在生产工作负载中使用 AAD 认证
何时使用
此技能适用于执行概述中描述的工作流或操作。
兼容工具
Claude CodeCursor
标签
后端开发
