用途
Azure Monitor OpenTelemetry Distro for Python 用于为 Python 应用接入 Azure Monitor / Application Insights。资料描述其核心价值是“一行代码完成 Application Insights 设置,并带有 OpenTelemetry 自动埋点”。
安装
pip install azure-monitor-opentelemetry
环境变量
APPLICATIONINSIGHTS_CONNECTION_STRING=InstrumentationKey=xxx;IngestionEndpoint=https://xxx.in.applicationinsights.azure.com/
主要能力
- 一行式初始化:调用
configure_azure_monitor(),从环境变量读取连接字符串。 - 显式配置连接字符串。
- 与 Flask、Django、FastAPI 集成。
- 自定义 Traces、自定义 Metrics、自定义 Logs。
- 采样(sampling_ratio)。
- 云角色名称设置,用于 Application Map。
- 按需启用或禁用特定埋点(instrumentations)。
- 启用 Live Metrics。
- Azure AD 认证(通过 credential 参数)。
使用方式示例
快速开始:
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"}
自定义 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")
# Do work...
自定义 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"})
自定义 Logs:
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
)
云角色名称:
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
)
启用 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()
)
内置自动埋点
资料列出的库与对应遥测类型均为 Traces,包括: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 | 是否启用 Live Metrics 流 | False |
适用场景
适用于需要为 Python 应用(尤其是 Flask、Django、FastAPI 等框架构建的服务)接入 Application Insights,采集追踪、指标与日志,并支持采样、Live Metrics 与 Azure AD 认证等可观测性需求的场景。
最佳实践(来自资料)
- 尽早调用
configure_azure_monitor(),在导入被埋点的库之前。 - 生产环境通过环境变量提供连接字符串。
- 多服务应用设置云角色名称。
- 高流量应用启用采样。
- 使用结构化日志以改善日志分析查询。
- 为 span 添加自定义属性以便调试。
- 生产工作负载使用 AAD 认证。
限制
资料说明:仅当任务明确匹配上述范围时使用该技能;不应将输出视为环境特定验证、测试或专家评审的替代;若缺少必要输入、权限、安全边界或成功标准,应停止并请求澄清。其他如收费、价格、平台或效果等信息未在资料中提供。