Pustaka klien Penyerapan Azure Monitor untuk JS
Pustaka klien Penyerapan Azure Monitor digunakan untuk mengirim log kustom ke Azure Monitor menggunakan API Penyerapan Log.
Pustaka ini memungkinkan Anda mengirim data dari hampir semua sumber ke tabel bawaan yang didukung atau ke tabel kustom yang Anda buat di ruang kerja Analitik Log. Anda bahkan dapat memperpanjang skema tabel bawaan dengan kolom kustom.
Sumber Daya:
Memulai
Prasyarat
Instal paketnya
Instal pustaka klien Penyerapan Azure Monitor untuk JS dengan npm:
npm install @azure/monitor-ingestion
Mengautentikasi klien
Klien yang diautentikasi diperlukan untuk menyerap data. Untuk mengautentikasi, buat instans kelas TokenCredential (lihat @azure/identitas untuk DefaultAzureCredential
dan implementasi lainnya TokenCredential
). Teruskan ke konstruktor kelas klien Anda.
Untuk mengautentikasi, contoh berikut menggunakan DefaultAzureCredential
dari paket @azure/identitas :
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);
Mengonfigurasi klien untuk sovereign cloud Azure
Secara default, klien dikonfigurasi untuk menggunakan Azure Public Cloud. Untuk menggunakan sovereign cloud sebagai gantinya, berikan nilai titik akhir dan audiens yang benar saat membuat instans klien. Contohnya:
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",
});
Konsep utama
Titik Akhir Pengumpulan Data
Titik Akhir Pengumpulan Data (DCE) memungkinkan Anda mengonfigurasi pengaturan penyerapan secara unik untuk Azure Monitor. Artikel ini menyediakan gambaran umum titik akhir pengumpulan data termasuk konten dan strukturnya dan bagaimana Anda dapat membuat dan bekerja dengannya.
Aturan Pengumpulan Data
Aturan pengumpulan data (DCR) menentukan data yang dikumpulkan oleh Azure Monitor dan menentukan bagaimana dan di mana data tersebut harus dikirim atau disimpan. Panggilan REST API harus menentukan DCR yang akan digunakan. Satu DCE dapat mendukung beberapa DDR, sehingga Anda dapat menentukan DCR yang berbeda untuk sumber dan tabel target yang berbeda.
DCR harus memahami struktur data input dan struktur tabel target. Jika tidak cocok, keduanya dapat menggunakan transformasi untuk mengonversi data sumber agar sesuai dengan tabel target. Anda juga dapat menggunakan transformasi untuk memfilter data sumber dan melakukan perhitungan atau konversi lainnya.
Untuk detail selengkapnya, lihat Aturan pengumpulan data di Azure Monitor. Untuk informasi tentang cara mengambil ID DCR, lihat tutorial ini.
Tabel ruang kerja Analitik Log
Log kustom dapat mengirim data ke setiap tabel kustom yang Anda buat dan ke tabel bawaan tertentu di ruang kerja Analitik Log Anda. Tabel target harus ada sebelum Anda dapat mengirim data ke tabel tersebut. Saat ini tabel bawaan berikut didukung:
Contoh
Anda dapat membiasakan diri dengan API yang berbeda menggunakan Sampel.
Mengunggah log kustom
Anda dapat membuat klien dan memanggil metode klien Upload
. Perhatikan batas penyerapan data.
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 };
Memverifikasi log
Anda dapat memverifikasi bahwa data Anda telah diunggah dengan benar dengan menggunakan pustaka @azure/monitor-query . Jalankan sampel Unggah log kustom terlebih dahulu sebelum memverifikasi log.
// 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 };
Mengunggah batch log yang besar
Saat mengunggah lebih dari 1MB log dalam satu panggilan ke upload
metode pada LogsIngestionClient
, unggahan akan dibagi menjadi beberapa batch yang lebih kecil, masing-masing tidak lebih besar dari 1MB. Secara default, batch ini akan diunggah secara paralel, dengan maksimum 5 batch diunggah secara bersamaan. Mungkin diinginkan untuk mengurangi konkurensi maksimum jika penggunaan memori menjadi perhatian. Jumlah maksimum unggahan bersamaan dapat dikontrol menggunakan opsi , seperti yang maxConcurrency
ditunjukkan dalam contoh ini:
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 };
Pengambilan log
Log yang diunggah menggunakan pustaka klien Monitor Ingestion dapat diambil menggunakan pustaka klien Monitor Query.
Pemecahan Masalah
Untuk detail tentang mendiagnosis berbagai skenario kegagalan, lihat panduan pemecahan masalah kami.
Langkah berikutnya
Untuk mempelajari selengkapnya tentang Azure Monitor, lihat dokumentasi layanan Azure Monitor. Silakan lihat direktori sampel untuk contoh terperinci tentang cara menggunakan pustaka ini.
Berkontribusi
Jika Anda ingin berkontribusi pada pustaka ini, baca panduan berkontribusi untuk mempelajari selengkapnya tentang cara membuat dan menguji kode.
Azure SDK for JavaScript