你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

适用于 JavaScript 的 Azure Monitor 查询客户端库 - 版本 1.2.0

Azure Monitor 查询客户端库用于对 Azure Monitor 的两个数据平台执行只读查询:

  • 日志 - 从受监视的资源收集和组织日志和性能数据。 来自不同源的数据(例如来自 Azure 服务的平台日志、来自虚拟机代理的日志和性能数据,以及应用的使用情况和性能数据)可以合并到单个 Azure Log Analytics 工作区中。 可以使用 Kusto 查询语言一起分析各种数据类型。
  • 指标 - 将受监视资源中的数字数据收集到时序数据库中。 指标是定期收集的数值,用于描述系统在某一特定时间的某些情况。 指标是轻量级的,能够支持准实时方案,因此可用于发出警报和快速检测问题。

资源:

入门

支持的环境

有关详细信息,请参阅 我们的支持策略

先决条件

安装包

使用 npm 安装适用于 JavaScript 的 Azure Monitor 查询客户端库:

npm install @azure/monitor-query

创建客户端

查询日志或指标需要经过身份验证的客户端。 为了进行身份验证,以下示例使用来自 @azure/标识包的 DefaultAzureCredential

import { DefaultAzureCredential } from "@azure/identity";
import { LogsQueryClient, MetricsQueryClient, MetricsBatchQueryClient } from "@azure/monitor-query";

const credential = new DefaultAzureCredential();

const logsQueryClient: LogsQueryClient = new LogsQueryClient(credential);
// or
const metricsQueryClient: MetricsQueryClient = new MetricsQueryClient(credential);
// or
const endPoint: string = "<YOUR_METRICS_ENDPOINT>"; //for example, https://eastus.metrics.monitor.azure.com/

const metricsQueryClient: MetricsQueryClient = new MetricsQueryClient(
  endPoint,
  credential
);

为 Azure 主权云配置客户端

默认情况下, LogsQueryClientMetricsQueryClient 配置为使用 Azure 公有云。 若要改用主权云,请提供正确的 endpoint 参数。 例如:

import { DefaultAzureCredential } from "@azure/identity";
import { LogsQueryClient, MetricsQueryClient } from "@azure/monitor-query";

const credential = new DefaultAzureCredential();

const logsQueryClient = new LogsQueryClient(credential, {
  endpoint: "https://api.loganalytics.azure.cn/v1",
});

// or
const metricsQueryClient = new MetricsQueryClient(credential{
  endpoint: "https://management.chinacloudapi.cn",
});

注意:目前, MetricsQueryClient 使用 Azure 资源管理器 (ARM) 终结点来查询指标。 使用此客户端时,需要云的相应管理终结点。 此详细信息将来可能会更改。

执行查询

有关日志和指标查询的示例,请参阅 示例 部分。

关键概念

日志查询速率限制和限制

当请求速率过高时,Log Analytics 服务会应用限制。 限制(如返回的最大行数)也应用于 Kusto 查询。 有关详细信息,请参阅 查询 API

指标数据结构

每组指标值都是具有以下特征的时序:

  • 值的收集时间
  • 与值关联的资源
  • 充当指标类别的命名空间
  • 指标名称
  • 值本身
  • 某些指标具有多个维度,如多维指标中所述。 自定义指标最多可以包含 10 个维度。

示例

日志查询

LogsQueryClient可用于使用 Kusto 查询语言查询 Log Analytics 工作区。 timespan.duration可以指定为 ISO 8601 持续时间格式的字符串。 可以使用 Durations 为某些常用的 ISO 8601 持续时间提供的常量。

可以按工作区 ID 或资源 ID 查询日志。 结果以包含行集合的表的形式返回。

以工作区为中心的日志查询

若要按工作区 ID 进行查询,请使用 LogsQueryClient.queryWorkspace 方法:

import { DefaultAzureCredential } from "@azure/identity";
import { Durations, LogsQueryClient, LogsQueryResultStatus, LogsTable } from "@azure/monitor-query";

