azure-monitor-opentelemetry-ts – skill DevOps & Hạ tầng cho agent AI
Tự động instrument ứng dụng Node.js với distributed tracing, metrics và logs.
Cài skill azure-monitor-opentelemetry-ts bằng một lệnh
Chọn công cụ bạn đang dùng, copy lệnh và dán vào terminal. Skill sẽ nằm trong thư mục skills của công cụ đó và sẵn sàng dùng ở phiên làm việc tiếp theo.
Claude Code
mkdir -p ~/.claude/skills && curl -fsSL https://skill.dn1nguoi.com/z/azure-monitor-opentelemetry-ts-f93fc.tgz | tar xz -C ~/.claude/skills
Gọi trong Claude Code: /azure-monitor-opentelemetry-ts – rồi mô tả công việc bạn muốn làm.
Codex
mkdir -p ~/.codex/skills && curl -fsSL https://skill.dn1nguoi.com/z/azure-monitor-opentelemetry-ts-f93fc.tgz | tar xz -C ~/.codex/skills
Gọi trong Codex: $azure-monitor-opentelemetry-ts – rồi mô tả công việc bạn muốn làm.
Hermes Agent
mkdir -p ~/.hermes/skills && curl -fsSL https://skill.dn1nguoi.com/z/azure-monitor-opentelemetry-ts-f93fc.tgz | tar xz -C ~/.hermes/skills
Gọi trong Hermes Agent: /azure-monitor-opentelemetry-ts – rồi mô tả công việc bạn muốn làm.
DeepSeek
mkdir -p ~/.deepcode/skills && curl -fsSL https://skill.dn1nguoi.com/z/azure-monitor-opentelemetry-ts-f93fc.tgz | tar xz -C ~/.deepcode/skills
Gọi trong DeepSeek: /azure-monitor-opentelemetry-ts – rồi mô tả công việc bạn muốn làm.
Nội dung SKILL.md
Nội dung SKILL.md gốc bằng tiếng Anh.
Azure Monitor OpenTelemetry SDK for TypeScript
Auto-instrument Node.js applications with distributed tracing, metrics, and logs.
Version and data boundaries
This document describes the existing @azure/monitor-opentelemetry distro. Current Microsoft guidance also offers @microsoft/opentelemetry for new adoption; do not initialize both. Match all OpenTelemetry package versions and use that version’s logger-provider constructor/processor API. Configure approved telemetry destinations, redact PII/secrets, and protect offline storage; automatic instrumentation may export sensitive request/log data. See [Microsoft enablement guidance](https://learn.microsoft.com/en-us/azure/azure-monitor/app/opentelemetry-enable).
Installation
# Distro (recommended - auto-instrumentation)
npm install @azure/monitor-opentelemetry
# Low-level exporters (custom OpenTelemetry setup)
npm install @azure/monitor-opentelemetry-exporter
# Custom logs ingestion
npm install @azure/monitor-ingestionEnvironment Variables
APPLICATIONINSIGHTS_CONNECTION_STRING=InstrumentationKey=...;IngestionEndpoint=...Quick Start (Auto-Instrumentation)
IMPORTANT: Call useAzureMonitor() BEFORE importing other modules.
import { useAzureMonitor } from "@azure/monitor-opentelemetry";
useAzureMonitor({
azureMonitorExporterOptions: {
connectionString: process.env.APPLICATIONINSIGHTS_CONNECTION_STRING
}
});
// Static ESM imports are hoisted; load the app after initialization.
const { default: express } = await import("express");
const app = express();ESM Support (Node.js 18.19+)
node --import @azure/monitor-opentelemetry/loader ./dist/index.jspackage.json:
{
"scripts": {
"start": "node --import @azure/monitor-opentelemetry/loader ./dist/index.js"
}
}Full Configuration
import { useAzureMonitor, AzureMonitorOpenTelemetryOptions } from "@azure/monitor-opentelemetry";
import { resourceFromAttributes } from "@opentelemetry/resources";
const options: AzureMonitorOpenTelemetryOptions = {
azureMonitorExporterOptions: {
connectionString: process.env.APPLICATIONINSIGHTS_CONNECTION_STRING,
storageDirectory: "/path/to/offline/storage",
disableOfflineStorage: false
},
// Sampling
samplingRatio: 1.0, // 0-1, percentage of traces
// Features
enableLiveMetrics: true,
enableStandardMetrics: true,
enablePerformanceCounters: true,
// Instrumentation libraries
instrumentationOptions: {
azureSdk: { enabled: true },
http: { enabled: true },
mongoDb: { enabled: true },
mySql: { enabled: true },
postgreSql: { enabled: true },
redis: { enabled: true },
bunyan: { enabled: false },
winston: { enabled: false }
},
// Custom resource
resource: resourceFromAttributes({ "service.name": "my-service" })
};
useAzureMonitor(options);Custom Traces
import { trace } from "@opentelemetry/api";
const tracer = trace.getTracer("my-tracer");
const span = tracer.startSpan("doWork");
try {
span.setAttribute("component", "worker");
span.setAttribute("operation.id", "42");
span.addEvent("processing started");
// Your work here
} catch (error) {
span.recordException(error as Error);
span.setStatus({ code: 2, message: (error as Error).message });
} finally {
span.end();
}Custom Metrics
import { metrics } from "@opentelemetry/api";
const meter = metrics.getMeter("my-meter");
// Counter
const counter = meter.createCounter("requests_total");
counter.add(1, { route: "/api/users", method: "GET" });
// Histogram
const histogram = meter.createHistogram("request_duration_ms");
histogram.record(150, { route: "/api/users" });
// Observable Gauge
const gauge = meter.createObservableGauge("active_connections");
gauge.addCallback((result) => {
result.observe(getActiveConnections(), { pool: "main" });
});Manual Exporter Setup
Trace Exporter
import { AzureMonitorTraceExporter } from "@azure/monitor-opentelemetry-exporter";
import { NodeTracerProvider, BatchSpanProcessor } from "@opentelemetry/sdk-trace-node";
const exporter = new AzureMonitorTraceExporter({
connectionString: process.env.APPLICATIONINSIGHTS_CONNECTION_STRING
});
const provider = new NodeTracerProvider({
spanProcessors: [new BatchSpanProcessor(exporter)]
});
provider.register();Metric Exporter
import { AzureMonitorMetricExporter } from "@azure/monitor-opentelemetry-exporter";
import { PeriodicExportingMetricReader, MeterProvider } from "@opentelemetry/sdk-metrics";
import { metrics } from "@opentelemetry/api";
const exporter = new AzureMonitorMetricExporter({
connectionString: process.env.APPLICATIONINSIGHTS_CONNECTION_STRING
});
const meterProvider = new MeterProvider({
readers: [new PeriodicExportingMetricReader({ exporter })]
});
metrics.setGlobalMeterProvider(meterProvider);Log Exporter
import { AzureMonitorLogExporter } from "@azure/monitor-opentelemetry-exporter";
import { BatchLogRecordProcessor, LoggerProvider } from "@opentelemetry/sdk-logs";
import { logs } from "@opentelemetry/api-logs";
const exporter = new AzureMonitorLogExporter({
connectionString: process.env.APPLICATIONINSIGHTS_CONNECTION_STRING
});
const loggerProvider = new LoggerProvider();
loggerProvider.addLogRecordProcessor(new BatchLogRecordProcessor(exporter));
logs.setGlobalLoggerProvider(loggerProvider);Custom Logs Ingestion
import { DefaultAzureCredential } from "@azure/identity";
import { LogsIngestionClient, isAggregateLogsUploadError } from "@azure/monitor-ingestion";
const endpoint = "https://<dce>.ingest.monitor.azure.com";
const ruleId = "<data-collection-rule-id>";
const streamName = "Custom-MyTable_CL";
const client = new LogsIngestionClient(endpoint, new DefaultAzureCredential());
const logs = [
{
Time: new Date().toISOString(),
Computer: "Server1",
Message: "Application started",
Level: "Information"
}
];
try {
await client.upload(ruleId, streamName, logs);
} catch (error) {
if (isAggregateLogsUploadError(error)) {
for (const uploadError of error.errors) {
console.error("Failed logs:", uploadError.failedLogs);
}
}
}Custom Span Processing
Enrich writable spans in onStart with span.setAttribute(). Do not mutate ReadableSpan.attributes or spanContext().traceFlags in onEnd: ended spans are read-only and this is not a reliable export filter. Use a supported sampler or a reviewed filtering exporter/processor pipeline for the pinned SDK version, and verify exported data.
Sampling
import { ApplicationInsightsSampler } from "@azure/monitor-opentelemetry-exporter";
import { NodeTracerProvider } from "@opentelemetry/sdk-trace-node";
// Sample 75% of traces
const sampler = new ApplicationInsightsSampler(0.75);
const provider = new NodeTracerProvider({ sampler });Shutdown
import { useAzureMonitor, shutdownAzureMonitor } from "@azure/monitor-opentelemetry";
useAzureMonitor();
// On application shutdown
process.on("SIGTERM", async () => {
await shutdownAzureMonitor();
process.exit(0);
});Key Types
import {
useAzureMonitor,
shutdownAzureMonitor,
AzureMonitorOpenTelemetryOptions,
InstrumentationOptions
} from "@azure/monitor-opentelemetry";
import {
AzureMonitorTraceExporter,
AzureMonitorMetricExporter,
AzureMonitorLogExporter,
ApplicationInsightsSampler,
AzureMonitorExporterOptions
} from "@azure/monitor-opentelemetry-exporter";
import {
LogsIngestionClient,
isAggregateLogsUploadError
} from "@azure/monitor-ingestion";Best Practices
1. Call useAzureMonitor() first - Before importing other modules
2. Use ESM loader for ESM projects - --import @azure/monitor-opentelemetry/loader
3. Enable offline storage - For reliable telemetry in disconnected scenarios
4. Set sampling ratio - For high-traffic applications
5. Add custom dimensions - Use span processors for enrichment
6. Graceful shutdown - Call shutdownAzureMonitor() to flush telemetry
When to Use
This skill is applicable to execute the workflow or actions described in the overview.
Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.
Skill liên quan
- azure-monitor-query-java – SDK Azure Monitor Query cho Java. Thực thi truy vấn Kusto trên Log Analytics workspace…
- azure-monitor-query-py – SDK Azure Monitor Query cho Python. Dùng để truy vấn Log Analytics workspace và metric…
- azure-networking – Cấu hình Azure VNet, NSG và Azure Firewall. Triển khai mô hình hub-spoke và private…
- azure-resource-manager-cosmosdb-dotnet – SDK Azure Resource Manager cho Cosmos DB trên .NET.
- azure-resource-manager-durabletask-dotnet – SDK Azure Resource Manager cho Durable Task Scheduler trên .NET.
- azure-resource-manager-mysql-dotnet – SDK Azure MySQL Flexible Server cho .NET. Quản lý cơ sở dữ liệu cho các triển khai MySQL…
- azure-resource-manager-playwright-dotnet – SDK Azure Resource Manager cho Microsoft Playwright Testing trên .NET.
- azure-resource-manager-redis-dotnet – SDK Azure Resource Manager cho Redis trên .NET.