Condividi tramite


Libreria client di inserimento di Monitoraggio di Azure per JS

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

Questa libreria consente di inviare dati praticamente da qualsiasi origine alle tabelle predefinite supportate o alle tabelle personalizzate create nell'area di lavoro Log Analytics. È anche possibile estendere lo schema delle tabelle predefinite con colonne personalizzate.

Resources:

Getting started

Prerequisites

Installare il pacchetto

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

npm install @azure/monitor-ingestion

Autenticare il client

Per inserire i dati è necessario un client autenticato. To authenticate, create an instance of a TokenCredential class (see @azure/identity for DefaultAzureCredential and other TokenCredential implementations). Passarlo al costruttore della classe client.

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

Configurare il client per il cloud sovrano di Azure

Per impostazione predefinita, il client è configurato per l'uso del cloud pubblico di Azure. Per usare invece un cloud sovrano, fornire il valore corretto dell'endpoint e del pubblico durante la creazione di un'istanza del client. 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

Endpoint di raccolta dati

Gli endpoint di raccolta dati (DCE) consentono di configurare in modo univoco le impostazioni di inserimento per Monitoraggio di Azure. This article provides an overview of data collection endpoints including their contents and structure and how you can create and work with them.

Regola di raccolta dati

Le regole di raccolta dati definiscono i dati raccolti da Monitoraggio di Azure e specificano come e dove i dati devono essere inviati o archiviati. La chiamata all'API REST deve specificare un DCR da utilizzare. Un singolo DCE può supportare più DCR, quindi è possibile specificare un DCR diverso per origini e tabelle di destinazione diverse.

Il DCR deve comprendere la struttura dei dati di input e la struttura della tabella di destinazione. Se i due non corrispondono, può usare una trasformazione per convertire i dati di origine in modo che corrispondano alla tabella di destinazione. È inoltre possibile utilizzare la trasformazione per filtrare i dati di origine ed eseguire altri calcoli o conversioni.

Per altre informazioni, vedere Regole di raccolta dati in Monitoraggio di Azure. Per informazioni su come recuperare un ID DCR, vedere questa esercitazione.

Tabelle dell'area di lavoro Log Analytics

I log personalizzati possono inviare dati a qualsiasi tabella personalizzata creata dall'utente e a determinate tabelle predefinite nell'area di lavoro Log Analytics. La tabella di destinazione deve esistere prima di potervi inviare i dati. Le tabelle predefinite seguenti sono attualmente supportate:

Examples

You can familiarize yourself with different APIs using Samples.

Caricare log personalizzati

È possibile creare un client e chiamare il metodo del Upload client. 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. Eseguire l'esempio Carica log personalizzati prima di verificare i log.

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

Caricamento di grandi batch di log

Quando si caricano più di 1 MB di log in una singola chiamata al upload metodo su LogsIngestionClient, il caricamento verrà suddiviso in diversi batch più piccoli, ciascuno non più grande di 1 MB. Per impostazione predefinita, questi batch verranno caricati in parallelo, con un massimo di 5 batch caricati contemporaneamente. Potrebbe essere opportuno ridurre la concorrenza massima se l'utilizzo della memoria è un problema. Il numero massimo di caricamenti simultanei può essere controllato utilizzando l'opzione maxConcurrency , come mostrato in questo esempio:

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

I log caricati utilizzando la libreria client Monitor Ingestion possono essere recuperati utilizzando la libreria client Monitor Query.

Troubleshooting

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

Next steps

Per altre informazioni su Monitoraggio di Azure, vedere la documentazione del servizio Monitoraggio di Azure. 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.