const azureLogAnalyticsWorkspaceId = "<the Workspace Id for your Azure Log Analytics resource>";
const logsQueryClient = new LogsQueryClient(new DefaultAzureCredential());

async function run() {
  const kustoQuery = "AppEvents | limit 1";
  const result = await logsQueryClient.queryWorkspace(azureLogAnalyticsWorkspaceId, kustoQuery, {
    duration: Durations.twentyFourHours,
  });

  if (result.status === LogsQueryResultStatus.Success) {
    const tablesFromResult: LogsTable[] = result.tables;

    if (tablesFromResult.length === 0) {
      console.log(`No results for query '${kustoQuery}'`);
      return;
    }
    console.log(`This query has returned table(s) - `);
    processTables(tablesFromResult);
  } else {
    console.log(`Error processing the query '${kustoQuery}' - ${result.partialError}`);
    if (result.partialTables.length > 0) {
      console.log(`This query has also returned partial data in the following table(s) - `);
      processTables(result.partialTables);
    }
  }
}

async function processTables(tablesFromResult: LogsTable[]) {
  for (const table of tablesFromResult) {
    const columnHeaderString = table.columnDescriptors
      .map((column) => `${column.name}(${column.type}) `)
      .join("| ");
    console.log("| " + columnHeaderString);

    for (const row of table.rows) {
      const columnValuesString = row.map((columnValue) => `'${columnValue}' `).join("| ");
      console.log("| " + columnValuesString);
    }
  }
}

run().catch((err) => console.log("ERROR:", err));

以资源为中心的日志查询

以下示例演示如何直接从 Azure 资源查询日志。 此处使用 queryResource 方法并传入 Azure 资源 ID。 例如 /subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}

查找资源 ID:

  1. 导航到Azure 门户中的资源页。
  2. “概述 ”边栏选项卡中,选择“ JSON 视图” 链接。
  3. 在生成的 JSON 中,复制 属性的值 id
/**
 * @summary Demonstrates how to run a query against a Log Analytics workspace, using an Azure resource ID.
 */

import { DefaultAzureCredential } from "@azure/identity";
import {
  Durations,
  LogsQueryClient,
  LogsTable,
  LogsQueryOptions,
  LogsQueryResultStatus,
} from "@azure/monitor-query";
import * as dotenv from "dotenv";
dotenv.config();

const logsResourceId = process.env.LOGS_RESOURCE_ID;

export async function main() {
  const tokenCredential = new DefaultAzureCredential();
  const logsQueryClient = new LogsQueryClient(tokenCredential);

  if (!logsResourceId) {
    throw new Error("LOGS_RESOURCE_ID must be set in the environment for this sample");
  }

  const kustoQuery = `MyTable_CL | summarize count()`

  console.log(`Running '${kustoQuery}' over the last One Hour`);
  const queryLogsOptions: LogsQueryOptions = {
    // explicitly control the amount of time the server can spend processing the query.
    serverTimeoutInSeconds: 600, // sets the timeout to 10 minutes
    // optionally enable returning additional statistics about the query's execution.
    // (by default, this is off)
    includeQueryStatistics: true,
  };

  const result = await logsQueryClient.queryResource(
    logsResourceId, 
    kustoQuery,
    { duration: Durations.sevenDays },
    queryLogsOptions);

  const executionTime =
    result.statistics && result.statistics.query && (result.statistics.query as any).executionTime;

  console.log(
    `Results for query '${kustoQuery}', execution time: ${
      executionTime == null ? "unknown" : executionTime
    }`
  );

  if (result.status === LogsQueryResultStatus.Success) {
    const tablesFromResult: LogsTable[] = result.tables;

    if (tablesFromResult.length === 0) {
      console.log(`No results for query '${kustoQuery}'`);
      return;
    }
    console.log(`This query has returned table(s) - `);
    processTables(tablesFromResult);
  } else {
    console.log(`Error processing the query '${kustoQuery}' - ${result.partialError}`);
    if (result.partialTables.length > 0) {
      console.log(`This query has also returned partial data in the following table(s) - `);
      processTables(result.partialTables);
    }
  }
}

