- AI 技能
- AI 插件
【免费下载链接】agentic-awesome-skills
AAS Core is the local, agent-first control plane for complete catalog discovery, agent-owned selection, stack validation, and planning, backed by 2,445+ agentic skills. Includes CLI, local MCP, catalog, plugins, and Workbench.
本指南以 plugins/agentic-awesome-skills-claude/skills/azure-monitor-opentelemetry-py/SKILL.md 为核心主体,系统讲解如何基于azure-monitor-opentelemetry发行版(Distro)以一行代码完成 Application Insights 接入与 OpenTelemetry 自动埋点。读完本文,你将掌握连接字符串配置、三大主流 Web 框架(Flask / Django / FastAPI)的零侵入接入、自定义 Trace / Metrics / Logs、采样与云角色名设置、AAD 认证等完整实战能力,并能理解该 Skill 在 AAS 仓库中"云可观测性"分类下的定位与适用边界。
一、Skill 定位:为什么需要"一行式"接入
在现代 Python 应用中,可观测性通常包含三条数据链路:分布式追踪(Traces)、指标(Metrics)与日志(Logs)。手工接入这三者需要分别配置 SDK、导出器(Exporter)与仪表化库(Instrumentation Library),步骤繁琐且极易出错。
Azure Monitor OpenTelemetry Distro(azure-monitor-opentelemetry)通过一个统一的入口函数configure_azure_monitor()把上述过程封装为一次调用:它负责读取连接字符串、初始化 OpenTelemetry SDK 的 Trace / Metrics / Logs 三个信号管道、装配 Azure Monitor 导出器,并自动启用常见第三方库的仪表化。这正是本 Skill 的核心价值——以最小的代码改动为 Python 应用建立通往 Application Insights 的可观测性管道。
在 skills/azure-monitor-opentelemetry-py/SKILL.md(以及 Claude 插件侧的同名文件)中,该 Skill 的元数据明确标注为risk: critical、source: community、分类cloud,并在 data/skills_index.json 的索引条目(id: azure-monitor-opentelemetry-py)中登记,同时支持codex与claude两种 Agent 目标。也就是说,在 AAS 的 Skill 生态中,它属于"云平台可观测性"类别、风险等级为关键的社区技能——Agent 在识别到"为 Python 服务接入 Application Insights / Azure Monitor 可观测性"这类任务时会被自动匹配。
二、安装与连接字符串配置
2.1 安装
pip install azure-monitor-opentelemetry该包是接入的核心依赖,它同时会带入 OpenTelemetry SDK 与 Azure Monitor Exporter 的相关组件。若你的项目使用requirements.txt或pyproject.toml管理依赖,请将该包加入其中以确保部署环境一致。
2.2 环境变量(推荐用于生产)
APPLICATIONINSIGHTS_CONNECTION_STRING=InstrumentationKey=xxx;IngestionEndpoint=https://xxx.in.applicationinsights.azure.com/连接字符串(Connection String)是 Application Insights 资源的访问凭证,由InstrumentationKey(仪表密钥)与IngestionEndpoint(数据摄取端点)两部分组成。将其放入环境变量后,configure_azure_monitor()在未显式传参时会自动读取,从而避免把敏感信息硬编码进源码。
提示:实际部署时请将
xxx替换为你在 Azure 门户中 Application Insights 资源里真实获取的连接字符串;在不同 Azure 区域中IngestionEndpoint的主机名(如.in.applicationinsights.azure.com前缀)可能不同,以门户提供的值为准。
三、快速开始与显式配置
3.1 快速开始(读取环境变量)
from azure.monitor.opentelemetry import configure_azure_monitor # One-line setup - reads connection string from environment configure_azure_monitor() # Your application code...这是最简接入方式:不传任何参数,仅依赖APPLICATIONINSIGHTS_CONNECTION_STRING环境变量完成初始化。
3.2 显式配置(代码内传入连接字符串)
from azure.monitor.opentelemetry import configure_azure_monitor configure_azure_monitor( connection_string="InstrumentationKey=xxx;IngestionEndpoint=https://xxx.in.applicationinsights.azure.com/" )适合本地开发、临时环境或无法使用环境变量的场景。两种方式等价,实际生产建议优先采用环境变量方案(见文末最佳实践)。
四、主流 Web 框架接入
Distro 的核心优势在于对常见框架的自动仪表化:只需在框架对象创建之前调用configure_azure_monitor(),随后创建的 Flask、Django、FastAPI 应用便会自动产生分布式追踪数据。
4.1 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()4.2 Django
# settings.py from azure.monitor.opentelemetry import configure_azure_monitor configure_azure_monitor() # Django settings...Django 场景下,初始化应放在settings.py中且位于任意视图/中间件加载之前,从而保证请求链路从一开始就被正确捕获。
4.3 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"}三个框架的使用模式完全一致——先初始化 Distro,再定义应用对象。这一点对异步框架(FastAPI、aiohttp)同样成立,Distro 会一并处理其异步上下文传播。
五、自定义 Telemetry:Trace、Metrics、Logs
除了自动采集,你还可以通过标准的 OpenTelemetry API 在业务代码中注入自定义数据,用于更精细的链路追踪、业务指标与日志关联。
5.1 自定义 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...要点:通过trace.get_tracer(__name__)获取 Tracer,start_as_current_span将新 Span 挂到当前上下文,span.set_attribute()可写入自定义属性(如业务订单号、用户 ID),这些属性后续可用于 Application Insights 中的查询与筛选。
5.2 自定义 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"})OpenTelemetry 指标 API 支持 Counter、Histogram、ObservableCounter 等类型;上例以 Counter 为例,每次counter.add()都会累加计数,并可通过 attributes(维度)做细分统计,最终呈现在 Application Insights 的指标/自定义指标视图中。
5.3 自定义 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)调用configure_azure_monitor()后,标准库logging的日志会自动路由到 Application Insights(Distro 会安装对应的日志处理器)。建议:
- 为 logger 显式设置
setLevel(logging.INFO),否则可能因默认级别过滤而丢失 INFO 级日志; - 错误日志带上
exc_info=True以输出堆栈信息,便于后续排障。
六、关键配置项深入:采样、云角色名与仪表化控制
6.1 采样(Sampling)
高流量场景下,为控制成本与摄取量,可以按比例采样:
from azure.monitor.opentelemetry import configure_azure_monitor # Sample 10% of requests configure_azure_monitor( sampling_ratio=0.1 )sampling_ratio取值范围为0.0 ~ 1.0,默认1.0(全量)。0.1即仅采集 10% 的请求追踪。
6.2 云角色名(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"}) )原理:OpenTelemetry 的Resource携带服务标识元数据,Distro 会把其中的SERVICE_NAME映射为 Application Insights 的 cloud_RoleName 字段,从而在应用地图上以"my-service-name"标识该节点。
6.3 精确控制启用哪些仪表化
默认启用全部支持的仪表化库;若只想启用部分库,可显式传入instrumentations列表:
from azure.monitor.opentelemetry import configure_azure_monitor configure_azure_monitor( instrumentations=["flask", "requests"] # Only enable these )这既可用于减少不必要的埋点开销,也可避免某些库的自动仪表化与业务逻辑冲突。若未传入该参数,则默认启用下表中的全部仪表化。
6.4 Live Metrics 实时指标流
from azure.monitor.opentelemetry import configure_azure_monitor configure_azure_monitor( enable_live_metrics=True )enable_live_metrics默认False;设为True后,可在 Azure 门户的"实时指标"(Live Metrics)视图中近乎实时地观察请求量、性能与异常,适合发布上线或压测期间进行即时监控。
6.5 Azure AD 认证
无需将连接字符串写入配置,改用 Azure AD 托管身份/服务主体认证:
from azure.monitor.opentelemetry import configure_azure_monitor from azure.identity import DefaultAzureCredential configure_azure_monitor( credential=DefaultAzureCredential() )DefaultAzureCredential会按顺序尝试环境变量、托管身份、Azure CLI 等多种凭据来源,适合在 AKS、VM 等支持托管身份的生产环境使用,避免密钥管理风险。
七、自动仪表化清单与配置参数总览
7.1 内置自动仪表化库
| Library | Telemetry Type |
|---|---|
| Flask | Traces |
| Django | Traces |
| FastAPI | Traces |
| Requests | Traces |
| urllib3 | Traces |
| httpx | Traces |
| aiohttp | Traces |
| psycopg2 | Traces |
| pymysql | Traces |
| pymongo | Traces |
| redis | Traces |
覆盖了 Web 框架、HTTP 客户端(同步与异步)以及主流数据库驱动(PostgreSQL、MySQL、MongoDB、Redis),意味着大多数典型后端服务的入口调用与下游数据访问都会被自动纳入追踪。
7.2configure_azure_monitor()配置参数总览
| Parameter | Description | Default |
|---|---|---|
connection_string | Application Insights connection string | From env var |
credential | Azure credential for AAD auth | None |
sampling_ratio | Sampling rate (0.0 to 1.0) | 1.0 |
resource | OpenTelemetry Resource | Auto-detected |
instrumentations | List of instrumentations to enable | All |
enable_live_metrics | Enable Live Metrics stream | False |
八、最佳实践
综合 Skill 文档与工程经验,建议在接入时遵循以下规范:
- 尽早调用
configure_azure_monitor()—— 必须在导入/实例化被仪表化的库(如 Flask、requests)之前完成初始化,确保仪表化钩子能够挂载生效; - 生产环境使用环境变量承载连接字符串,避免密钥泄漏,同时便于在部署平台(如 App Service、AKS)上按环境注入;
- 多服务应用务必设置云角色名(Cloud Role Name),保证 Application Map 拓扑清晰可辨;
- 高流量应用开启采样,通过
sampling_ratio控制成本与数据量; - 使用结构化日志,便于在 Log Analytics 中执行高效的 KQL 查询与关联分析;
- 为 Span 添加自定义属性,记录业务关键字段,提升问题定位与排查效率;
- 生产负载优先采用 AAD 认证(
credential参数),替代静态连接字符串的长期凭证。
九、适用场景与限制
何时使用本 Skill:当任务明确属于"为 Python 应用接入 Azure Monitor / Application Insights 可观测性",需要快速完成 OpenTelemetry 自动埋点、框架接入或自定义 Trace/Metrics/Logs 上报时,本 Skill 提供了一站式、可直接落地的执行路径。
使用限制:
- 仅当任务范围与上述描述清晰匹配时才使用本 Skill,避免在无关场景下强行套用;
- 输出结果不能替代针对具体环境的验证、测试或专家评审——接入后请务必在真实环境中确认数据确实到达 Application Insights;
- 若缺少必要的输入(如连接字符串、权限边界、成功标准),应停下来向用户确认,而不是擅自假设。
十、在 AAS 仓库中的延伸阅读
- 本 Skill 的 Claude 插件版本:plugins/agentic-awesome-skills-claude/skills/azure-monitor-opentelemetry-py/SKILL.md
- 本 Skill 的核心库版本:skills/azure-monitor-opentelemetry-py/SKILL.md
- Skill 索引登记(分类
cloud、风险critical):data/skills_index.json - 仓库中还提供了 TypeScript 与 Java 版本的同源 Skill(
azure-monitor-opentelemetry-ts、azure-monitor-opentelemetry-exporter-java),若你的技术栈涉及多语言,可对照查看。
通过本 Skill,Agent 可以在一分钟内为 Python 服务建立完整的 Application Insights 可观测性管道;配合采样、云角色名、AAD 认证等高级配置,即可平滑适配从单体应用到微服务集群的各类生产场景。
- AI 技能
- AI 插件
【免费下载链接】agentic-awesome-skills
AAS Core is the local, agent-first control plane for complete catalog discovery, agent-owned selection, stack validation, and planning, backed by 2,445+ agentic skills. Includes CLI, local MCP, catalog, plugins, and Workbench.
相关推荐
agentic-awesome-skills 实战:Azure Monitor OpenTelemetry Exporter for Python 低层遥测导出指南
agentic awesome skills 实战:Azure Monitor OpenTelemetry Exporter for Python 低层遥测导出
AI 技能AI 插件agentic-awesome-skills 实战:Java 应用接入 Azure Monitor OpenTelemetry Exporter 与 Autoconfigure 迁移指南
agentic awesome skills 实战:Java 应用接入 Azure Monitor OpenTelemetry Exporter 与 Autoc
AI 技能AI 插件Agentic Awesome Skills 实战:使用 azure-monitor-ingestion-java 将自定义日志写入 Azure Monitor
Agentic Awesome Skills 实战:使用 azure monitor ingestion java 将自定义日志写入 Azure Monitor
AI 技能AI 插件
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考