共用方式為


適用於 JS 的 Azure 監視器擷取客戶端連結庫

Azure 監視器擷取客戶端連結庫可用來使用記錄擷取 API 將自定義記錄傳送至 Azure 監視器

此連結庫可讓您將數據從幾乎任何來源傳送到支援的內建數據表,或傳送至您在Log Analytics工作區中建立的自定義數據表。 您甚至還可以使用自訂資料行擴充內建資料表的結構描述。

資源:

開始使用

必要條件

安裝套件

使用 npm 安裝適用於 JS 的 Azure 監視器擷取客戶端連結庫:

npm install @azure/monitor-ingestion

驗證用戶端

擷取數據需要經過驗證的用戶端。 若要進行驗證,請建立 TokenCredential 類別的實例, (請參閱@azure /身分 識別, DefaultAzureCredential 以及其他 TokenCredential 實作) 。 將它傳遞至客戶端類別的建構函式。

若要驗證,下列範例會從 @azure/身分識別套件使用DefaultAzureCredential

import { DefaultAzureCredential } from "@azure/identity";
import { LogsIngestionClient } from "@azure/monitor-ingestion";

import * as dotenv from "dotenv";
dotenv.config();

const logsIngestionEndpoint = process.env.LOGS_INGESTION_ENDPOINT || "logs_ingestion_endpoint";

const credential = new DefaultAzureCredential();
const logsIngestionClient = new LogsIngestionClient(logsIngestionEndpoint, credential);

設定 Azure 主權雲端的用戶端

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

import { DefaultAzureCredential } from "@azure/identity";
import { LogsIngestionClient } from "@azure/monitor-ingestion";

import * as dotenv from "dotenv";
dotenv.config();

const logsIngestionEndpoint = process.env.LOGS_INGESTION_ENDPOINT || "logs_ingestion_endpoint";

const credential = new DefaultAzureCredential();
const logsIngestionClient = new LogsIngestionClient(logsIngestionEndpoint, credential, {
  audience: "https://api.loganalytics.azure.cn/.default",
});

重要概念

資料收集端點

資料收集端點 (DCE) 可讓您設定獨特的 Azure 監視器擷取設定。 本文 提供數據收集端點的概觀,包括其內容和結構,以及如何建立及使用這些端點。

數據收集規則

數據收集規則 (DCR) 定義 Azure 監視器收集的數據,並指定該數據應該傳送或儲存的方式和位置。 REST API 呼叫必須指定要使用的 DCR。 單一 DCE 可以支援多個 DCR,因此您可以針對不同的來源和目標資料表指定不同的 DCR。

DCR 必須了解輸入資料和目標資料表的結構。 如果兩者不相符,其可以使用轉換,以此來轉換來源資料,使其符合目標資料表。 您也可以使用轉換來篩選來源資料,並執行任何其他的計算或轉換。

如需詳細資訊,請參閱 Azure 監視器中的數據收集規則。如需如何擷取 DCR 識別符的資訊,請參閱 本教學課程

Log Analytics 工作區數據表

自訂記錄可將資料傳送至您建立的任何自訂資料表,以及您 Log Analytics 工作區中的某些內建資料表。 目標資料表必須先存在,您才能將資料傳送至該資料表。 目前下列的內建資料表受到支援:

範例

您可以使用 範例熟悉不同的 API。

上傳自定義記錄

您可以建立用戶端並呼叫用戶端 Upload 的方法。 記下數據擷取 限制

const { isAggregateLogsUploadError, DefaultAzureCredential } = require("@azure/identity");
const { LogsIngestionClient } = require("@azure/monitor-ingestion");

require("dotenv").config();

async function main() {
  const logsIngestionEndpoint = process.env.LOGS_INGESTION_ENDPOINT || "logs_ingestion_endpoint";
  const ruleId = process.env.DATA_COLLECTION_RULE_ID || "data_collection_rule_id";
  const streamName = process.env.STREAM_NAME || "data_stream_name";
  const credential = new DefaultAzureCredential();
  const client = new LogsIngestionClient(logsIngestionEndpoint, credential);
  const logs = [
    {
      Time: "2021-12-08T23:51:14.1104269Z",
      Computer: "Computer1",
      AdditionalContext: "context-2",
    },
    {
      Time: "2021-12-08T23:51:14.1104269Z",
      Computer: "Computer2",
      AdditionalContext: "context",
    },
  ];
  try{
    await client.upload(ruleId, streamName, logs);
  }
  catch(e){
    let aggregateErrors = isAggregateLogsUploadError(e) ? e.errors : [];
    if (aggregateErrors.length > 0) {
      console.log("Some logs have failed to complete ingestion");
      for (const error of aggregateErrors) {
        console.log(`Error - ${JSON.stringify(error.cause)}`);
        console.log(`Log - ${JSON.stringify(error.failedLogs)}`);
      }
    } else {
      console.log(e);
    }
  }
}

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

