共用方式為


已棄用 ⚠️:此套件已棄用,且不再處於主動開發階段。 請移轉至下列套件:

新功能和非安全性錯誤修正將新增至上面列出的替代程式庫。

Azure Monitor 查詢用戶端庫用於對 Azure Monitor 的兩個數據平台執行只讀查詢:

  • 日誌 - 從受監控的資源中收集和組織日誌和性能數據。 來自不同來源的數據(例如 Azure 服務中的平臺日誌、虛擬機代理中的日誌和性能數據以及應用中的使用方式和性能數據)可以合併到單個 Azure Log Analytics 工作區中。 可以使用 Kusto 查詢語言一起分析各種數據類型。
  • Metrics (指標) – 將受監控資源中的數值資料收集到時間序列資料庫中。 計量是定期收集的數值,並在特定時間描述系統的某些層面。 計量是輕量型且能夠支援近乎即時的案例,因此有助於警示和快速偵測問題。

資源:

開始

支援的環境

如需詳細資訊,請參閱我們的 支持原則

先決條件

安裝套件

使用 npm 安裝適用於 JavaScript 的 Azure 監視器查詢客戶端連結庫:

npm install --save @azure/monitor-query

建立用戶端

需要已驗證的用戶端才能查詢記錄或計量。 為了進行身份驗證,以下示例使用 @azure/identity 包中的DefaultAzureCredential

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

const credential = new DefaultAzureCredential();

// Create a LogsQueryClient
const logsQueryClient = new LogsQueryClient(credential);

// Create a MetricsQueryClient
const metricsQueryClient = new MetricsQueryClient(credential);

// Create a MetricsClient
const endpoint = " https://<endpoint>.monitor.azure.com/";
const metricsClient = new MetricsClient(endpoint, credential);

設定 Azure 主權雲端的用戶端

根據預設,連結庫的用戶端會設定為使用 Azure 公用雲端。 若要改用主權雲端,請在具現化用戶端時提供正確的端點和物件值。 例如:

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

const credential = new DefaultAzureCredential();

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

// Create a MetricsQueryClient
const metricsQueryClient: MetricsQueryClient = new MetricsQueryClient(credential, {
  endpoint: "https://management.chinacloudapi.cn",
  audience: "https://monitor.azure.cn/.default",
});

// Create a MetricsClient
const endpoint = " https://<endpoint>.monitor.azure.cn/";
const metricsClient = new MetricsClient(endpoint, credential, {
  audience: "https://monitor.azure.cn/.default",
});

注意:目前, MetricsQueryClient 使用 Azure Resource Manager (ARM) 終端節點來查詢指標。 當您使用此用戶端時,您需要雲端的對應管理端點。 此詳細數據未來可能會有所變更。

執行查詢

有關 Logs 和 Metrics 查詢的範例,請參閱 範例 部分。

重要概念

記錄查詢速率限制和節流

當要求速率太高時,Log Analytics 服務會套用節流。 Kusto 查詢也會套用限制,例如傳回的數據列數目上限。 有關更多資訊,請參閱 查詢 API

計量數據結構

每一組計量值都是具有下列特性的時間序列:

  • 收集值的時間
  • 與值相關聯的資源
  • 命名空間,其作用就像計量的類別
  • 計量名稱
  • 值本身
  • 某些計量具有多個維度,如多維度計量中所述。 自定義計量最多可以有10個維度。

例子

記錄查詢

可用於 LogsQueryClient 使用 Kusto 查詢語言查詢 Log Analytics 工作區。 可以 timespan.duration 指定為 ISO 8601 持續時間格式的字串。 您可以使用 Durations 為一些常用的 ISO 8601 持續時間提供的常量。

您可以透過Log Analytics工作區識別碼或 Azure 資源識別碼來查詢記錄。 結果會以具有數據列集合的數據表的形式傳回。

以工作區為中心的記錄查詢

