Azure Monitor Query SDK for Java 实战指南在 AAS 技能目录中构建 Logs 与 Metrics 查询能力【免费下载链接】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,445 agentic skills. Includes CLI, local MCP, catalog, plugins, and Workbench.项目地址: https://gitcode.com/gh_mirrors/an/agentic-awesome-skills本指南以 SKILL.md 为主体围绕 Azure Monitor Query SDK for Javaazure-monitor-query展开完整覆盖客户端创建、Kusto 日志查询、指标查询、批处理、错误处理与最佳实践并说明该能力在当前仓库AAS 技能目录中的定位与使用前提。读完本文你将能够用 Java 同步/异步客户端执行 Log Analytics 工作区查询与 Azure 资源指标查询、将结果映射为自定义模型、批量合并多个查询并正确处理部分失败与响应结构。技能定位与弃用说明在 AAS 技能目录中azure-monitor-query-java是一个以 SKILL.md 为唯一文件元数据 frontmatter 标记risk: safe、source: community、date_added: 2026-02-27的社区技能其描述为针对 Log Analytics 工作区执行 Kusto 查询、从 Azure 资源查询指标。需要特别留意的是该技能文档开头带有明确的DEPRECATION NOTICE弃用声明日志Logs查询请迁移至azure-monitor-query-logs包指标Metrics查询请迁移至azure-monitor-query-metrics包。因此在引入依赖之前应优先评估新包若存量代码仍在使用azure-monitor-query如 1.5.9本文下述 API 用法依然成立但新项目应规划迁移。该技能仅适用于与文档概述描述一致的工作流不可替代环境级验证、测试或专家评审。安装依赖直接引入 Maven 依赖在pom.xml中加入dependency groupIdcom.azure/groupId artifactIdazure-monitor-query/artifactId version1.5.9/version /dependency使用 Azure SDK BOM 统一版本管理推荐通过azure-sdk-bom引入避免手动维护版本号dependencyManagement dependencies dependency groupIdcom.azure/groupId artifactIdazure-sdk-bom/artifactId version{bom_version}/version typepom/type scopeimport/scope /dependency /dependencies /dependencyManagement dependencies dependency groupIdcom.azure/groupId artifactIdazure-monitor-query/artifactId /dependency /dependenciesBOM 会自动锁定与当前 BOM 版本匹配的azure-monitor-query版本并保证与其他 Azure SDK 组件版本一致。前置条件与环境变量运行示例代码前需要准备场景必需资源日志查询Log Analytics 工作区workspace指标查询Azure 资源resource通用具有相应权限的TokenCredential如DefaultAzureCredential建议通过环境变量注入标识符避免硬编码LOG_ANALYTICS_WORKSPACE_IDxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx AZURE_RESOURCE_ID/subscriptions/{sub}/resourceGroups/{rg}/providers/{provider}/{resource}AZURE_RESOURCE_ID的完整格式为 Azure 资源统一资源标识符URI例如/subscriptions/订阅ID/resourceGroups/资源组/providers/命名空间/资源类型/资源名。客户端创建SDK 提供同步与异步两类客户端分别面向阻塞式调用与高吞吐异步场景。LogsQueryClient同步import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.monitor.query.LogsQueryClient; import com.azure.monitor.query.LogsQueryClientBuilder; LogsQueryClient logsClient new LogsQueryClientBuilder() .credential(new DefaultAzureCredentialBuilder().build()) .buildClient();LogsQueryAsyncClient异步import com.azure.monitor.query.LogsQueryAsyncClient; LogsQueryAsyncClient logsAsyncClient new LogsQueryClientBuilder() .credential(new DefaultAzureCredentialBuilder().build()) .buildAsyncClient();MetricsQueryClient同步import com.azure.monitor.query.MetricsQueryClient; import com.azure.monitor.query.MetricsQueryClientBuilder; MetricsQueryClient metricsClient new MetricsQueryClientBuilder() .credential(new DefaultAzureCredentialBuilder().build()) .buildClient();MetricsQueryAsyncClient异步import com.azure.monitor.query.MetricsQueryAsyncClient; MetricsQueryAsyncClient metricsAsyncClient new MetricsQueryClientBuilder() .credential(new DefaultAzureCredentialBuilder().build()) .buildAsyncClient();所有客户端均通过对应的 BuilderLogsQueryClientBuilder/MetricsQueryClientBuilder构造credential()接收TokenCredentialDefaultAzureCredential会依次尝试环境变量、托管身份、Azure CLI 等多种认证链适合本地开发与云端部署统一使用。主权云Sovereign Cloud配置Azure 中国云等主权云环境需要显式指定 endpoint// Azure China Cloud - Logs LogsQueryClient logsClient new LogsQueryClientBuilder() .credential(new DefaultAzureCredentialBuilder().build()) .endpoint(https://api.loganalytics.azure.cn/v1) .buildClient(); // Azure China Cloud - Metrics MetricsQueryClient metricsClient new MetricsQueryClientBuilder() .credential(new DefaultAzureCredentialBuilder().build()) .endpoint(https://management.chinacloudapi.cn) .buildClient();日志服务与指标服务的 endpoint 不同日志查询走 Log Analytics APIapi.loganalytics.azure.cn/v1指标查询走 Azure Resource Manager 管理面management.chinacloudapi.cn。核心概念概念说明Logs通过 Kusto 查询语言KQL查询 Azure 资源的日志与性能数据Metrics以固定间隔采集的数值型时序数据Workspace IDLog Analytics 工作区标识符Resource ID指标查询所用的 Azure 资源 URIQueryTimeInterval查询的时间范围Logs 查询操作基础查询queryWorkspace面向工作区执行 KQL 查询并返回结构化表格结果import com.azure.monitor.query.models.LogsQueryResult; import com.azure.monitor.query.models.LogsTableRow; import com.azure.monitor.query.models.QueryTimeInterval; import java.time.Duration; LogsQueryResult result logsClient.queryWorkspace( {workspace-id}, AzureActivity | summarize count() by ResourceGroup | top 10 by count_, new QueryTimeInterval(Duration.ofDays(7)) ); for (LogsTableRow row : result.getTable().getRows()) { System.out.println(row.getColumnValue(ResourceGroup) : row.getColumnValue(count_)); }QueryTimeInterval支持基于Duration构造如最近 7 天也支持更精确的起止时间区间。按资源 ID 查询queryResource允许直接针对单个 Azure 资源查询日志LogsQueryResult result logsClient.queryResource( {resource-id}, AzureMetrics | where TimeGenerated ago(1h), new QueryTimeInterval(Duration.ofDays(1)) ); for (LogsTableRow row : result.getTable().getRows()) { System.out.println(row.getColumnValue(MetricName) row.getColumnValue(Average)); }将结果映射为自定义模型SDK 支持将查询行自动映射到 POJO减少手工取值代码// Define model class public class ActivityLog { private String resourceGroup; private String operationName; public String getResourceGroup() { return resourceGroup; } public String getOperationName() { return operationName; } } // Query with model mapping ListActivityLog logs logsClient.queryWorkspace( {workspace-id}, AzureActivity | project ResourceGroup, OperationName | take 100, new QueryTimeInterval(Duration.ofDays(2)), ActivityLog.class ); for (ActivityLog log : logs) { System.out.println(log.getOperationName() - log.getResourceGroup()); }映射依赖 KQL 中project输出的列名与模型字段的匹配此处 KQL 列名为ResourceGroup、OperationName模型字段为resourceGroup、operationName建议在 KQL 中显式project对齐字段。批量查询Batch Query将多个查询合并到一次 HTTP 请求中可显著降低往返开销import com.azure.monitor.query.models.LogsBatchQuery; import com.azure.monitor.query.models.LogsBatchQueryResult; import com.azure.monitor.query.models.LogsBatchQueryResultCollection; import com.azure.core.util.Context; LogsBatchQuery batchQuery new LogsBatchQuery(); String q1 batchQuery.addWorkspaceQuery({workspace-id}, AzureActivity | count, new QueryTimeInterval(Duration.ofDays(1))); String q2 batchQuery.addWorkspaceQuery({workspace-id}, Heartbeat | count, new QueryTimeInterval(Duration.ofDays(1))); String q3 batchQuery.addWorkspaceQuery({workspace-id}, Perf | count, new QueryTimeInterval(Duration.ofDays(1))); LogsBatchQueryResultCollection results logsClient .queryBatchWithResponse(batchQuery, Context.NONE) .getValue(); LogsBatchQueryResult result1 results.getResult(q1); LogsBatchQueryResult result2 results.getResult(q2); LogsBatchQueryResult result3 results.getResult(q3); // Check for failures if (result3.getQueryResultStatus() LogsQueryResultStatus.FAILURE) { System.err.println(Query failed: result3.getError().getMessage()); }addWorkspaceQuery返回用于定位单个结果的 key之后通过results.getResult(key)取回对应查询的结果批量结果需要逐一检查getQueryResultStatus()是否为FAILURE。带选项的查询通过LogsQueryOptions可控制服务端超时、统计信息与可视化数据import com.azure.monitor.query.models.LogsQueryOptions; import com.azure.core.http.rest.Response; LogsQueryOptions options new LogsQueryOptions() .setServerTimeout(Duration.ofMinutes(10)) .setIncludeStatistics(true) .setIncludeVisualization(true); ResponseLogsQueryResult response logsClient.queryWorkspaceWithResponse( {workspace-id}, AzureActivity | summarize count() by bin(TimeGenerated, 1h), new QueryTimeInterval(Duration.ofDays(7)), options, Context.NONE ); LogsQueryResult result response.getValue(); // Access statistics BinaryData statistics result.getStatistics(); // Access visualization data BinaryData visualization result.getVisualization();setServerTimeout延长服务端查询执行时限适合重型聚合查询setIncludeStatistics返回查询执行统计如扫描数据量、CPU 时间便于性能诊断setIncludeVisualization返回图表渲染所需的可视化数据如渲染类型与图表配置。跨工作区查询通过setAdditionalWorkspaces可在一个查询中关联多个工作区跨工作区 Join 场景import java.util.Arrays; LogsQueryOptions options new LogsQueryOptions() .setAdditionalWorkspaces(Arrays.asList({workspace-id-2}, {workspace-id-3})); ResponseLogsQueryResult response logsClient.queryWorkspaceWithResponse( {workspace-id-1}, AzureActivity | summarize count() by TenantId, new QueryTimeInterval(Duration.ofDays(1)), options, Context.NONE );主工作区通过queryWorkspaceWithResponse的第一个参数指定附加工作区在 KQL 中可直接引用其表名参与计算。Metrics 查询操作基础指标查询queryResource按资源 URI 与指标名集合查询import com.azure.monitor.query.models.MetricsQueryResult; import com.azure.monitor.query.models.MetricResult; import com.azure.monitor.query.models.TimeSeriesElement; import com.azure.monitor.query.models.MetricValue; import java.util.Arrays; MetricsQueryResult result metricsClient.queryResource( {resource-uri}, Arrays.asList(SuccessfulCalls, TotalCalls) ); for (MetricResult metric : result.getMetrics()) { System.out.println(Metric: metric.getMetricName()); for (TimeSeriesElement ts : metric.getTimeSeries()) { System.out.println( Dimensions: ts.getMetadata()); for (MetricValue value : ts.getValues()) { System.out.println( value.getTimeStamp() : value.getTotal()); } } }返回结构为指标MetricResult→ 时间序列TimeSeriesElement含维度元数据→ 数据点MetricValue含时间戳与聚合值。带聚合与粒度的指标查询import com.azure.monitor.query.models.MetricsQueryOptions; import com.azure.monitor.query.models.AggregationType; ResponseMetricsQueryResult response metricsClient.queryResourceWithResponse( {resource-id}, Arrays.asList(SuccessfulCalls, TotalCalls), new MetricsQueryOptions() .setGranularity(Duration.ofHours(1)) .setAggregations(Arrays.asList(AggregationType.AVERAGE, AggregationType.COUNT)), Context.NONE ); MetricsQueryResult result response.getValue();setGranularity指定采样粒度如 1 小时setAggregations指定返回的聚合类型AVERAGE、COUNT、SUM、MIN、MAX等未指定时服务端会返回默认聚合值。跨多资源指标查询MetricsClientMetricsClient支持在一次请求中批量查询多个资源的指标并需显式指定指标命名空间import com.azure.monitor.query.MetricsClient; import com.azure.monitor.query.MetricsClientBuilder; import com.azure.monitor.query.models.MetricsQueryResourcesResult; MetricsClient metricsClient new MetricsClientBuilder() .credential(new DefaultAzureCredentialBuilder().build()) .endpoint({endpoint}) .buildClient(); MetricsQueryResourcesResult result metricsClient.queryResources( Arrays.asList({resourceId1}, {resourceId2}), Arrays.asList({metric1}, {metric2}), {metricNamespace} ); for (MetricsQueryResult queryResult : result.getMetricsQueryResults()) { for (MetricResult metric : queryResult.getMetrics()) { System.out.println(metric.getMetricName()); metric.getTimeSeries().stream() .flatMap(ts - ts.getValues().stream()) .forEach(mv - System.out.println( mv.getTimeStamp() Count mv.getCount() Avg mv.getAverage())); } }queryResources接收三个参数资源 ID 列表、指标名列表、指标命名空间返回MetricsQueryResourcesResult其getMetricsQueryResults()按请求顺序对应各资源的结果。该能力特别适合在单个控制面批量巡检多个资源的健康状态。响应结构Logs 响应层级LogsQueryResult ├── statistics (BinaryData) ├── visualization (BinaryData) ├── error └── tables (ListLogsTable) ├── name ├── columns (ListLogsTableColumn) │ ├── name │ └── type └── rows (ListLogsTableRow) ├── rowIndex └── rowCells (ListLogsTableCell)LogsQueryResult可包含多张表如 KQLrender、union或多结果语句单元格通过LogsTableCell提供类型化取值能力。Metrics 响应层级MetricsQueryResult ├── granularity ├── timeInterval ├── namespace ├── resourceRegion └── metrics (ListMetricResult) ├── id, name, type, unit └── timeSeries (ListTimeSeriesElement) ├── metadata (dimensions) └── values (ListMetricValue) ├── timeStamp ├── count, average, total ├── maximum, minimum理解该层级是正确遍历指标数据的前提顶层携带粒度、时间区间、命名空间与资源区域逐层下钻到单个数据点。错误处理日志查询可能出现部分失败PARTIAL_FAILURE即部分行成功、部分行因类型转换等问题失败此时必须显式检查状态并读取error信息而不是盲目消费结果import com.azure.core.exception.HttpResponseException; import com.azure.monitor.query.models.LogsQueryResultStatus; try { LogsQueryResult result logsClient.queryWorkspace(workspaceId, query, timeInterval); // Check partial failure if (result.getStatus() LogsQueryResultStatus.PARTIAL_FAILURE) { System.err.println(Partial failure: result.getError().getMessage()); } } catch (HttpResponseException e) { System.err.println(Query failed: e.getMessage()); System.err.println(Status: e.getResponse().getStatusCode()); }HttpResponseException捕获 HTTP 层错误如 400 语法错误、403 权限不足、429 限流可通过e.getResponse().getStatusCode()获取状态码辅助诊断。最佳实践使用批量查询—— 将多个查询合并为一次请求减少网络往返与配额消耗设置合理的超时—— 长耗时聚合查询需通过setServerTimeout延长服务端超时限制结果集大小—— 在 KQL 中使用top/take控制返回行数使用投影projection—— 用project只选择所需列降低传输与解析开销检查查询状态—— 对PARTIAL_FAILURE结果优雅处理避免误用不完整数据缓存结果—— 指标数据变化不频繁合适场景下缓存可降低 API 配额消耗规划迁移—— 存量代码尽早迁移至azure-monitor-query-logs与azure-monitor-query-metrics跟随 SDK 演进。使用边界与注意事项本技能azure-monitor-query-java仅适用于与上述工作流匹配的任务仅在任务明确符合本技能描述范围时使用技能输出不能替代针对具体环境的验证、测试或专家评审当缺少必要的输入、权限、安全边界或成功标准时应停下来请求澄清而不是盲目执行。结合 AAS 目录的使用方式该技能文件位于 plugins/agentic-awesome-skills-claude/skills/azure-monitor-query-java/SKILL.md其 frontmatter 中的description为 Agent 提供了触发匹配依据执行 Kusto 日志查询与指标查询元数据中的risk: safe与source: community则用于目录的筛选与审计。在 AAS 的 agent-first 目录发现与选择流程中Agent 可依据该技能的描述字段在“需要查询 Azure 日志/指标”时自动匹配并加载对应文档执行。综上azure-monitor-query-java技能文档为 Java 开发者提供了一条从认证、建连、查询到错误处理的完整链路在实际落地时请结合新包迁移路线与 AAS 目录筛选机制选择最合适的查询方案。【免费下载链接】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,445 agentic skills. Includes CLI, local MCP, catalog, plugins, and Workbench.项目地址: https://gitcode.com/gh_mirrors/an/agentic-awesome-skills创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考