Azure Monitor OpenTelemetry Python SDK
Azure Monitor OpenTelemetry Distro for Python
通过 OpenTelemetry 自动检测实现 Application Insights 的单行快速配置。
安装
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
单行配置 - 从环境变量中读取连接字符串
configure_azure_monitor()
您的应用程序代码...
显式配置
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 设置...
结合 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"}
自定义追踪 (Custom Traces)
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")
# 执行操作...
自定义指标 (Custom Metrics)
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"})
自定义日志 (Custom Logs)
import logging
from azure.monitor.opentelemetry import configure_azure_monitor
configure_azure_monitor()
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
logger.info("这条日志将出现在 Application Insights 中")
logger.error("错误也会被捕获", exc_info=True)
采样 (Sampling)
from azure.monitor.opentelemetry import configure_azure_monitor
采样 10% 的请求
configure_azure_monitor(
sampling_ratio=0.1
)云角色名称 (Cloud Role Name)
为 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"] # 仅启用这些项
)
启用实时指标 (Live Metrics)
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()
)
包含的自动检测 (Auto-Instrumentations)
| 库 | 遥测类型 |
|---------|---------------|
| Flask | Traces |
| Django | Traces |
| FastAPI | Traces |
| Requests | Traces |
| urllib3 | Traces |
| httpx | Traces |
| aiohttp | Traces |
| psycopg2 | Traces |
| pymysql | Traces |
| pymongo | Traces |
| redis | Traces |
配置选项
| 参数 | 描述 | 默认值 |
|-----------|-------------|---------|
| connection_string | Application Insights 连接字符串 | 来自环境变量 |
| credential | 用于 AAD 认证的 Azure 凭据 | None |
| sampling_ratio | 采样率 (0.0 到 1.0) | 1.0 |
| resource | OpenTelemetry 资源 | 自动检测 |
| instrumentations | 要启用的检测库列表 | 全部 |
| enable_live_metrics | 启用实时指标 (Live Metrics) 流 | False |
最佳实践
1. 尽早调用 configure_azure_monitor() —— 在导入被检测的库之前调用。
2. 在生产环境中使用环境变量 配置连接字符串。
3. 为多服务应用设置云角色名称 (cloud role name)。
4. 在高流量应用中启用采样。
5. 使用结构化日志 以获得更好的日志分析查询效果。
6. 为 Span 添加自定义属性 以便于调试。
7. 生产工作负载建议使用 AAD 认证。
适用场景
本技能适用于执行概览中所描述的工作流或操作。局限性
- 仅在任务与上述范围明确匹配时使用此技能。
- 不要将输出视为针对特定环境的验证、测试或专家评审的替代方案。
- 如果缺少必要的输入、权限、安全边界或成功标准,请停止并请求澄清。