azure-monitor-opentelemetry-ts

โดย microsoft

Instrument applications with Azure Monitor and OpenTelemetry for JavaScript (@azure/monitor-opentelemetry). Use when adding distributed tracing, metrics, and logs to Node.js applications with Application Insights.

npx skills add https://github.com/microsoft/skills --skill azure-monitor-opentelemetry-ts

Azure Monitor OpenTelemetry SDK for TypeScript

Auto-instrument Node.js applications with distributed tracing, metrics, and logs.

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-ingestion

Environment Variables

APPLICATIONINSIGHTS_CONNECTION_STRING=InstrumentationKey=...;IngestionEndpoint=...
AZURE_TOKEN_CREDENTIALS=prod # Required only if DefaultAzureCredential is used in production

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

// Now import your application
import express from "express";
const app = express();

ESM Support (Node.js 18.19+)

node --import @azure/monitor-opentelemetry/loader ./dist/index.js

package.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, ManagedIdentityCredential } 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";

// Local dev: DefaultAzureCredential. Production: set AZURE_TOKEN_CREDENTIALS=prod or AZURE_TOKEN_CREDENTIALS=<specific_credential>
const credential = new DefaultAzureCredential({requiredEnvVars: ["AZURE_TOKEN_CREDENTIALS"]});
// Or use a specific credential directly in production:
// See https://learn.microsoft.com/javascript/api/overview/azure/identity-readme?view=azure-node-latest#credential-classes
// const credential = new ManagedIdentityCredential();

const client = new LogsIngestionClient(endpoint, credential);

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 Processor

import { SpanProcessor, ReadableSpan } from "@opentelemetry/sdk-trace-base";
import { Span, Context, SpanKind, TraceFlags } from "@opentelemetry/api";
import { useAzureMonitor } from "@azure/monitor-opentelemetry";

class FilteringSpanProcessor implements SpanProcessor {
  forceFlush(): Promise<void> { return Promise.resolve(); }
  shutdown(): Promise<void> { return Promise.resolve(); }
  onStart(span: Span, context: Context): void {}
  
  onEnd(span: ReadableSpan): void {
    // Add custom attributes
    span.attributes["CustomDimension"] = "value";
    
    // Filter out internal spans
    if (span.kind === SpanKind.INTERNAL) {
      span.spanContext().traceFlags = TraceFlags.NONE;
    }
  }
}

useAzureMonitor({
  spanProcessors: [new FilteringSpanProcessor()]
});

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

Skills เพิ่มเติมจาก microsoft

oss-growth
microsoft
บุคลิกภาพนักเติบโตโอเอสเอส
agent-framework-azure-ai-py
microsoft
สร้างเอเจนต์ Azure AI Foundry โดยใช้ Microsoft Agent Framework Python SDK (agent-framework-azure-ai) ใช้เมื่อสร้างเอเจนต์แบบถาวรด้วย AzureAIAgentsProvider ใช้เครื่องมือที่โฮสต์ไว้ (ตัวแปลโค้ด การค้นหาไฟล์ การค้นหาเว็บ) ผสานรวมเซิร์ฟเวอร์ MCP จัดการเธรดการสนทนา หรือใช้งานการตอบสนองแบบสตรีมมิ่ง ครอบคลุมเครื่องมือฟังก์ชัน ผลลัพธ์แบบมีโครงสร้าง และเอเจนต์แบบหลายเครื่องมือ
development
airunway-aks-setup
microsoft
ตั้งค่า AI Runway บน AKS — จากคลัสเตอร์เปล่าสู่การรันโมเดล ครอบคลุมการตรวจสอบคลัสเตอร์ การติดตั้งคอนโทรลเลอร์ การประเมิน GPU การตั้งค่าผู้ให้บริการ และการปรับใช้ครั้งแรก เมื่อ: "ตั้งค่า AI Runway", "เริ่มใช้งานคลัสเตอร์ AKS", "ติดตั้ง AI Runway", "ตั้งค่า airunway", "ปรับใช้โมเดลกับ AKS", "อนุมานด้วย GPU บน AKS", "ตั้งค่า KAITO บน AKS", "รัน LLM บน AKS", "vLLM บน AKS", "ตั้งค่าการให้บริการโมเดลบน AKS", "AI Runway controller
devops
appinsights-instrumentation
microsoft
Guidance for instrumenting webapps with Azure Application Insights. Provides telemetry patterns, SDK setup, and configuration references. WHEN: how to instrument app, App Insights SDK, telemetry patterns, what is App Insights, Application Insights guidance, instrumentation examples, APM best practices.
devops
applicationinsights-web-ts
microsoft
ใช้เครื่องมือวัดแอปเบราว์เซอร์/เว็บด้วย Application Insights JavaScript SDK (@microsoft/applicationinsights-web) ใช้สำหรับ Real User Monitoring (RUM) — การดูหน้าเว็บ คลิก ดีเพนเดนซี AJAX/fetch ข้อยกเว้น อีเวนต์ที่กำหนดเอง และเทรซเอเจนต์ GenAI ฝั่งเบราว์เซอร์ที่เชื่อมโยงกับเทรซ OpenTelemetry ฝั่งแบ็กเอนด์ ครอบคลุมการตั้งค่า SDK Loader Script และ npm ส่วนขยายเฟรมเวิร์ก (React, React Native, Angular), Click Analytics, ตัวเริ่มต้นเทเลเมทรี และหลักการตั้งชื่อเชิงความหมาย OTel GenAI สำหรับสแปนเอเจนต์/เครื่องมือ/โมเดลที่ส่งจากเบราว์เซอร์
devops
azure-ai-anomalydetector-java
microsoft
สร้างแอปพลิเคชันตรวจจับความผิดปกติด้วย Azure AI Anomaly Detector SDK สำหรับ Java ใช้เมื่อต้องการนำการตรวจจับความผิดปกติแบบตัวแปรเดียว/หลายตัวแปร การวิเคราะห์อนุกรมเวลา หรือการตรวจสอบที่ขับเคลื่อนด้วย AI ไปใช้
development
azure-ai-language-conversations-py
microsoft
ใช้ Conversational Language Understanding (CLU) ด้วย Python SDK ของ azure-ai-language-conversations ใช้เมื่อทำงานกับ ConversationAnalysisClient เพื่อวิเคราะห์เจตนาและเอนทิตีของการสนทนา สร้างฟีเจอร์ NLP หรือผสานความเข้าใจภาษาเข้ากับแอปพลิเคชัน
development
azure-ai-ml-py
microsoft
Azure Machine Learning SDK v2 สำหรับ Python ใช้สำหรับพื้นที่ทำงาน ML งาน โมเดล ชุดข้อมูล คอมพิวต์ และไปป์ไลน์ ทริกเกอร์: "azure-ai-ml", "MLClient", "workspace", "model registry", "training jobs", "datasets
development