你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

适用于 JS 的 Azure Monitor 引入客户端库

Azure Monitor 引入客户端库用于使用日志引入 API 将自定义日志发送到 Azure Monitor

此库允许将几乎任何源中的数据发送到支持的内置表或 Log Analytics 工作区中创建的自定义表。 甚至可以使用自定义列来扩展内置表的架构。

资源:

入门

先决条件

安装包

使用 npm 安装适用于 JS 的 Azure Monitor 引入客户端库:

npm install @azure/monitor-ingestion

验证客户端

引入数据需要经过身份验证的客户端。 若要进行身份验证,请创建 TokenCredential 类的实例, (请参阅 @azure/identityDefaultAzureCredential 以及) 的其他 TokenCredential 实现。 将其传递给客户端类的构造函数。

为了进行身份验证,以下示例使用 DefaultAzureCredential@azure/identity 包:

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 Monitor 的引入设置。 本文 概述了数据收集终结点,包括其内容和结构,以及如何创建和使用它们。

数据收集规则

数据收集规则 (DCR) 定义 Azure Monitor 收集的数据,并指定发送或存储这些数据的方式和位置。 REST API 调用必须指定要使用的 DCR。 一个 DCE 可以支持多个 DCR,因此,可以为不同的源和目标表指定不同的 DCR。

DCR 必须了解输入数据的结构和目标表的结构。 如果这两个结构不匹配,它可以使用转换将源数据转换为与目标表匹配。 你还可使用转换来筛选源数据并执行任何其他计算或转换。

有关更多详细信息,请参阅 Azure Monitor 中的数据收集规则。有关如何检索 DCR ID 的信息,请参阅 本教程

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中上传超过 1MB 的日志时,上传将拆分为多个较小的批,每个批不超过 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 };

检索日志

可以使用 Monitor 查询客户端库检索使用 Monitor 引入客户端库上传的日志。

疑难解答

日志记录

启用日志记录可能有助于发现有关故障的有用信息。 若要查看 HTTP 请求和响应的日志,请将 AZURE_LOG_LEVEL 环境变量设置为 info。 或者,可以在运行时通过调用 @azure/logger 中的 setLogLevel 来启用日志记录:

import { setLogLevel } from "@azure/logger";

setLogLevel("info");

有关如何启用日志的详细说明,请参阅 @azure/记录器包文档

后续步骤

若要详细了解 Azure Monitor,请参阅 Azure Monitor 服务文档。 请查看示例目录,获取有关如何使用此库的详细 示例

贡献

若要为此库做出贡献,请阅读贡献指南,详细了解如何生成和测试代码。

曝光数