다음을 통해 공유


JS용 Azure Monitor 수집 클라이언트 라이브러리

The Azure Monitor Ingestion client library is used to send custom logs to Azure Monitor using the Logs Ingestion API.

이 라이브러리를 사용하면 거의 모든 원본에서 지원되는 기본 제공 테이블 또는 Log Analytics 작업 영역에서 만든 사용자 지정 테이블로 데이터를 보낼 수 있습니다. 기본 제공 테이블의 스키마를 사용자 지정 열로 확장할 수도 있습니다.

Resources:

Getting started

Prerequisites

패키지 설치

Install the Azure Monitor Ingestion client library for JS with npm:

npm install @azure/monitor-ingestion

클라이언트 인증

데이터를 수집하려면 인증된 클라이언트가 필요합니다. To authenticate, create an instance of a TokenCredential class (see @azure/identity for DefaultAzureCredential and other TokenCredential implementations). 클라이언트 클래스의 생성자에 전달하십시오.

To authenticate, the following example uses DefaultAzureCredential from the @azure/identity package:

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

const logsIngestionEndpoint = "https://<my-endpoint>.azure.com";

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

Azure 소버린 클라우드에 대한 클라이언트 구성

기본적으로 클라이언트는 Azure 퍼블릭 클라우드를 사용하도록 구성됩니다. 대신 소버린 클라우드를 사용하려면 클라이언트를 인스턴스화할 때 올바른 엔드포인트와 대상 그룹 값을 제공합니다. For example:

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

const logsIngestionEndpoint = "https://<my-endpoint>.azure.cn";

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

Key concepts

데이터 컬렉션 엔드포인트

DCE(데이터 수집 엔드포인트)를 사용하면 Azure Monitor에 대한 수집 설정을 고유하게 구성할 수 있습니다. This article provides an overview of data collection endpoints including their contents and structure and how you can create and work with them.

데이터 수집 규칙

DCR(데이터 수집 규칙)은 Azure Monitor에서 수집한 데이터를 정의하고 해당 데이터를 보내거나 저장해야 하는 방법과 위치를 지정합니다. REST API 호출은 사용할 DCR을 지정해야 합니다. 단일 DCE는 여러 DCR을 지원할 수 있으므로 다른 원본 및 대상 테이블에 대해 다른 DCR을 지정할 수 있습니다.

DCR은 입력 데이터의 구조와 대상 테이블의 구조를 이해해야 합니다. 두 값이 일치하지 않으면 변환을 사용하여 원본 데이터를 대상 테이블과 일치하도록 변환할 수 있습니다. 변환을 사용하여 원본 데이터를 필터링하고 다른 계산 또는 변환을 수행할 수도 있습니다.

자세한 내용은 Azure Monitor의 데이터 수집 규칙을 참조하세요. DCR ID를 검색하는 방법에 대한 자세한 내용은 이 자습서를 참조하세요.

Log Analytics 작업 영역 테이블

사용자 지정 로그는 사용자가 만든 모든 사용자 지정 테이블과 Log Analytics 작업 영역의 특정 기본 제공 테이블로 데이터를 보낼 수 있습니다. 대상 테이블이 있어야 데이터를 보낼 수 있습니다. 현재 지원되는 기본 제공 테이블은 다음과 같습니다.

Examples

You can familiarize yourself with different APIs using Samples.

사용자 지정 로그 업로드

클라이언트를 만들고 클라이언트의 Upload 메서드를 호출할 수 있습니다. Take note of the data ingestion limits.

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

const logsIngestionEndpoint = "https://<my-endpoint>.azure.com";
const ruleId = "data_collection_rule_id";
const streamName = "data_stream_name";

const credential = new DefaultAzureCredential();
const logsIngestionClient = 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 logsIngestionClient.upload(ruleId, streamName, logs);
} catch (e) {
  const 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(`An error occurred: ${e}`);
  }
}

Verify logs

You can verify that your data has been uploaded correctly by using the @azure/monitor-query library. 로그를 확인하기 전에 먼저 사용자 지정 로그 업로드 샘플을 실행합니다.

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

const monitorWorkspaceId = "workspace_id";
const tableName = "table_name";

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

대량의 로그 배치 업로드

에 대한 메서드 호출LogsIngestionClient에 대한 upload 단일 호출에서 1MB 이상의 로그를 업로드하는 경우 업로드는 각각 1MB보다 크지 않은 여러 개의 더 작은 배치로 분할됩니다. 기본적으로 이러한 배치는 병렬로 업로드되며 최대 5개의 배치가 동시에 업로드됩니다. 메모리 사용량이 문제가 되는 경우 최대 동시성을 줄이는 것이 바람직할 수 있습니다. 최대 동시 업로드 수는 다음 예제와 같이 옵션을 사용하여 maxConcurrency 제어할 수 있습니다.

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

const logsIngestionEndpoint = "https://<my-endpoint>.azure.com";
const ruleId = "data_collection_rule_id";
const streamName = "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);
  }
}

Retrieve logs

모니터 수집 클라이언트 라이브러리를 사용하여 업로드된 로그는 모니터 쿼리 클라이언트 라이브러리를 사용하여 검색할 수 있습니다.

Troubleshooting

For details on diagnosing various failure scenarios, see our troubleshooting guide.

Next steps

Azure Monitor에 대한 자세한 내용은 Azure Monitor 서비스 설명서를 참조하세요. Please take a look at the samples directory for detailed examples on how to use this library.

Contributing

If you'd like to contribute to this library, please read the contributing guide to learn more about how to build and test the code.