async function processTables(tablesFromResult: LogsTable[]) {
  for (const table of tablesFromResult) {
    const columnHeaderString = table.columnDescriptors
      .map((column) => `${column.name}(${column.type}) `)
      .join("| ");
    console.log("| " + columnHeaderString);

    for (const row of table.rows) {
      const columnValuesString = row.map((columnValue) => `'${columnValue}' `).join("| ");
      console.log("| " + columnValuesString);
    }
  }
}

main().catch((err) => {
  console.error("The sample encountered an error:", err);
  process.exit(1);
});

处理日志查询响应

queryWorkspaceLogsQueryClient 函数返回 对象 LogsQueryResult 。 对象类型可以是 LogsQuerySuccessfulResultLogsQueryPartialResult。 下面是响应的层次结构:

LogsQuerySuccessfulResult
|---statistics
|---visualization
|---status ("Success")
|---tables (list of `LogsTable` objects)
    |---name
    |---rows
    |---columnDescriptors (list of `LogsColumn` objects)
        |---name
        |---type

LogsQueryPartialResult
|---statistics
|---visualization
|---status ("PartialFailure")
|---partialError
    |--name
    |--code
    |--message
    |--stack
|---partialTables (list of `LogsTable` objects)
    |---name
    |---rows
    |---columnDescriptors (list of `LogsColumn` objects)
        |---name
        |---type

例如,若要处理包含表的响应::

async function processTables(tablesFromResult: LogsTable[]) {
  for (const table of tablesFromResult) {
    const columnHeaderString = table.columnDescriptors
      .map((column) => `${column.name}(${column.type}) `)
      .join("| ");
    console.log("| " + columnHeaderString);

    for (const row of table.rows) {
      const columnValuesString = row.map((columnValue) => `'${columnValue}' `).join("| ");
      console.log("| " + columnValuesString);
    }
  }
}

在此处找到完整示例。

批处理日志查询

以下示例演示如何使用批处理查询 API 同时发送多个查询。 查询可以表示为对象的列表 BatchQuery

export async function main() {
  if (!monitorWorkspaceId) {
    throw new Error("MONITOR_WORKSPACE_ID must be set in the environment for this sample");
  }

  const tokenCredential = new DefaultAzureCredential();
  const logsQueryClient = new LogsQueryClient(tokenCredential);

  const kqlQuery = "AppEvents | project TimeGenerated, Name, AppRoleInstance | limit 1";
  const queriesBatch = [
    {
      workspaceId: monitorWorkspaceId,
      query: kqlQuery,
      timespan: { duration: "P1D" },
    },
    {
      workspaceId: monitorWorkspaceId,
      query: "AzureActivity | summarize count()",
      timespan: { duration: "PT1H" },
    },
    {
      workspaceId: monitorWorkspaceId,
      query:
        "AppRequests | take 10 | summarize avgRequestDuration=avg(DurationMs) by bin(TimeGenerated, 10m), _ResourceId",
      timespan: { duration: "PT1H" },
    },
    {
      workspaceId: monitorWorkspaceId,
      query: "AppRequests | take 2",
      timespan: { duration: "PT1H" },
      includeQueryStatistics: true,
    },
  ];

  const result = await logsQueryClient.queryBatch(queriesBatch);

  if (result == null) {
    throw new Error("No response for query");
  }

  let i = 0;
  for (const response of result) {
    console.log(`Results for query with query: ${queriesBatch[i]}`);
    if (response.status === LogsQueryResultStatus.Success) {
      console.log(
        `Printing results from query '${queriesBatch[i].query}' for '${queriesBatch[i].timespan}'`
      );
      processTables(response.tables);
    } else if (response.status === LogsQueryResultStatus.PartialFailure) {
      console.log(
        `Printing partial results from query '${queriesBatch[i].query}' for '${queriesBatch[i].timespan}'`
      );
      processTables(response.partialTables);
      console.log(
        ` Query had errors:${response.partialError.message} with code ${response.partialError.code}`
      );
    } else {
      console.log(`Printing errors from query '${queriesBatch[i].query}'`);
      console.log(` Query had errors:${response.message} with code ${response.code}`);
    }
    // next query
    i++;
  }
}

