Skip to content

使用 Azure Monitor OpenTelemetry 为 Node.js 实现全链路追踪

解决 Node.js 应用在复杂微服务环境下难以定位性能瓶颈和错误的问题,通过自动化插桩快速实现分布式追踪(Tracing)、指标(Metrics)和日志(Logs)的统一采集。

为什么需要这个技能

在分布式系统中,一个请求可能会跨越多个服务。传统的本地日志无法还原完整的请求路径,导致排查问题时需要在多个日志文件中手动比对时间戳。

通过集成 OpenTelemetry 和 Azure Monitor,开发者可以实现“零代码”或“低代码”的自动化插桩。它能够自动捕捉 HTTP 请求、数据库查询(MongoDB, MySQL, PostgreSQL 等)以及 Redis 调用,将这些碎片信息串联成一个完整的调用链,极大地缩短了从发现问题到定位根因(Root Cause)的时间。

适用场景

  • 快速集成监控:需要快速为现有 Node.js 项目添加性能监控,而不想手动编写大量埋点代码。
  • 微服务链路分析:需要分析请求在多个服务之间的流转路径及耗时。
  • 自定义业务指标:需要记录特定业务操作的计数(Counter)或分布(Histogram)以监控系统健康度。
  • 云原生迁移:将应用迁移至 Azure 并在 Application Insights 中进行统一观测。

核心工作流

1. 安装与初始化

首先安装核心 SDK,并在应用启动的最早阶段调用 useAzureMonitor(),确保在其他模块加载前完成插桩。

bash
npm install @azure/monitor-opentelemetry
typescript
import { useAzureMonitor } from "@azure/monitor-opentelemetry";

useAzureMonitor({
  azureMonitorExporterOptions: {
    connectionString: process.env.APPLICATIONINSIGHTS_CONNECTION_STRING
  }
});

// 必须在 useAzureMonitor 之后导入业务模块
import express from "express";

2. 进阶配置与采样

针对高流量应用,可以通过配置 samplingRatio 降低采样率,或通过 instrumentationOptions 精确控制需要监控的库。

typescript
const options: AzureMonitorOpenTelemetryOptions = {
  samplingRatio: 0.75, // 采样 75% 的追踪数据
  instrumentationOptions: {
    http: { enabled: true },
    mongoDb: { enabled: true },
    redis: { enabled: true },
  },
  resource: resourceFromAttributes({ "service.name": "order-service" })
};
useAzureMonitor(options);

3. 实现自定义观测

当自动插桩无法覆盖业务逻辑时,可以使用 OpenTelemetry API 手动创建 Span 或 Metric。

typescript
import { trace } from "@opentelemetry/api";
const tracer = trace.getTracer("my-tracer");

const span = tracer.startSpan("processPayment");
try {
  span.setAttribute("payment.id", "12345");
  // 业务逻辑
} catch (error) {
  span.recordException(error as Error);
} finally {
  span.end();
}

下载和安装

下载 azure-monitor-opentelemetry-ts 中文版 Skill ZIP

解压后将目录放入你的 AI 工具 skills 文件夹,重启工具后即可使用。具体路径参考内附的 USAGE.zh.md

你可能还需要

暂无推荐