Aracılığıyla paylaş


JavaScript için Azure İzleyici Sorgu Günlükleri istemci kitaplığı - sürüm 1.0.0

Azure İzleyici Sorgu Günlükleri istemci kitaplığı, Azure İzleyici'nin Günlükler 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.

Danışma belgesinden @azure/monitor-query⚠geçiş ️

Uygulama kodunuzu orijinal @azure/monitor-query paketten kitaplığa nasıl güncelleyeceğinizle ilgili ayrıntılı yönergeler için Geçiş Kılavuzu'na@azure/monitor-query-logs göz atın.

Kaynaklar:

Başlangıç Yapmak

Desteklenen ortamlar

Daha fazla bilgi için destek politikamıza bakın.

Önkoşullar

Paketi yükle

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

npm install --save @azure/monitor-query-logs

İstemciyi oluşturma

Günlükleri sorgulamak için kimliği doğrulanmış bir istemci gereklidir. Kimlik doğrulaması için aşağıdaki örnek, @azure/identity paketinden DefaultAzureCredential kullanır.

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

const credential = new DefaultAzureCredential();

// Create a LogsQueryClient
const logsQueryClient = new LogsQueryClient(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. Örneğin:

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

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

Sorguyu yürütme

Günlük 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.

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

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:

  1. Azure portalında 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ğin değerini id kopyalayın.
import { DefaultAzureCredential } from "@azure/identity";
import { LogsQueryClient, Durations, LogsQueryResultStatus } from "@azure/monitor-query-logs";

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

console.log(`Results for query '${kustoQuery}'`);

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

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-logs";

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

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:

  • 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:

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

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-logs";

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 - Parametrede workspaceId sağ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-logs";

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:

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

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

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

console.log(`Results for query '${kustoQuery}'`);

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. Örneğin:

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

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

Örneğin:

import { LogsQueryClient, Durations } from "@azure/monitor-query-logs";
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. Örneğin:

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

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 Bulunmak

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:

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

Daha fazla ayrıntı için testler dosyamıza bakın.