async function processTables(tablesFromResult: LogsTable[]) {
  for (const table of tablesFromResult) {
    const columnHeaderString = table.columnDescriptors
      .map((column) => `${column.name}(${column.type}) `)
      .join("| ");
    console.log("| " + columnHeaderString);

    for (const row of table.rows) {
      const columnValuesString = row.map((columnValue) => `'${columnValue}' `).join("| ");
      console.log("| " + columnValuesString);
    }
  }
}

处理日志批处理查询响应

queryBatchLogsQueryClient 函数返回 对象 LogsQueryBatchResultLogsQueryBatchResult 包含具有以下可能类型的 对象的列表:

  • LogsQueryPartialResult
  • LogsQuerySuccessfulResult
  • LogsQueryError

下面是响应的层次结构:

LogsQuerySuccessfulResult
|---statistics
|---visualization
|---status ("Success")
|---tables (list of `LogsTable` objects)
    |---name
    |---rows
    |---columnDescriptors (list of `LogsColumn` objects)
        |---name
        |---type

LogsQueryPartialResult
|---statistics
|---visualization
|---status ("PartialFailure")
|---partialError
    |--name
    |--code
    |--message
    |--stack
|---partialTables (list of `LogsTable` objects)
    |---name
    |---rows
    |---columnDescriptors (list of `LogsColumn` objects)
        |---name
        |---type

LogsQueryError
|--name
|--code
|--message
|--stack
|--status ("Failure")

例如,以下代码处理批处理日志查询响应:

async function processBatchResult(result: LogsQueryBatchResult) {
  let i = 0;
  for (const response of result) {
    console.log(`Results for query with query: ${queriesBatch[i]}`);
    if (response.status === LogsQueryResultStatus.Success) {
      console.log(
        `Printing results from query '${queriesBatch[i].query}' for '${queriesBatch[i].timespan}'`
      );
      processTables(response.tables);
    } else if (response.status === LogsQueryResultStatus.PartialFailure) {
      console.log(
        `Printing partial results from query '${queriesBatch[i].query}' for '${queriesBatch[i].timespan}'`
      );
      processTables(response.partialTables);
      console.log(
        ` Query had errors:${response.partialError.message} with code ${response.partialError.code}`
      );
    } else {
      console.log(`Printing errors from query '${queriesBatch[i].query}'`);
      console.log(` Query had errors:${response.message} with code ${response.code}`);
    }
    // next query
    i++;
  }
}

async function processTables(tablesFromResult: LogsTable[]) {
  for (const table of tablesFromResult) {
    const columnHeaderString = table.columnDescriptors
      .map((column) => `${column.name}(${column.type}) `)
      .join("| ");
    console.log("| " + columnHeaderString);

    for (const row of table.rows) {
      const columnValuesString = row.map((columnValue) => `'${columnValue}' `).join("| ");
      console.log("| " + columnValuesString);
    }
  }
}

在此处找到完整示例。

高级日志查询方案

设置日志查询超时

某些日志查询的执行时间超过 3 分钟。 默认服务器超时为 3 分钟。 可以将服务器超时增加到最多 10 分钟。 在以下示例中 LogsQueryOptions , 对象的 serverTimeoutInSeconds 属性用于将服务器超时增加到 10 分钟:

// setting optional parameters
const queryLogsOptions: LogsQueryOptions = {
  // explicitly control the amount of time the server can spend processing the query.
  serverTimeoutInSeconds: 600, // 600 seconds = 10 minutes
};

const result = await logsQueryClient.queryWorkspace(
  azureLogAnalyticsWorkspaceId,
  kustoQuery,
  { duration: Durations.twentyFourHours },
  queryLogsOptions
);

