Azure Monitor 查询 Java
Azure Monitor Java 查询 SDK
> 弃用通知:此包已弃用,请改用:
> - azure-monitor-query-logs — 用于日志查询
> - azure-monitor-query-metrics — 用于指标查询
>
> 查看迁移指南:日志迁移 | 指标迁移
用于查询 Azure Monitor 日志和指标的客户端库。
安装
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-monitor-query</artifactId>
<version>1.5.9</version>
</dependency>或使用 Azure SDK BOM:
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-sdk-bom</artifactId>
<version>{bom_version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-monitor-query</artifactId>
</dependency>
</dependencies>
前提条件
- Log Analytics 工作区(用于日志查询)
- Azure 资源(用于指标查询)
- 具有相应权限的 TokenCredential
环境变量
LOG_ANALYTICS_WORKSPACE_ID=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
AZURE_RESOURCE_ID=/subscriptions/{sub}/resourceGroups/{rg}/providers/{provider}/{resource}客户端创建
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();
主权云配置
// Azure 中国云 - 日志
LogsQueryClient logsClient = new LogsQueryClientBuilder()
.credential(new DefaultAzureCredentialBuilder().build())
.endpoint("https://api.loganalytics.azure.cn/v1")
.buildClient();
// Azure 中国云 - 指标
MetricsQueryClient metricsClient = new MetricsQueryClientBuilder()
.credential(new DefaultAzureCredentialBuilder().build())
.endpoint("https://management.chinacloudapi.cn")
.buildClient();
nt();
## 核心概念
| 概念 | 描述 |
|---------|-------------|
| Logs (日志) | 通过 Kusto 查询语言 (KQL) 获取的 Azure 资源日志和性能数据 |
| Metrics (指标) | 定期收集的数值型时间序列数据 |
| Workspace ID | Log Analytics 工作区标识符 |
| Resource ID | 用于指标查询的 Azure 资源 URI |
| QueryTimeInterval | 查询的时间范围 |
日志查询操作
基础查询
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_"));
}
### 通过资源 ID 查询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"));
}
### 将结果映射到自定义模型// 定义模型类
public class ActivityLog {
private String resourceGroup;
private String operationName;
public String getResourceGroup() { return resourceGroup; }
public String getOperationName() { return operationName; }
}
// 使用模型映射进行查询
List<ActivityLog> 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());
}
### 批量查询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);
// 检查是否失败
if (result3.getQueryResultStatus() == LogsQueryResultStatus.FAILURE) {
System.err.println("Query failed: " + result3.getError().getMessage());
}
### 带选项的查询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);
Response<LogsQueryResult> response = logsClient.quer
yWorkspaceWithResponse(
"{workspace-id}",
"AzureActivity | summarize count() by bin(TimeGenerated, 1h)",
new QueryTimeInterval(Duration.ofDays(7)),
options,
Context.NONE
);
LogsQueryResult result = response.getValue();
// 访问统计信息
BinaryData statistics = result.getStatistics();
// 访问可视化数据
BinaryData visualization = result.getVisualization();
### 查询多个工作区import java.util.Arrays;
LogsQueryOptions options = new LogsQueryOptions()
.setAdditionalWorkspaces(Arrays.asList("{workspace-id-2}", "{workspace-id-3}"));
Response<LogsQueryResult> response = logsClient.queryWorkspaceWithResponse(
"{workspace-id-1}",
"AzureActivity | summarize count() by TenantId",
new QueryTimeInterval(Duration.ofDays(1)),
options,
Context.NONE
);
## 指标查询操作
基础指标查询
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());
}
}
}
### 包含聚合的指标查询import com.azure.monitor.query.models.MetricsQueryOptions;
import com.azure.monitor.query.models.AggregationType;
Response<MetricsQueryResult> 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();
### 查询多个资源 (MetricsClient)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()));
}
}
## 响应结构
日志响应层级
(List<LogsTableRow>)
├── rowIndex
└── rowCells (List<LogsTableCell>)指标响应层级结构
MetricsQueryResult
├── granularity
├── timeInterval
├── namespace
├── resourceRegion
└── metrics (List<MetricResult>)
├── id, name, type, unit
└── timeSeries (List<TimeSeriesElement>)
├── metadata (dimensions)
└── values (List<MetricValue>)
├── timeStamp
├── count, average, total
├── maximum, minimum错误处理
import com.azure.core.exception.HttpResponseException;
import com.azure.monitor.query.models.LogsQueryResultStatus;
try {
LogsQueryResult result = logsClient.queryWorkspace(workspaceId, query, timeInterval);
// 检查部分失败
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());
}
最佳实践
1. 使用批量查询 — 将多个查询合并到单个请求中
2. 设置合适的超时时间 — 耗时较长的查询可能需要延长服务器超时时间
3. 限制结果大小 — 在 Kusto 查询中使用 top 或 take
4. 使用投影 (Projections) — 使用 project 仅选择需要的列
5. 检查查询状态 — 优雅地处理 PARTIAL_FAILURE 结果
6. 缓存结果 — 指标数据变化不频繁,在适当情况下进行缓存
7. 迁移至新包 — 计划迁移至 azure-monitor-query-logs 和 azure-monitor-query-metrics
参考链接
| 资源 | URL |
|----------|-----|
| Maven 包 | https://central.sonatype.com/artifact/com.azure/azure-monitor-query |
| GitHub | https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/monitor/azure-monitor-query |
| API 参考 | https://learn.microsoft.com/java/api/com.azure.monitor.query |
| Kusto 查询语言 | https://learn.microsoft.com/azure/data-explorer/kusto/query/ |
| Log Analytics 限制 | https://learn.microsoft.com/azure/azure-monitor/service-limits#la-query-api |
| 故障排除 | https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/monitor/azure-monitor-query/TROUBLESHOOTING.md |
适用场景
此技能适用于执行概览中描述的工作流或操作。局限性
- 仅在任务明确符合上述范围时使用此技能。
- 不要将输出视为针对特定环境的验证、测试或专家评审的替代方案。
- 如果缺少必要的输入、权限、安全边界或成功标准,请停止并请求澄清。