要按工作區 ID 查詢,請使用以下 LogsQueryClient.queryWorkspace 方法:

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

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

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

if (result.status === LogsQueryResultStatus.Success) {
  const tablesFromResult = 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);
  }
}

function processTables(tablesFromResult) {
  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);
    }
  }
}

以資源為中心的記錄查詢

下列範例示範如何直接從 Azure 資源查詢記錄。 此處使用 queryResource 該方法並傳入 Azure 資源 ID。 例如: /subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}

若要尋找資源識別碼:

  1. 流覽至 Azure 入口網站中的資源頁面。
  2. 在「 概述 」邊欄選項卡中,選擇「 JSON 檢視 」連結。
  3. 在生成的 JSON 中,複製屬性的值 id
import { DefaultAzureCredential } from "@azure/identity";
import { LogsQueryClient, Durations, LogsQueryResultStatus } from "@azure/monitor-query";

const logsResourceId = "<the Resource Id for your logs resource>";

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

const kustoQuery = `MyTable_CL | summarize count()`;

console.log(`Running '${kustoQuery}' over the last One Hour`);
const queryLogsOptions = {
  // 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 as any)?.statistics?.query?.executionTime;

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

if (result.status === LogsQueryResultStatus.Success) {
  const tablesFromResult = 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);
  }
}

function processTables(tablesFromResult) {
  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);
    }
  }
}

處理記錄查詢回應

函數 queryWorkspace of LogsQueryClient 返回一個 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

例如,若要處理含有資料表的回應:

function processTables(tablesFromResult) {
  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

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

const monitorWorkspaceId = "<workspace_id>";

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++;
}

function processTables(tablesFromResult) {
  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);
    }
  }
}

處理記錄批次查詢回應

函數 queryBatch of LogsQueryClient 返回一個 LogsQueryBatchResult 物件。 LogsQueryBatchResult 包含具有以下可能類型的物件清單:

  • 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")

例如,下列程式代碼會處理批次記錄查詢回應:

import { LogsQueryResultStatus } from "@azure/monitor-query";

async function processBatchResult(result, queriesBatch) {
  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++;
  }
}