const tablesFromResult = result.tables;

查询多个工作区

可以在多个 Log Analytics 工作区中执行相同的日志查询。 除了 Kusto 查询之外,还需要以下参数:

  • workspaceId - 第一个 (主) 工作区 ID。
  • additionalWorkspaces - 工作区列表,不包括 参数中 workspaceId 提供的工作区。 参数的列表项可以包含以下标识符格式:
    • 限定的工作区名称
    • 工作区 ID
    • Azure 资源 ID

例如,以下查询在三个工作区中执行:

const queryLogsOptions: LogsQueryOptions = {
  additionalWorkspaces: ["<workspace2>", "<workspace3>"],
};

const kustoQuery = "AppEvents | limit 10";
const result = await logsQueryClient.queryWorkspace(
  azureLogAnalyticsWorkspaceId,
  kustoQuery,
  { duration: Durations.twentyFourHours },
  queryLogsOptions
);

若要查看每个工作区的结果,请使用 TenantId 列对结果进行排序或在 Kusto 查询中对其进行筛选。

按 TenantId 对结果进行排序

AppEvents | order by TenantId

按 TenantId 筛选结果

AppEvents | filter TenantId == "<workspace2>"

在此处找到完整示例。

包括统计信息

若要获取日志查询执行统计信息,例如 CPU 和内存消耗:

  1. LogsQueryOptions.includeQueryStatistics 属性设置为 true
  2. statistics访问 对象内的 LogsQueryResult 字段。

以下示例输出查询执行时间:

const workspaceId = "<workspace_id>";
const logsQueryClient = new LogsQueryClient(new DefaultAzureCredential());
const kustoQuery = "AzureActivity | top 10 by TimeGenerated";

const result = await logsQueryClient.queryWorkspace(
  monitorWorkspaceId,
  kustoQuery,
  { duration: Durations.oneDay },
  {
    includeQueryStatistics: true,
  }
);

const executionTime =
  result.statistics && result.statistics.query && result.statistics.query.executionTime;

console.log(
  `Results for query '${kustoQuery}', execution time: ${
    executionTime == null ? "unknown" : executionTime
  }`
);

由于有效负载的结构 statistics 因查询而异,因此 Record<string, unknown> 使用返回类型。 它包含原始 JSON 响应。 统计信息位于 JSON 的 属性中 query 。 例如:

{
  "query": {
    "executionTime": 0.0156478,
    "resourceUsage": {...},
    "inputDatasetStatistics": {...},
    "datasetStatistics": [{...}]
  }
}

包括可视化效果

若要使用 render 运算符获取日志查询的可视化数据,请执行以下操作:

  1. LogsQueryOptions.includeVisualization 属性设置为 true
  2. visualization访问 对象内的 LogsQueryResult 字段。

例如:

const workspaceId = "<workspace_id>";
const logsQueryClient = new LogsQueryClient(new DefaultAzureCredential());

const result = await logsQueryClient.queryWorkspace(
    monitorWorkspaceId,
    @"StormEvents
        | summarize event_count = count() by State
        | where event_count > 10
        | project State, event_count
        | render columnchart",
    { duration: Durations.oneDay },
    {
      includeVisualization: true
    }
  );
console.log("visualization result:", result.visualization);

由于有效负载的结构 visualization 因查询而异,因此 Record<string, unknown> 使用返回类型。 它包含原始 JSON 响应。 例如:

{
  "visualization": "columnchart",
  "title": "the chart title",
  "accumulate": false,
  "isQuerySorted": false,
  "kind": null,
  "legend": null,
  "series": null,
  "yMin": "NaN",
  "yMax": "NaN",
  "xAxis": null,
  "xColumn": null,
  "xTitle": "x axis title",
  "yAxis": null,
  "yColumns": null,
  "ySplit": null,
  "yTitle": null,
  "anomalyColumns": null
}

指标查询

