
使用 Azure Monitor Query Python SDK 查询日志与指标azure-monitor-query-py 技能实战指南【免费下载链接】agentic-awesome-skillsAAS Core is the local, agent-first control plane for complete catalog discovery, agent-owned selection, stack validation, and planning, backed by 2,400 agentic skills. Includes CLI, local MCP, catalog, plugins, and Workbench.项目地址: https://gitcode.com/gh_mirrors/an/agentic-awesome-skills本指南基于 agentic-awesome-skills 仓库收录的社区技能 azure-monitor-query-pySKILL.md系统讲解如何用 Python 的azure-monitor-querySDK 查询 Log Analytics 工作区日志与 Azure Monitor 资源指标。读完本文你将掌握日志/指标双客户端的完整用法、Kusto 查询技巧、批量查询与部分结果处理以及如何在 Agent 工作流中安全、正确地调用这一能力。技能概览与仓库定位azure-monitor-query-py是 agentic-awesome-skills 仓库中面向Azure 可观测性数据读取的社区技能source: community其 frontmatter 中标注risk: critical、date_added: 2026-02-27说明它面向生产级监控数据的查询操作。该技能在仓库中有两个副本主目录下的 skills/azure-monitor-query-py/SKILL.md 与 Claude 插件变体 plugins/agentic-awesome-skills-claude/skills/azure-monitor-query-py/SKILL.md。同时该技能已被仓库的数据资产正式收录在 data/catalog.json 中出现 8 处相关引用并同步登记于 data/skills_index.json 与 data/bundles.json表明它是 AAS 目录体系中可被发现、可被 Agent 检索与选择的正式成员。这正体现了 AAS「agent-first control plane」的定位——Agent 通过目录发现技能再按技能文档执行查询。技能的核心定位一句话即可概括只用 Python 读取 Azure Monitor 日志与指标只读操作不涉及写入与配置变更适合故障排查、容量分析、告警验证等场景。安装与环境准备安装 SDKpip install azure-monitor-queryazure-monitor-query是 Azure SDK for Python 家族的查询客户端库依赖azure-core与azure-identity认证库通常需要一并安装pip install azure-identity。它面向两类数据源Log Analytics 工作区日志通过LogsQueryClient查询 Kusto 查询语言KQLAzure Monitor 平台指标通过MetricsQueryClient查询资源的数值型指标序列。环境变量技能文档约定通过环境变量注入查询目标避免在代码中硬编码敏感信息# Log Analytics AZURE_LOG_ANALYTICS_WORKSPACE_IDworkspace-id # Metrics AZURE_METRICS_RESOURCE_URI/subscriptions/sub/resourceGroups/rg/providers/provider/type/nameAZURE_LOG_ANALYTICS_WORKSPACE_IDLog Analytics 工作区的workspaceId形如 GUID是日志查询的必填目标AZURE_METRICS_RESOURCE_URIAzure 资源的 ARM 资源 ID遵循/subscriptions/{sub}/resourceGroups/{rg}/providers/{provider}/{type}/{name}格式例如/subscriptions/xxx/resourceGroups/my-rg/providers/Microsoft.Web/sites/my-app用于定位指标归属资源。这两个变量在下面所有代码示例中均可直接复用。认证DefaultAzureCredentialfrom azure.identity import DefaultAzureCredential credential DefaultAzureCredential()DefaultAzureCredential按链式顺序依次尝试多种身份来源典型包括环境变量凭据AZURE_CLIENT_ID/AZURE_TENANT_ID/AZURE_CLIENT_SECRET、Azure CLI 登录缓存、托管身份部署在 Azure VM / App Service 时、Visual Studio Code / Azure PowerShell 登录态等。因此它既能满足本地开发先用az login登录也能无缝支持云端无密钥部署走托管身份是技能文档首推的零配置认证方式。需要注意日志与指标查询均要求该身份具备对目标工作区/资源的最小读取权限Log Analytics Reader、Monitoring Reader 等权限不足会在运行时返回 403/Authorization 相关错误属于「环境特定验证」范畴应在实际环境中确认。LogsQueryClient查询 Log Analytics 日志基础查询from azure.monitor.query import LogsQueryClient from datetime import timedelta client LogsQueryClient(credential) query AppRequests | where TimeGenerated ago(1h) | summarize count() by bin(TimeGenerated, 5m), ResultCode | order by TimeGenerated desc response client.query_workspace( workspace_idos.environ[AZURE_LOG_ANALYTICS_WORKSPACE_ID], queryquery, timespantimedelta(hours1) ) for table in response.tables: for row in table.rows: print(row)关键点拆解query_workspace(workspace_id, query, timespan, ...)是核心方法workspace_id即上文环境变量注入的值query为 KQL 语句——示例中先用where TimeGenerated ago(1h)过滤最近一小时日志再用summarize count() by bin(TimeGenerated, 5m), ResultCode按 5 分钟窗口和结果码聚合请求数最后排序timespan用timedelta(hours1)表示「最近 1 小时」这是相对时间范围的推荐写法详见最佳实践响应对象含tables列表每张表有rows行元组列表与columns列定义逐行遍历即可输出结果。显式时间范围from datetime import datetime, timezone response client.query_workspace( workspace_idworkspace_id, queryAppRequests | take 10, timespan( datetime(2024, 1, 1, tzinfotimezone.utc), datetime(2024, 1, 2, tzinfotimezone.utc) ) )当需要回溯某个确定的历史窗口时将timespan传为(开始时间, 结束时间)的 UTC 元组即可。注意时区必须显式指定为 UTCtzinfotimezone.utc否则 SDK 会因 naive datetime 报错或产生时区偏移LogsQueryClient的timespan也可以直接传一个timedelta表示「从现在向前回溯」。转换为 DataFrameimport pandas as pd response client.query_workspace(workspace_id, query, timespantimedelta(hours1)) if response.tables: table response.tables[0] df pd.DataFrame(datatable.rows, columns[col.name for col in table.columns]) print(df.head())将查询结果接入 pandas 是最常用的下游分析方式以首张表的rows作为数据行、以columns中的列名作为表头构造DataFrame即可直接使用groupby、绘图、统计等生态工具。这是技能文档最佳实践中「Convert to DataFrame for easier data analysis」的落地写法。批量查询from azure.monitor.query import LogsBatchQuery queries [ LogsBatchQuery(workspace_idworkspace_id, queryAppRequests | take 5, timespantimedelta(hours1)), LogsBatchQuery(workspace_idworkspace_id, queryAppExceptions | take 5, timespantimedelta(hours1)) ] responses client.query_batch(queries) for response in responses: if response.tables: print(fRows: {len(response.tables[0].rows)})当需要同时执行多条日志查询时用LogsBatchQuery封装每条查询并一次性提交给query_batch()。批量接口在服务端并行执行能显著减少多次串行调用的往返时延与配额消耗返回值是与提交顺序对应的响应列表逐一处理即可。处理部分结果from azure.monitor.query import LogsQueryStatus response client.query_workspace(workspace_id, query, timespantimedelta(hours24)) if response.status LogsQueryStatus.PARTIAL: print(fPartial results: {response.partial_error}) elif response.status LogsQueryStatus.FAILURE: print(fQuery failed: {response.partial_error})大时间窗口或复杂聚合查询可能触发服务端部分成功此时返回的status为LogsQueryStatus.PARTIAL响应中已包含部分数据但partial_error记录了未完成部分的原因如超出内存限制、超时或数据量过大。代码必须显式区分三种状态LogsQueryStatus.SUCCESS查询完全成功LogsQueryStatus.PARTIAL有部分数据但存在局部错误需通过partial_error判断可信度LogsQueryStatus.FAILURE整体失败数据不可用。这是技能文档最佳实践中「Handle partial results for large queries」的实现依据。MetricsQueryClient查询 Azure Monitor 指标查询资源指标from azure.monitor.query import MetricsQueryClient from datetime import timedelta metrics_client MetricsQueryClient(credential) response metrics_client.query_resource( resource_urios.environ[AZURE_METRICS_RESOURCE_URI], metric_names[Percentage CPU, Network In Total], timespantimedelta(hours1), granularitytimedelta(minutes5) ) for metric in response.metrics: print(f{metric.name}:) for time_series in metric.timeseries: for data in time_series.data: print(f {data.timestamp}: {data.average})query_resource(resource_uri, metric_names, timespan, granularity, ...)按资源读取平台指标metric_names指标名列表示例中的Percentage CPU、Network In Total为 VM 等资源的平台指标granularity采样粒度。timedelta(minutes5)表示 5 分钟一个数据点粒度越细数据点越多、费用与解析开销越高结果结构为metrics → timeseries → data三层每个指标包含若干时间序列每个序列含时间戳与average、minimum、maximum、count等聚合值字段。指定聚合类型from azure.monitor.query import MetricAggregationType response metrics_client.query_resource( resource_uriresource_uri, metric_names[Requests], timespantimedelta(hours1), aggregations[ MetricAggregationType.AVERAGE, MetricAggregationType.MAXIMUM, MetricAggregationType.MINIMUM, MetricAggregationType.COUNT ] )默认情况下服务端按Average返回如需峰值、谷值与请求计数通过aggregations显式列出MetricAggregationType枚举AVERAGE/MAXIMUM/MINIMUM/COUNT/TOTAL。多聚合组合能在一次请求中同时拿到均值、极值与总量适合性能瓶颈研判。按维度过滤response metrics_client.query_resource( resource_uriresource_uri, metric_names[Requests], timespantimedelta(hours1), filterApiName eq GetBlob )filter使用 OData 语法对指标维度dimension做过滤示例ApiName eq GetBlob表示只保留 API 名为GetBlob的时间序列。维度过滤可以大幅缩小返回的时间序列数量使结果聚焦到具体实例、接口或区域——这是技能最佳实践中「Filter by dimensions to narrow metric results」的直接体现。列出指标定义与命名空间definitions metrics_client.list_metric_definitions(resource_uri) for definition in definitions: print(f{definition.name}: {definition.unit}) namespaces metrics_client.list_metric_namespaces(resource_uri) for ns in namespaces: print(ns.fully_qualified_namespace)在编写查询前可用两个「发现型」接口盘点资源可用的指标资产list_metric_definitions(resource_uri)枚举该资源支持的全部指标及其单位如Percent、CountPerSecond、Bytes用于确认指标名拼写list_metric_namespaces(resource_uri)列出指标的命名空间如Microsoft.Web/sites用于理解指标归属层次尤其是在自定义命名空间场景下。异步客户端from azure.monitor.query.aio import LogsQueryClient, MetricsQueryClient from azure.identity.aio import DefaultAzureCredential async def query_logs(): credential DefaultAzureCredential() client LogsQueryClient(credential) response await client.query_workspace( workspace_idworkspace_id, queryAppRequests | take 10, timespantimedelta(hours1) ) await client.close() await credential.close() return response两个客户端都在azure.monitor.query.aio与azure.identity.aio下提供异步变体API 签名与同步版一一对应仅将调用改为await。在高并发编排场景如 Agent 同时查询多个工作区/资源下asyncio版本可避免阻塞事件循环。注意异步模式下必须显式await client.close()与await credential.close()释放底层连接。常用 Kusto 查询速查技能文档附带四组开箱即用的 KQL 模板覆盖日志排查最常见场景// Requests by status code AppRequests | summarize count() by ResultCode | order by count_ desc // Exceptions over time AppExceptions | summarize count() by bin(TimeGenerated, 1h) // Slow requests AppRequests | where DurationMs 1000 | project TimeGenerated, Name, DurationMs | order by DurationMs desc // Top errors AppExceptions | summarize count() by ExceptionType | top 10 by count_按状态码统计请求summarize count() by ResultCode聚合后按count_降序可快速定位 4xx/5xx 占比异常时序bin(TimeGenerated, 1h)按小时分桶统计AppExceptions用于观察异常随时间起伏慢请求where DurationMs 1000过滤出耗时超 1 秒的请求project只保留关键列Top 错误summarize count() by ExceptionType后top 10 by count_取出异常类型排行。这些模板中AppRequests、AppExceptions为 Application Insights 类表的典型名称实际使用时请按目标工作区中真实的表名如Perf、AzureActivity、Heartbeat替换。客户端类型总览ClientPurposeLogsQueryClientQuery Log Analytics workspacesMetricsQueryClientQuery Azure Monitor metricsLogsQueryClient面向结构化日志与追踪数据输入 KQL输出表集MetricsQueryClient面向数值型平台指标按资源 指标名 时间范围返回时序数据。两者共享DefaultAzureCredential认证实例可在一个程序中同时使用。最佳实践清单技能文档归纳了 7 条工程化实践结合上文代码逐一落实使用timedelta表达相对时间范围如timedelta(hours1)表示最近 1 小时语义清晰且无需处理时区边界需要精确历史窗口时再改用带tzinfotimezone.utc的绝对时间元组大查询务必处理部分结果检查response.status LogsQueryStatus.PARTIAL并读取partial_error避免把不完整数据当作全量结论多条查询用批量接口query_batch()一次提交多条LogsBatchQuery降低往返与配额开销指标查询设置合理granularity粒度越细数据点越多按需选择如 5 分钟以减少数据量与费用结果转DataFrame分析pd.DataFrame(table.rows, columns[c.name for c in table.columns])让下游统计与可视化更顺手用aggregations汇总指标一次请求同时取均值/极值/计数避免多次调用用filter按维度收窄结果如ApiName eq GetBlob聚焦目标序列、降低解析成本。使用时机与边界何时使用本技能当任务明确属于「读取 Azure Monitor 日志与指标」时例如排查应用错误、分析资源利用率、验证告警阈值、为报告收集数据即可按本技能执行查询流程frontmatter 中的risk: critical提示该操作涉及生产监控数据应在明确授权的工作区/订阅范围内执行。已知限制来自技能文档仅应在任务与上述范围明确匹配时使用本技能不要将日志/指标查询能力泛化到无关操作查询结果不能替代环境特定的验证、测试或专家复核——例如部分结果、指标缺失、时区口径等问题需结合真实环境确认若缺少必需的输入工作区 ID、资源 URI、权限、安全边界或成功标准应停下来向用户澄清而不是擅自猜测目标。延伸阅读技能本体plugins/agentic-awesome-skills-claude/skills/azure-monitor-query-py/SKILL.md、skills/azure-monitor-query-py/SKILL.md目录与索引登记data/catalog.json、data/skills_index.json、data/bundles.json技能结构与元数据规范docs/SKILL_ANATOMY.md已迁移至 docs/contributors/skill-anatomy.md【免费下载链接】agentic-awesome-skillsAAS Core is the local, agent-first control plane for complete catalog discovery, agent-owned selection, stack validation, and planning, backed by 2,400 agentic skills. Includes CLI, local MCP, catalog, plugins, and Workbench.项目地址: https://gitcode.com/gh_mirrors/an/agentic-awesome-skills创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考