JavaScript için Azure İzleyici Sorgu istemci kitaplığı - sürüm 1.2.0

Azure İzleyici Sorgusu istemci kitaplığı, Azure İzleyici'nin iki veri platformunda salt okunur sorgular yürütmek için kullanılır:

  • Günlükler - İzlenen kaynaklardan günlük ve performans verilerini toplar ve düzenler. Azure hizmetlerinden platform günlükleri, sanal makine aracılarından günlük ve performans verileri ve uygulamalardan gelen kullanım ve performans verileri gibi farklı kaynaklardan gelen veriler tek bir Azure Log Analytics çalışma alanında birleştirilebilir. Çeşitli veri türleri Kusto Sorgu Dili kullanılarak birlikte analiz edilebilir.
  • Ölçümler - İzlenen kaynaklardan bir zaman serisi veritabanına sayısal veriler toplar. Ölçümler, düzenli aralıklarla toplanan ve belirli bir zamanda sistemin bazı yönlerini açıklayan sayısal değerlerdir. Ölçümler hafiftir ve gerçek zamanlıya yakın senaryoları destekleyerek sorunları uyarmak ve hızlı algılamak için kullanışlıdır.

Kaynaklar:

Başlarken

Desteklenen ortamlar

Daha fazla bilgi için destek ilkemize bakın.

Önkoşullar

Paketi yükleme

npm ile JavaScript için Azure İzleyici Sorgusu istemci kitaplığını yükleyin:

npm install @azure/monitor-query

İstemci oluşturma

Günlükleri veya Ölçümleri sorgulamak için kimliği doğrulanmış bir istemci gerekir. Aşağıdaki örnekte kimlik doğrulaması için @azure/identity paketinden DefaultAzureCredential kullanılır.

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 bağımsız bulutu için istemci yapılandırma

varsayılan olarak LogsQueryClient ve MetricsQueryClient Azure Genel Bulutu kullanacak şekilde yapılandırılır. Bunun yerine bağımsız bir bulut kullanmak için doğru endpoint bağımsız değişkeni sağlayın. Örnek:

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",
});

Not: Şu anda MetricsQueryClient ölçümleri sorgulamak için Azure Resource Manager (ARM) uç noktasını kullanmaktadır. Bu istemciyi kullanırken bulutunuz için karşılık gelen yönetim uç noktasına ihtiyacınız vardır. Bu ayrıntı gelecekte değişebilir.

Sorguyu yürütün

Günlükler ve Ölçümler sorgusu örnekleri için Örnekler bölümüne bakın.

Önemli kavramlar

Sorgu hızı sınırlarını ve azaltmayı günlüğe kaydeder

İstek oranı çok yüksek olduğunda Log Analytics hizmeti azaltma uygular. Döndürülen en fazla satır sayısı gibi sınırlar Kusto sorgularına da uygulanır. Daha fazla bilgi için bkz . Sorgu API'si.

Ölçüm veri yapısı

Her ölçüm değeri kümesi, aşağıdaki özelliklere sahip bir zaman serisidir:

  • Değerin toplandığı saat
  • Değerle ilişkili kaynak
  • Ölçüm için bir kategori gibi davranan bir ad alanı
  • Ölçüm adı
  • Değerin kendisi
  • Bazı ölçümlerin çok boyutlu ölçümlerde açıklandığı gibi birden çok boyutu vardır. Özel ölçümlerin en fazla 10 boyutu olabilir.

Örnekler

Günlükler sorgusu

Kusto Sorgu DiliLogsQueryClient kullanarak Log Analytics çalışma alanını sorgulamak için kullanılabilir. , timespan.duration ISO 8601 süre biçiminde bir dize olarak belirtilebilir. Yaygın olarak kullanılan bazı ISO 8601 süreleri için sağlanan sabitleri kullanabilirsiniz Durations .

Günlükleri çalışma alanı kimliğine veya kaynak kimliğine göre sorgulayabilirsiniz. Sonuç, satır koleksiyonuna sahip bir tablo olarak döndürülür.

Çalışma alanı merkezli günlükler sorgusu

Çalışma alanı kimliğine göre sorgulamak için yöntemini kullanın 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));

Kaynak merkezli günlükler sorgusu