function processTables(tablesFromResult) {
  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 分鐘:

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

const azureLogAnalyticsWorkspaceId = "<workspace_id>";

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

const kqlQuery = "AppEvents | project TimeGenerated, Name, AppRoleInstance | limit 1";

// setting optional parameters
const queryLogsOptions = {
  // 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,
  kqlQuery,
  { duration: Durations.twentyFourHours },
  queryLogsOptions,
);

const status = result.status;

查詢多個工作區

相同的記錄查詢可以跨多個Log Analytics工作區執行。 除了 Kusto 查詢之外,還需要下列參數:

  • workspaceId - 第一個(主要)工作區ID。
  • additionalWorkspaces - 工作區清單,不包括參數中提供的 workspaceId 工作區。 參數的清單專案可以包含下列識別碼格式:
    • 限定的工作區名稱
    • 工作區標識碼
    • Azure 資源標識碼

例如,下列查詢會在三個工作區中執行:

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

const azureLogAnalyticsWorkspaceId = "<workspace_id>";

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

const kqlQuery = "AppEvents | project TimeGenerated, Name, AppRoleInstance | limit 1";

// setting optional parameters
const queryLogsOptions = {
  additionalWorkspaces: ["<workspace2>", "<workspace3>"],
};

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

const status = result.status;

若要查看每個工作區的結果,請使用該 TenantId 列對結果進行排序或在 Kusto 查詢中篩選結果。

按 TenantId 對結果進行排序

AppEvents | order by TenantId

按 TenantId 篩選結果

AppEvents | filter TenantId == "<workspace2>"

可以 在此處找到完整的範例。

包含統計數據

若要取得記錄查詢執行統計數據,例如 CPU 和記憶體耗用量:

  1. LogsQueryOptions.includeQueryStatistics 屬性設定為 true
  2. statistics訪問物件內的LogsQueryResult欄位。

下列範例會列印查詢執行時間:

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

const monitorWorkspaceId = "<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 as any)?.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欄位。

例如:

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

const monitorWorkspaceId = "<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 { MetricsQueryClient, Durations } from "@azure/monitor-query";

const metricsResourceId = "<the Resource Id for your metrics resource>";

const tokenCredential = new DefaultAzureCredential();
const metricsQueryClient = new MetricsQueryClient(tokenCredential);

const metricNames = [];
const metricDefinitions = metricsQueryClient.listMetricDefinitions(metricsResourceId);
for await (const { id, name } of metricDefinitions) {
  console.log(` metricDefinitions - ${id}, ${name}`);
  if (name) {
    metricNames.push(name);
  }
}

const [firstMetricName, secondMetricName] = metricNames;
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 = 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}`);
}

在前面的示例中,metric 結果metricsResponse根據使用者在函數的 metricNames array 參數中queryResource指定 metric 名稱的順序進行排序。 如果使用者指定 [firstMetricName, secondMetricName],則 的結果firstMetricName將出現在 的結果 for secondMetricName 之前。metricResponse

處理計量查詢回應

metrics queryResource 函數返回一個 QueryMetricsResult 物件。 這個 QueryMetricsResult 物件包含屬性,例如類型物件清單 MetricintervalnamespacetimespanMetric可以使用 property 訪問 metrics objects 清單。 此清單中的每個 Metric 物件都包含一個物件清單 TimeSeriesElement 。 每個 TimeSeriesElement contains datametadataValues properties. 在視覺化形式中,回應的物件階層類似下列結構:

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 { MetricsQueryClient, Durations } from "@azure/monitor-query";

const metricsResourceId = "<the Resource Id for your metrics resource>";

const tokenCredential = new DefaultAzureCredential();
const metricsQueryClient = new MetricsQueryClient(tokenCredential);

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 = 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}`);
      }
    }
  }
}

可以 在此處找到完整的範例。

查詢多個資源的計量

若要在單個請求中查詢多個 Azure 資源的指標,請使用該方法 MetricsClient.queryResources 。 此方法:

  • 調用與方法不同的 API MetricsClient
  • 建立用戶端時需要區域端點。 例如,“https://westus3.metrics.monitor.azure.com"。

每個 Azure 資源都必須位於:

  • 與建立用戶端時所指定的端點相同的區域。
  • 相同的 Azure 訂用帳戶。

此外:

import { DefaultAzureCredential } from "@azure/identity";
import { MetricsClient } from "@azure/monitor-query";

const resourceIds = [
  "/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",
];
const metricsNamespace = "<YOUR_METRICS_NAMESPACE>";
const metricNames = ["requests", "count"];
const endpoint = " https://<endpoint>.monitor.azure.com/";

const credential = new DefaultAzureCredential();
const metricsClient = new MetricsClient(endpoint, credential);

const result = await metricsClient.queryResources(resourceIds, metricNames, metricsNamespace);

有關可用於每種 Azure 資源類型的指標和維度的清單,請參閱 Azure Monitor 支援的指標

故障排除

要診斷各種故障場景,請參閱 故障排除指南

後續步驟

若要瞭解有關 Azure Monitor 的詳細資訊,請參閱 Azure Monitor 服務文檔

貢獻

如果您想要參與此連結庫,請閱讀 參與指南 ,以深入瞭解如何建置和測試程序代碼。

本課程模組的測試是即時和單元測試的混合,需要您擁有 Azure 監視器實例。 若要執行測試,您必須執行:

  1. pnpm install
  2. pnpm build --filter @azure/monitor-query...
  3. cd into sdk/monitor/monitor-query
  4. sample.env 檔案複製到 .env
  5. .env在編輯器中打開檔並填寫值。
  6. npm run test

有關更多詳細資訊,請查看我們的 tests 資料夾。