azure-monitor-opentelemetry-ts について
Azure Monitor OpenTelemetry SDK for TypeScript は、Node.js アプリケーションからトレース、メトリック、ログを収集します。自動計装に加え、カスタムエクスポーターとテレメトリ取り込みにも対応します。
主な機能
- 01Node.js の自動計装
- 02トレース、メトリック、ログのエクスポート
- 03カスタム属性とメトリックの追加
- 04サンプリングとオフライン保存の設定
- 05カスタムログの取り込み
活用シーン
- 01Node.js サービスのテレメトリ収集
- 02カスタムスパンとメトリックの追加
- 03サンプリングによるトレース量の削減
- 04カスタムログの Azure Monitor への送信
インストール
コマンドをコピーしてターミナルで実行します。
npx skills add https:/ / github.com/ sickn33/ agentic-awesome-skills --skill azure-monitor-opentelemetry-tsインストール後、Claude Code で/azure-monitor-opentelemetry-tsを入力して読み込まれたか確認します。
詳細
TypeScript 用 Azure Monitor OpenTelemetry SDK
分散トレース、メトリクス、ログを使用して Node.js アプリケーションを自動計装します。
バージョンとデータの境界
このドキュメントでは、既存の @azure/monitor-opentelemetry ディストリビューションについて説明します。現在、Microsoft のガイダンスでは新規導入向けに @microsoft/opentelemetry も案内されています。両方を初期化しないでください。すべての OpenTelemetry パッケージのバージョンを一致させ、そのバージョンのロガープロバイダーのコンストラクター/プロセッサー API を使用してください。承認済みのテレメトリ送信先を設定し、PII/シークレットをマスキングし、オフラインストレージを保護してください。自動計装によって、機密性の高いリクエスト/ログデータがエクスポートされる場合があります。Microsoft の有効化ガイダンスを参照してください。
インストール
# 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
環境変数
APPLICATIONINSIGHTS_CONNECTION_STRING=InstrumentationKey=...;IngestionEndpoint=...
クイックスタート(自動計装)
重要: 他のモジュールをインポートする前に useAzureMonitor() を呼び出してください。
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 のサポート(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"
}
}
完全な構成
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);
カスタムトレース
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();
}
カスタムメトリクス
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" });
});
エクスポーターの手動設定
トレースエクスポーター
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();
メトリクスエクスポーター
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);
ログエクスポーター
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);
カスタムログの取り込み
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);
}
}
}
カスタムスパン処理
onStart で span.setAttribute() を使用して、書き込み可能なスパンを拡張してください。onEnd で ReadableSpan.attributes や spanContext().traceFlags を変更しないでください。終了済みのスパンは読み取り専用であり、これらの変更は信頼できるエクスポートフィルターにはなりません。固定された SDK バージョンでサポートされているサンプラー、またはレビュー済みのフィルタリングエクスポーター/プロセッサーパイプラインを使用し、エクスポートされるデータを確認してください。
サンプリング
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 });
シャットダウン
import { useAzureMonitor, shutdownAzureMonitor } from "@azure/monitor-opentelemetry";
useAzureMonitor();
// On application shutdown
process.on("SIGTERM", async () => {
await shutdownAzureMonitor();
process.exit(0);
});
主な型
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";
ベストプラクティス
- 最初に useAzureMonitor() を呼び出す - 他のモジュールをインポートする前に呼び出します
- ESM プロジェクトでは ESM ローダーを使用する -
--import @azure/monitor-opentelemetry/loader - オフラインストレージを有効にする - 接続が切断される状況でも、テレメトリを確実に送信できます
- サンプリング比率を設定する - トラフィックの多いアプリケーション向けです
- カスタムディメンションを追加する - スパンプロセッサーを使用して情報を付加します
- 正常にシャットダウンする -
shutdownAzureMonitor()を呼び出してテレメトリをフラッシュします
使用する場合
このスキルは、概要で説明されているワークフローやアクションを実行する場合に適用できます。
制限事項
- このスキルは、タスクが上記の範囲に明確に該当する場合にのみ使用してください。
- 出力を、環境固有の検証、テスト、または専門家によるレビューの代わりとして扱わないでください。
- 必要な入力、権限、安全性の境界、または成功基準が不足している場合は、作業を中断して確認してください。