Aşağıdaki örnekte, günlüklerin doğrudan bir Azure kaynağından nasıl sorgu yapılacağı gösterilmektedir. queryResource Burada yöntemi kullanılır ve bir Azure kaynak kimliği geçirilir. Örneğin, /subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}.

Kaynak kimliğini bulmak için:

  1. Azure portal kaynağınızın sayfasına gidin.
  2. Genel Bakış dikey penceresinde JSON Görünümü bağlantısını seçin.
  3. Sonuçta elde edilen JSON'da özelliğinin id değerini kopyalayın.
/**
 * @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);
});

Günlükleri işleme sorgu yanıtı

queryWorkspace işlevi LogsQueryClient bir LogsQueryResult nesnesi döndürür. Nesne türü veya LogsQueryPartialResultolabilirLogsQuerySuccessfulResult. Yanıtın hiyerarşisi aşağıdadır:

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

Örneğin, bir yanıtı tablolarla işlemek için:

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

Tam bir örnek burada bulunabilir.

Batch günlükleri sorgusu

Aşağıdaki örnek, toplu sorgu API'sini kullanarak aynı anda birden çok sorgu göndermeyi gösterir. Sorgular bir nesne listesi BatchQuery olarak temsil edilebilir.

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

Günlükleri işleme toplu sorgu yanıtı

queryBatch işlevi LogsQueryClient bir LogsQueryBatchResult nesnesi döndürür. LogsQueryBatchResult aşağıdaki olası türlere sahip nesnelerin listesini içerir:

  • LogsQueryPartialResult
  • LogsQuerySuccessfulResult
  • LogsQueryError

Yanıtın hiyerarşisi aşağıdadır:

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

Örneğin, aşağıdaki kod bir toplu iş günlükleri sorgu yanıtını işler:

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

Tam bir örnek burada bulunabilir.

Gelişmiş günlükler sorgu senaryoları

Günlükleri ayarlama sorgusu zaman aşımı

Bazı günlük sorgularının yürütülmesi 3 dakikadan uzun sürer. Varsayılan sunucu zaman aşımı 3 dakikadır. Sunucu zaman aşımını en fazla 10 dakikaya çıkarabilirsiniz. Aşağıdaki örnekte, nesnenin LogsQueryOptionsserverTimeoutInSeconds özelliği sunucu zaman aşımını 10 dakikaya yükseltmek için kullanılır:

// 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;

Birden çok çalışma alanını sorgulama

Aynı günlük sorgusu birden çok Log Analytics çalışma alanında yürütülebilir. Kusto sorgusuna ek olarak aşağıdaki parametreler de gereklidir:

  • workspaceId - İlk (birincil) çalışma alanı kimliği.
  • additionalWorkspaces - Parametresinde sağlanan çalışma alanı dışında kalan çalışma alanlarının workspaceId listesi. Parametrenin liste öğeleri aşağıdaki tanımlayıcı biçimlerinden oluşabilir:
    • Nitelikli çalışma alanı adları
    • Çalışma Alanı Kimlikleri
    • Azure kaynak kimlikleri

Örneğin, aşağıdaki sorgu üç çalışma alanında yürütülür:

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

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

Her çalışma alanının sonuçlarını görüntülemek için, sonuçları sıralamak veya Kusto sorgusunda filtrelemek için sütununu kullanın TenantId .

Sonuçları TenantId'ye göre sıralama

AppEvents | order by TenantId

Sonuçları TenantId'ye göre filtreleme

AppEvents | filter TenantId == "<workspace2>"

Tam bir örnek burada bulunabilir.

İstatistikleri dahil et

Günlükleri almak için CPU ve bellek tüketimi gibi sorgu yürütme istatistikleri:

  1. LogsQueryOptions.includeQueryStatistics özelliğini olarak trueayarlayın.
  2. Nesnenin statistics içindeki alana erişin LogsQueryResult .

Aşağıdaki örnek, sorgu yürütme süresini yazdırır:

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

Yükün yapısı sorguya statistics göre değiştiğinden bir Record<string, unknown> dönüş türü kullanılır. Ham JSON yanıtını içerir. İstatistikler JSON özelliğinin içinde query bulunur. Örnek:

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

Görselleştirme ekle

İşleme işlecini kullanarak günlük sorgularının görselleştirme verilerini almak için:

  1. LogsQueryOptions.includeVisualization özelliğini olarak trueayarlayın.
  2. Nesnenin visualization içindeki alana erişin LogsQueryResult .

Örnek:

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);

Yükün yapısı sorguya visualization göre değiştiğinden bir Record<string, unknown> dönüş türü kullanılır. Ham JSON yanıtını içerir. Örnek:

{
  "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
}

Ölçümler sorgusu

Aşağıdaki örnek, Azure Ölçüm Danışmanı aboneliğinin ölçümlerini alır. Kaynak URI'sinin ölçümlerin sorgulandığı kaynak olması gerekir. Normalde biçimindedir /subscriptions/<id>/resourceGroups/<rg-name>/providers/<source>/topics/<resource-name>.

Kaynak URI'sini bulmak için:

  1. Azure portal kaynağınızın sayfasına gidin.
  2. Genel Bakış dikey penceresinde JSON Görünümü bağlantısını seçin.
  3. Sonuçta elde edilen JSON'da özelliğinin id değerini kopyalayın.
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);
});

Yukarıdaki örnekte, içindeki metricsResponse ölçüm sonuçları, kullanıcının işlev için queryResource dizi bağımsız değişkeninde metricNames ölçüm adlarını belirttiği sıraya göre sıralanır. Kullanıcı belirtirse [firstMetricName, secondMetricName], için sonucu firstMetricName içinde sonucundan secondMetricNamemetricResponseönce görünür.

Ölçüm sorgu yanıtını işleme

Metrics queryResource işlevi bir QueryMetricsResult nesne döndürür. QueryMetricsResult nesnesi, -typed nesneleri listesiMetric, interval, namespaceve timespangibi özellikler içerir. Metric Nesneler listesine özelliği kullanılarak metrics erişilebilir. Bu listedeki her Metric nesne bir nesne listesi TimeSeriesElement içerir. Her TimeSeriesElement birinin ve özellikleri vardır datametadataValues . Görsel biçimde, yanıtın nesne hiyerarşisi aşağıdaki yapıya benzer:

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)

Yanıtı işleme örneği

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

Tam bir örnek burada bulunabilir.

Birden çok kaynak için sorgu ölçümleri

Tek bir istekte birden çok Azure kaynağının ölçümlerini sorgulamak MetricsQueryClient.queryResources için yöntemini kullanın. Bu yöntem:

  • Yöntemlerden MetricsQueryClient farklı bir API çağırır.
  • İstemciyi oluştururken bölgesel bir uç nokta gerektirir. Örneğin, "https://westus3.metrics.monitor.azure.com".

Her Azure kaynağının şu durumlarda bulunması gerekir:

  • İstemci oluşturulurken belirtilen uç noktayla aynı bölge.
  • Aynı Azure aboneliği.

Ayrıca sorgulanacak ölçümleri içeren ölçüm ad alanı da sağlanmalıdır. Ölçüm ad alanlarının listesi için bkz . Kaynak türüne göre desteklenen ölçümler ve günlük kategorileri.

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
);

Her Azure kaynak türü için kullanılabilen ölçümlerin ve boyutların envanteri için bkz. Azure İzleyici ile desteklenen ölçümler.

Sorun giderme

Çeşitli hata senaryolarını tanılamak için sorun giderme kılavuzuna bakın.

Sonraki adımlar

Azure İzleyici hakkında daha fazla bilgi edinmek için Bkz. Azure İzleyici hizmeti belgeleri.

Katkıda bulunma

Bu kitaplığa katkıda bulunmak isterseniz, kodu derleme ve test etme hakkında daha fazla bilgi edinmek için lütfen katkıda bulunma kılavuzunu okuyun.

Bu modülün testleri, bir Azure İzleyici örneğine sahip olmanız gereken canlı ve birim testlerinin bir karışımıdır. Testleri yürütmek için şunları çalıştırmanız gerekir:

  1. rush update
  2. rush build -t @azure/monitor-query
  3. cd into sdk/monitor/monitor-query
  4. Dosyayı şu dosyaya sample.env kopyalayın: .env
  5. .env Dosyayı bir düzenleyicide açın ve değerleri doldurun.
  6. npm run test.

Diğer ayrıntılar için testler klasörümüzü görüntüleyin.

İzlenimler