以下示例获取 Azure 指标顾问订阅的 指标。 资源 URI 必须是要查询其指标的资源的 URI。 它通常采用 格式 /subscriptions/<id>/resourceGroups/<rg-name>/providers/<source>/topics/<resource-name>

查找资源 URI:

  1. 导航到Azure 门户中的资源页。
  2. “概述 ”边栏选项卡中,选择“ JSON 视图” 链接。
  3. 在生成的 JSON 中,复制 属性的值 id
import { DefaultAzureCredential } from "@azure/identity";
import { Durations, Metric, MetricsQueryClient } from "@azure/monitor-query";
import * as dotenv from "dotenv";

dotenv.config();

const metricsResourceId = process.env.METRICS_RESOURCE_ID;

export async function main() {
  const tokenCredential = new DefaultAzureCredential();
  const metricsQueryClient = new MetricsQueryClient(tokenCredential);

  if (!metricsResourceId) {
    throw new Error("METRICS_RESOURCE_ID must be set in the environment for this sample");
  }

  const iterator = metricsQueryClient.listMetricDefinitions(metricsResourceId);
  let result = await iterator.next();
  let metricNames: string[] = [];
  for await (const result of iterator) {
    console.log(` metricDefinitions - ${result.id}, ${result.name}`);
    if (result.name) {
      metricNames.push(result.name);
    }
  }
  const firstMetricName = metricNames[0];
  const secondMetricName = metricNames[1];
  if (firstMetricName && secondMetricName) {
    console.log(`Picking an example metric to query: ${firstMetricName} and ${secondMetricName}`);
    const metricsResponse = await metricsQueryClient.queryResource(
      metricsResourceId,
      [firstMetricName, secondMetricName],
      {
        granularity: "PT1M",
        timespan: { duration: Durations.fiveMinutes },
      }
    );

    console.log(
      `Query cost: ${metricsResponse.cost}, interval: ${metricsResponse.granularity}, time span: ${metricsResponse.timespan}`
    );

    const metrics: Metric[] = metricsResponse.metrics;
    console.log(`Metrics:`, JSON.stringify(metrics, undefined, 2));
    const metric = metricsResponse.getMetricByName(firstMetricName);
    console.log(`Selected Metric: ${firstMetricName}`, JSON.stringify(metric, undefined, 2));
  } else {
    console.error(`Metric names are not defined - ${firstMetricName} and ${secondMetricName}`);
  }
}

main().catch((err) => {
  console.error("The sample encountered an error:", err);
  process.exit(1);
});

在前面的示例中,指标结果 metricsResponse 是根据用户在函数的数组参数中 metricNames 指定指标名称的顺序排序的 queryResource 。 如果用户指定 [firstMetricName, secondMetricName],则 的结果 firstMetricName 将显示在 中 的 secondMetricName 结果之前 metricResponse

处理指标查询响应

指标 queryResource 函数返回 对象 QueryMetricsResult 。 对象QueryMetricsResult包含一些属性,例如类型化对象、intervalnamespacetimespan的列表MetricMetric可以使用 属性访问metrics对象列表。 此列表中的每个对象都包含 Metric 一个 TimeSeriesElement 对象列表。 每个 都包含 TimeSeriesElementdatametadataValues 属性。 在可视形式中,响应的对象层次结构类似于以下结构:

QueryMetricsResult
|---cost
|---timespan (of type `QueryTimeInterval`)
|---granularity
|---namespace
|---resourceRegion
|---metrics (list of `Metric` objects)
    |---id
    |---type
    |---name
    |---unit
    |---displayDescription
    |---errorCode
    |---timeseries (list of `TimeSeriesElement` objects)
        |---metadataValues
        |---data (list of data points represented by `MetricValue` objects)
            |---timeStamp
            |---average
            |---minimum
            |---maximum
            |---total
            |---count
|---getMetricByName(metricName): Metric | undefined (convenience method)

处理响应的示例

