Not
Bu sayfaya erişim yetkilendirme gerektiriyor. Oturum açmayı veya dizinleri değiştirmeyi deneyebilirsiniz.
Bu sayfaya erişim yetkilendirme gerektiriyor. Dizinleri değiştirmeyi deneyebilirsiniz.
LogsQueryClient:@azure/monitor-query-logs- geçiş kılavuzu: Sorgu Günlükleri geçişini izleme • npm: @azure/monitor-query-logsMetricsClient:@azure/monitor-query-metrics- geçiş kılavuzu: Sorgu Metrikleri geçişini izleme • npm: @azure/monitor-query-metricsMetricsQueryClient: Yönetim kitaplığına@azure/arm-monitorgeçiş - kılavuz: MetricsQueryClient → @azure/arm-monitorYeni özellikler ve güvenlikle ilgili olmayan hata düzeltmeleri, yukarıda listelenen değiştirme kitaplıklarına eklenecektir.
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 sayısal verileri bir zaman serisi veritabanına toplar. Ölçümler, düzenli aralıklarla toplanan ve belirli bir zamanda sistemin bazı yönlerini açıklayan sayısal değerlerdir. Ölçümler basittir ve neredeyse gerçek zamanlı senaryoları destekleyerek sorunları uyarmak ve hızlı algılamak için kullanışlı hale getirir.
Kaynaklar:
Başlarken
Desteklenen ortamlar
- Node.js LTS sürümleri
- Safari, Chrome, Microsoft Edge ve Firefox'un en son sürümleri
Daha fazla bilgi için
Önkoşullar
- Azure aboneliği
- Azure Kimlik kitaplığı kimlik bilgisi türügibi bir TokenCredential uygulaması.
- Günlükleri sorgulamak için aşağıdakilerden birine ihtiyacınız vardır:
- Azure Log Analytics çalışma alanı
- Her türlü Azure kaynağı (Depolama Hesabı, Key Vault, Cosmos DB vb.)
- Ölçümleri sorgulamak için her türlü Azure kaynağına (Depolama Hesabı, Key Vault, Cosmos DB vb.) ihtiyacınız vardır.
Paketi yükleme
npm ile JavaScript için Azure İzleyici Sorgusu istemci kitaplığını yükleyin:
npm install --save @azure/monitor-query
İstemciyi oluşturma
Günlükleri veya Ölçümleri sorgulamak için kimliği doğrulanmış bir istemci gerekir. Kimlik doğrulaması için aşağıdaki örnek, @azure/identity paketinden DefaultAzureCredential kullanır.
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 bağımsız bulutu için istemci yapılandırma
Varsayılan olarak, kitaplığın istemcileri Azure Genel Bulutu kullanacak şekilde yapılandırılır. Bunun yerine bağımsız bir bulut kullanmak için, istemci örneği oluştururken doğru uç nokta ve hedef kitle değerini sağlayın. Mesela:
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",
});
Not: Şu anda MetricsQueryClient ölçümleri sorgulamak için Azure Resource Manager (ARM) uç noktasını kullanır. Bu istemciyi kullanırken bulutunuz için ilgili yönetim uç noktasına ihtiyacınız vardır. Bu ayrıntı gelecekte değişebilir.
Sorguyu yürütme
Günlükler ve Ölçüm sorgularının örnekleri için Örnekler bölümüne bakın.
Temel kavramlar
Sorgu hızı sınırlarını ve azaltmayı günlüğe kaydeder
Log Analytics hizmeti, istek oranı çok yüksek olduğunda 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çümler 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şkilendirilmiş 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çümler en fazla 10 boyuta sahip olabilir.
Örnekler
Günlükler sorgusu
LogsQueryClient
Sorgu Dili'ni kullanarak bir Log Analytics çalışma alanını sorgulamak için kullanılabilir. ISO timespan.duration 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 Log Analytics çalışma alanı kimliğine veya Azure 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 şu LogsQueryClient.queryWorkspace yöntemi kullanın:
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);
}
}
}
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öntem 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:
- Azure portalında kaynağınızın sayfasına gidin.
- Genel Bakış dikey penceresinde JSON Görünümü bağlantısını seçin.
- Sonuçta elde edilen JSON'da özelliğin değerini
idkopyalayın.
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);
}
}
}
Günlükleri işleme sorgu yanıtı
fonksiyonu queryWorkspaceLogsQueryClient bir LogsQueryResult nesneyi döndürür. Nesne türü veya LogsQuerySuccessfulResultolabilirLogsQueryPartialResult. 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:
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);
}
}
}
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 gösterilebilir.
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);
}
}
}
Günlükleri işleme toplu sorgu yanıtı
fonksiyonu queryBatchLogsQueryClient bir LogsQueryBatchResult nesneyi döndürür.
LogsQueryBatchResult Aşağıdaki olası türlere sahip nesnelerin listesini içerir:
LogsQueryPartialResultLogsQuerySuccessfulResultLogsQueryError
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:
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);
}
}
}
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, LogsQueryOptions sunucu zaman aşımını 10 dakikaya çıkarmak için nesnenin serverTimeoutInSeconds özelliği kullanılır:
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;
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- ParametredeworkspaceIdsağlanan çalışma alanı hariç çalışma alanlarının 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:
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;
Her çalışma alanının sonuçlarını görüntülemek için, sonuçları sıralamak TenantId veya Kusto sorgusunda filtrelemek için sütunu kullanın.
TenantId'ye göre sipariş sonuçları
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:
-
LogsQueryOptions.includeQueryStatisticsözelliğinitrueolarak ayarlayın. -
statisticsNesnenin içindekiLogsQueryResultalana erişin.
Aşağıdaki örnek sorgu yürütme süresini yazdırır:
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}`,
);
Yükün statistics yapısı sorguya 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'un query özelliği içinde bulunur. Mesela:
{
"query": {
"executionTime": 0.0156478,
"resourceUsage": {...},
"inputDatasetStatistics": {...},
"datasetStatistics": [{...}]
}
}
Görselleştirme ekle
İşleme işlecini kullanarak günlük sorguları için görselleştirme verilerini almak için:
-
LogsQueryOptions.includeVisualizationözelliğinitrueolarak ayarlayın. -
visualizationNesnenin içindekiLogsQueryResultalana erişin.
Mesela:
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);
Yükün visualization yapısı sorguya göre değiştiğinden, bir Record<string, unknown> dönüş türü kullanılır. Ham JSON yanıtını içerir. Mesela:
{
"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, bir Azure Ölçüm Danışmanı aboneliği için ölçümleri alır.
Kaynak URI'sinin ölçümlerin sorgulandığı kaynak olması gerekir. Normalde şu formattadır /subscriptions/<id>/resourceGroups/<rg-name>/providers/<source>/topics/<resource-name>: .
Kaynak URI'sini bulmak için:
- Azure portalında kaynağınızın sayfasına gidin.
- Genel Bakış dikey penceresinde JSON Görünümü bağlantısını seçin.
- Sonuçta elde edilen JSON'da özelliğin değerini
idkopyalayın.
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}`);
}
Önceki örnekte, ölçüm sonuçları metricsResponse , kullanıcının işlevin dizi bağımsız değişkeninde metricNames ölçüm adlarını belirttiği sıraya göre sıralanmıştır queryResource . Kullanıcı belirtirse[firstMetricName, secondMetricName], için firstMetricName sonucu, içinde secondMetricNameiçin metricResponse sonucundan önce görünecektir.
Ölçüm sorgu yanıtını işleme
metrics queryResource işlevi bir QueryMetricsResult nesne döndürür. Nesne QueryMetricsResult , -typed nesnelerin listesi Metric, interval, namespace, ve timespangibi özellikler içerir. Nesne Metric listesine özellik kullanılarak metrics erişilebilir. Bu listedeki her Metric nesne bir nesne listesi TimeSeriesElement içerir. Her biri TimeSeriesElement ve özelliklerini içerir 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 { 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}`);
}
}
}
}
Tam bir örnek burada bulunabilir.
Birden çok kaynak için sorgu ölçümleri
Tek bir istekte birden çok Azure kaynağı için ölçümleri sorgulamak için yöntemini MetricsClient.queryResources kullanın. Bu yöntem:
- Yöntemlerden farklı bir API çağırır
MetricsClient. - İ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:
- Kullanıcının izleme verilerini Azure abonelik düzeyinde okuma yetkisine sahip olması gerekir. Örneğin, sorgulanacak abonelikte İzleme Okuyucusu rolü .
- Sorgulanacak ölçümleri içeren ölçüm ad alanı sağlanmalıdır. Ölçüm ad alanlarının listesi için Kaynak türüne göre desteklenen ölçümler ve günlük kategorileri bölümüne bakın.
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);
Her Azure kaynak türü için kullanılabilen ölçümlerin ve boyutların envanteri için bkz.
Sorun giderme
Çeşitli arıza 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 Azure İzleyici hizmet belgelerine bakın.
Katkıda
Bu kitaplığa katkıda bulunmak istiyorsanız kodu oluşturma ve test etme hakkında daha fazla bilgi edinmek için lütfen katkıda bulunma kılavuzu 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:
pnpm installpnpm build --filter @azure/monitor-query...cd into sdk/monitor/monitor-query- Dosyayı şuraya kopyalayın:
sample.env.env -
.envDosyayı bir düzenleyicide açın ve değerleri doldurun. -
npm run test.
Daha fazla ayrıntı için testler dosyamıza bakın.
İlgili projeler
- JavaScript için Microsoft Azure SDK
- Azure İzleyici
Azure SDK for JavaScript