module.exports = { main };

驗證記錄

您可以使用 @azure/monitor-query 連結庫,確認您的數據已正確上傳。 先執行 上傳自定義記錄 範例,再驗證記錄。

// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.

/**
 * @summary Demonstrates how to run query against a Log Analytics workspace to verify if the logs were uploaded
 */

const { DefaultAzureCredential } = require("@azure/identity");
const { LogsQueryClient } = require("@azure/monitor-query");

const monitorWorkspaceId = process.env.MONITOR_WORKSPACE_ID || "workspace_id";
const tableName = process.env.TABLE_NAME || "table_name";
require("dotenv").config();

async function main() {
  const credential = new DefaultAzureCredential();
  const logsQueryClient = new LogsQueryClient(credential);
  const queriesBatch = [
    {
      workspaceId: monitorWorkspaceId,
      query: tableName + " | count;",
      timespan: { duration: "P1D" },
    },
  ];

  const result = await logsQueryClient.queryBatch(queriesBatch);
  if (result[0].status === "Success") {
    console.log("Table entry count: ", JSON.stringify(result[0].tables));
  } else {
    console.log(
      `Some error encountered while retrieving the count. Status = ${result[0].status}`,
      JSON.stringify(result[0])
    );
  }
}

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

module.exports = { main };

上傳大量記錄

在 對 方法LogsIngestionClient的單一呼叫upload中上傳超過 1 MB 的記錄時,上傳會分割成數個較小的批次,每個批次不超過 1MB。 根據預設,這些批次會平行上傳,同時上傳最多5個批次。 如果記憶體使用量是考慮的,可能會想要減少最大並行存取。 您可以使用 選項來控制 maxConcurrency 並行上傳數目上限,如下列範例所示:

const { DefaultAzureCredential } = require("@azure/identity");
const { isAggregateLogsUploadError, LogsIngestionClient } = require("@azure/monitor-ingestion");

require("dotenv").config();

async function main() {
  const logsIngestionEndpoint = process.env.LOGS_INGESTION_ENDPOINT || "logs_ingestion_endpoint";
  const ruleId = process.env.DATA_COLLECTION_RULE_ID || "data_collection_rule_id";
  const streamName = process.env.STREAM_NAME || "data_stream_name";
  const credential = new DefaultAzureCredential();
  const client = new LogsIngestionClient(logsIngestionEndpoint, credential);

  // Constructing a large number of logs to ensure batching takes place
  const logs = [];
  for (let i = 0; i < 100000; ++i) {
    logs.push({
      Time: "2021-12-08T23:51:14.1104269Z",
      Computer: "Computer1",
      AdditionalContext: `context-${i}`,
    });
  }

  try{
    // Set the maximum concurrency to 1 to prevent concurrent requests entirely
    await client.upload(ruleId, streamName, logs, { maxConcurrency: 1 });
  }
  catch(e){
    let aggregateErrors = isAggregateLogsUploadError(e) ? e.errors : [];
    if (aggregateErrors.length > 0) {
      console.log("Some logs have failed to complete ingestion");
      for (const error of aggregateErrors) {
        console.log(`Error - ${JSON.stringify(error.cause)}`);
        console.log(`Log - ${JSON.stringify(error.failedLogs)}`);
      }
    } else {
      console.log(e);
    }
  }
}
main().catch((err) => {
  console.error("The sample encountered an error:", err);
  process.exit(1);
});

module.exports = { main };

擷取記錄

您可以使用 監視查詢客戶端連結庫來擷取使用監視擷取客戶端連結庫上傳的記錄。

疑難排解

如需診斷各種失敗案例的詳細資訊,請參閱我們的 疑難解答指南

下一步

若要深入瞭解 Azure 監視器,請參閱 Azure 監視器服務檔。 如需如何使用此連結庫的詳細 範例 ,請參閱範例目錄。

參與

如果您希望向此程式庫投稿,請參閱投稿指南,深入瞭解如何組建與測試程式碼。

曝光數