import { DefaultAzureCredential } from "@azure/identity";
import { Durations, Metric, MetricsQueryClient } from "@azure/monitor-query";
import * as dotenv from "dotenv";
dotenv.config();

const metricsResourceId = process.env.METRICS_RESOURCE_ID;
export async function main() {
  const tokenCredential = new DefaultAzureCredential();
  const metricsQueryClient = new MetricsQueryClient(tokenCredential);

  if (!metricsResourceId) {
    throw new Error(
      "METRICS_RESOURCE_ID for an Azure Metrics Advisor subscription must be set in the environment for this sample"
    );
  }

  console.log(`Picking an example metric to query: MatchedEventCount`);

  const metricsResponse = await metricsQueryClient.queryResource(
    metricsResourceId,
    ["MatchedEventCount"],
    {
      timespan: {
        duration: Durations.fiveMinutes,
      },
      granularity: "PT1M",
      aggregations: ["Count"],
    }
  );

  console.log(
    `Query cost: ${metricsResponse.cost}, granularity: ${metricsResponse.granularity}, time span: ${metricsResponse.timespan}`
  );

  const metrics: Metric[] = metricsResponse.metrics;
  for (const metric of metrics) {
    console.log(metric.name);
    for (const timeseriesElement of metric.timeseries) {
      for (const metricValue of timeseriesElement.data!) {
        if (metricValue.count !== 0) {
          console.log(`There are ${metricValue.count} matched events at ${metricValue.timeStamp}`);
        }
      }
    }
  }
}

main().catch((err) => {
  console.error("The sample encountered an error:", err);
  process.exit(1);
});

在此处找到完整示例。

查询多个资源的指标

若要在单个请求中查询多个 Azure 资源的指标,请使用 MetricsQueryClient.queryResources 方法。 此方法:

  • 调用与 MetricsQueryClient 方法不同的 API。
  • 创建客户端时需要区域终结点。 例如,"https://westus3.metrics.monitor.azure.com"。

每个 Azure 资源必须驻留在以下位置:

  • 与创建客户端时指定的终结点相同的区域。
  • 相同的 Azure 订阅。

此外,必须提供包含要查询的指标的指标命名空间。 有关指标命名空间的列表,请参阅 支持的指标和日志类别(按资源类型)。

let resourceIds: string[] = [
  "/subscriptions/0000000-0000-000-0000-000000/resourceGroups/test/providers/Microsoft.OperationalInsights/workspaces/test-logs",
  "/subscriptions/0000000-0000-000-0000-000000/resourceGroups/test/providers/Microsoft.OperationalInsights/workspaces/test-logs2",
];
let metricsNamespace: string = "<YOUR_METRICS_NAMESPACE>";
let metricNames: string[] = ["requests", "count"];
const batchEndPoint: string = "<YOUR_METRICS_ENDPOINT>"; //for example, https://eastus.metrics.monitor.azure.com/

const credential = new DefaultAzureCredential();
const metricsQueryClient: MetricsQueryClient = new MetricsQueryClient(
  batchEndPoint,
  credential
);

const result: : MetricsQueryResult[] = await metricsQueryClient.queryResources(
  resourceIds,
  metricsNamespace,
  metricNames
);

有关可用于每种 Azure 资源类型的指标和维度的清单,请参阅 Azure Monitor 支持的指标

故障排除

若要诊断各种故障情况,请参阅 故障排除指南

后续步骤

若要了解有关 Azure Monitor 的详细信息,请参阅 Azure Monitor 服务文档

贡献

若要为此库做出贡献,请阅读贡献指南,详细了解如何生成和测试代码。

此模块的测试是实时测试和单元测试的混合,这要求你有一个 Azure Monitor 实例。 若要执行测试,需要运行:

  1. rush update
  2. rush build -t @azure/monitor-query
  3. cd into sdk/monitor/monitor-query
  4. sample.env 文件复制到 .env
  5. .env 编辑器中打开文件并填写值。
  6. npm run test.

有关更多详细信息,请查看 测试 文件夹。

曝光数