关于 sentry-node-sdk
面向 Node.js、Bun 和 Deno 服务端 JavaScript/TypeScript 项目的 Sentry 配置技能,可扫描运行时和框架并引导安装与配置。它依据项目中的日志、定时任务、AI 库及 OpenTelemetry 使用情况提供建议。
主要功能
- 01识别 Node.js、Bun 或 Deno 运行时
- 02检测框架及现有 Sentry 配置
- 03引导 SDK 安装和启动配置
- 04配置错误监控与追踪
- 05按需设置日志、性能分析和定时任务监控
适用场景
- 01为服务端 JavaScript 项目接入 Sentry
- 02根据运行时配置错误与追踪监控
- 03为定时任务或 AI 调用添加监控
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ getsentry/ sentry-for-ai --skill sentry-node-sdk安装后在 Claude Code 中输入/sentry-node-sdk确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
references/ai-monitoring.mdcrons.mderror-monitoring.mdlogging.mdmetrics.mdprofiling.mdtracing.md详细介绍
Sentry Node.js / Bun / Deno SDK
一款具有明确指导性的向导,可扫描你的项目,并引导你为服务端 JavaScript 和 TypeScript 运行时(Node.js、Bun 和 Deno)完成 Sentry 的完整配置。
适用场景
- 用户要求“为 Node.js 添加 Sentry”、使用“Bun”或“Deno”
- 用户想要安装或配置
@sentry/node、@sentry/bun或@sentry/deno - 用户想为后端 JS/TS 应用启用错误监控、追踪、日志、性能分析、定时任务、指标或 AI 监控
- 用户询问
instrument.js、--import ./instrument.mjs、bun --preload或npm:@sentry/deno - 用户想监控 Express、Fastify、Koa、Hapi、Connect、Bun.serve() 或 Deno.serve()
使用 NestJS? 请改用
sentry-nestjs-sdk——它使用@sentry/nestjs以及 NestJS 原生装饰器和过滤器。 使用 Next.js? 请改用sentry-nextjs-sdk——它负责处理三运行时架构(浏览器、服务端、边缘)。
注意: 此处列出的 SDK 版本依据撰写时 Sentry 文档中的当前信息(
@sentry/node≥10.42.0、@sentry/bun≥10.42.0、@sentry/deno≥10.42.0)。 实施前,请务必对照 docs.sentry.io/platforms/javascript/guides/node/ 进行验证。
阶段 1:检测
运行以下命令,以识别运行时、框架和现有的 Sentry 配置:
# Detect runtime
bun --version 2>/dev/null && echo "Bun detected"
deno --version 2>/dev/null && echo "Deno detected"
node --version 2>/dev/null && echo "Node.js detected"
# Detect existing Sentry packages
cat package.json 2>/dev/null | grep -E '"@sentry/'
cat deno.json deno.jsonc 2>/dev/null | grep -i sentry
# Detect Node.js framework
cat package.json 2>/dev/null | grep -E '"express"|"fastify"|"@hapi/hapi"|"koa"|"@nestjs/core"|"connect"'
# Detect Bun-specific frameworks
cat package.json 2>/dev/null | grep -E '"elysia"|"hono"'
# Detect Deno frameworks (deno.json imports)
cat deno.json deno.jsonc 2>/dev/null | grep -E '"oak"|"hono"|"fresh"'
# Detect module system (Node.js)
cat package.json 2>/dev/null | grep '"type"'
ls *.mjs *.cjs 2>/dev/null | head -5
# Detect existing instrument file
ls instrument.js instrument.mjs instrument.ts instrument.cjs 2>/dev/null
# Detect logging libraries
cat package.json 2>/dev/null | grep -E '"winston"|"pino"|"bunyan"'
# Detect cron / scheduling
cat package.json 2>/dev/null | grep -E '"node-cron"|"cron"|"agenda"|"bull"|"bullmq"'
# Detect AI / LLM usage
cat package.json 2>/dev/null | grep -E '"openai"|"@anthropic-ai"|"@langchain"|"@vercel/ai"|"@google/generative-ai"'
# Detect OpenTelemetry tracing
cat package.json 2>/dev/null | grep -E '"@opentelemetry/sdk-node"|"@opentelemetry/sdk-trace-node"|"@opentelemetry/sdk-trace-base"'
grep -rn "NodeTracerProvider\|trace\.getTracer\|startActiveSpan" \
--include="*.ts" --include="*.js" --include="*.mjs" 2>/dev/null | head -5
# Check for companion frontend
ls frontend/ web/ client/ ui/ 2>/dev/null
cat package.json 2>/dev/null | grep -E '"react"|"vue"|"svelte"|"next"'
需要确定的事项:
| 问题 | 影响 |
|---|---|
| 使用哪种运行时?(Node.js / Bun / Deno) | 决定使用哪个软件包、初始化模式和预加载标志 |
| Node.js:使用 ESM 还是 CJS? | ESM 需要 --import ./instrument.mjs;CJS 使用 require("./instrument") |
| 检测到哪个框架? | 决定注册哪个错误处理器 |
是否已安装 @sentry/*? | 跳过安装,直接配置功能 |
是否已存在 instrument.js / instrument.mjs? | 将配置合并到现有文件中,而不是覆盖 |
| 是否检测到日志库? | 建议使用 Sentry Logs |
| 是否检测到定时任务 / 作业调度器? | 建议启用 Crons 监控 |
| 是否检测到 AI 库? | 建议启用 AI 监控 |
| 是否检测到 OpenTelemetry 追踪? | 使用 OTLP 路径,而不是原生追踪 |
| 是否找到配套的前端? | 触发阶段 4 的交叉链接 |
阶段 2:推荐
根据发现的情况提出具体建议。不要提出开放式问题,而是直接给出方案:
根据 OTel 检测结果选择方案:
- 检测到 OTel 跟踪(
package.json中包含@opentelemetry/sdk-node或@opentelemetry/sdk-trace-node,或源代码中包含NodeTracerProvider)→ 使用 OTLP 路径:通过@sentry/node-core/light使用otlpIntegration();不要设置tracesSampleRate;Sentry 会自动将错误关联到 OTel 跟踪
推荐(核心覆盖):
- ✅ 错误监控 — 始终启用;捕获未处理的异常、Promise 拒绝和框架错误
- ✅ 跟踪 — 通过 OpenTelemetry 自动检测 HTTP、数据库和队列
可选(增强可观测性):
- ⚡ 日志记录 — 通过
Sentry.logger.*记录结构化日志;使用winston/pino/bunyan或需要搜索日志时推荐启用 - ⚡ 性能分析 — 持续进行 CPU 性能分析(仅限 Node.js;Bun 或 Deno 不支持);OTLP 路径不可用
- ⚡ AI 监控 — OpenAI、Anthropic、LangChain、Vercel AI SDK;检测到 AI/LLM 调用时推荐启用
- ⚡ 定时任务 — 检测遗漏或失败的计划任务;检测到 node-cron、Bull 或 Agenda 时推荐启用
- ⚡ 指标 — 自定义计数器、仪表盘和分布;需要自定义 KPI 时推荐启用
- ⚡ 运行时指标 — 自动收集内存、CPU 和事件循环指标;
nodeRuntimeMetricsIntegration()(Node.js)/bunRuntimeMetricsIntegration()(Bun)
推荐逻辑:
| 功能 | 推荐条件…… |
|---|---|
| 错误监控 | 始终启用 — 不可或缺的基础配置 |
| OTLP 集成 | 检测到 OTel 跟踪 — 取代原生跟踪 |
| 跟踪 | 服务器应用始终启用 — HTTP span 和数据库 span 价值很高;检测到 OTel 跟踪时跳过 |
| 日志记录 | 应用使用 winston、pino、bunyan,或需要日志与跟踪关联 |
| 性能分析 | 仅限 Node.js — 对性能要求高的服务;原生插件兼容;检测到 OTel 跟踪时跳过(需要 tracesSampleRate,与 OTLP 不兼容) |
| AI 监控 | 应用调用 OpenAI、Anthropic、LangChain、Vercel AI 或 Google GenAI |
| 定时任务 | 应用使用 node-cron、Bull、BullMQ、Agenda 或任何计划任务模式 |
| 指标 | 应用需要自定义计数器、仪表盘或直方图 |
| 运行时指标 | 任何希望自动了解内存、CPU 和事件循环情况的 Node.js 或 Bun 服务 |
检测到 OTel 跟踪: “我发现项目中使用了 OpenTelemetry 跟踪。我建议使用 Sentry 的 OTLP 集成进行跟踪(通过现有的 OTel 配置)+ 错误监控 + Sentry 日志记录 [+ 适用时添加指标/定时任务/AI 监控]。要继续吗?”
未检测到 OTel: “我建议配置错误监控 + 跟踪。还要添加日志记录或性能分析吗?”
阶段 3:指导
运行时:Node.js
选项 1:向导(推荐用于 Node.js)
你需要自行运行此命令 — 向导会打开浏览器进行登录,并要求交互式输入,Agent 无法代为完成。请复制并粘贴到终端:
npx @sentry/wizard@latest -i node向导会处理登录、组织/项目选择、SDK 安装、
instrument.js创建以及 package.json 脚本更新。完成后,请返回并跳到验证。
如果用户跳过向导,请使用下面的选项 2(手动配置)。
选项 2:手动配置 — Node.js
安装
npm install @sentry/node --save
# or
yarn add @sentry/node
# or
pnpm add @sentry/node
创建 Instrument 文件
CommonJS(instrument.js):
// instrument.js — must be loaded before all other modules
const Sentry = require("@sentry/node");
Sentry.init({
dsn: process.env.SENTRY_DSN ?? "___DSN___",
dataCollection: {
// To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit:
// https://docs.sentry.io/platforms/javascript/guides/node/configuration/options/#dataCollection
// userInfo: false,
// httpBodies: [],
},
// 100% in dev, lower in production
tracesSampleRate: process.env.NODE_ENV === "development" ? 1.0 : 0.1,
// Capture local variable values in stack frames
includeLocalVariables: true,
enableLogs: true,
});
ESM(instrument.mjs):
// instrument.mjs — loaded via --import flag before any other module
import * as Sentry from "@sentry/node";
Sentry.init({
dsn: process.env.SENTRY_DSN ?? "___DSN___",
dataCollection: {
// To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit:
// https://docs.sentry.io/platforms/javascript/guides/node/configuration/options/#dataCollection
// userInfo: false,
// httpBodies: [],
},
tracesSampleRate: process.env.NODE_ENV === "development" ? 1.0 : 0.1,
includeLocalVariables: true,
enableLogs: true,
});
首先加载 Sentry,再启动应用
CommonJS — 在入口文件的第一行添加 require("./instrument"):
// app.js
require("./instrument"); // must be first
const express = require("express");
// ... rest of your app
ESM — 使用 --import 标志,确保 Sentry 在所有其他模块之前加载(需要 Node.js 18.19.0+):
node --import ./instrument.mjs app.mjs
添加到 package.json 脚本中:
{
"scripts": {
"start": "node --import ./instrument.mjs server.mjs",
"dev": "node --import ./instrument.mjs --watch server.mjs"
}
}
或者通过环境变量设置(适用于包装现有的启动命令):
NODE_OPTIONS="--import ./instrument.mjs" npm start
框架错误处理器
请在所有路由之后注册 Sentry 错误处理器,以便捕获框架错误:
Express:
const express = require("express");
const Sentry = require("@sentry/node");
const app = express();
// ... your routes
// Add AFTER all routes — captures 5xx errors by default
Sentry.setupExpressErrorHandler(app);
// Optional: capture 4xx errors too
// Sentry.setupExpressErrorHandler(app, {
// shouldHandleError(error) { return error.status >= 400; },
// });
app.listen(3000);
Fastify:
const Fastify = require("fastify");
const Sentry = require("@sentry/node");
const fastify = Fastify();
// Add BEFORE routes (unlike Express!)
Sentry.setupFastifyErrorHandler(fastify);
// ... your routes
await fastify.listen({ port: 3000 });
Koa:
const Koa = require("koa");
const Sentry = require("@sentry/node");
const app = new Koa();
// Add as FIRST middleware (catches errors thrown by later middleware)
Sentry.setupKoaErrorHandler(app);
// ... your other middleware and routes
app.listen(3000);
Hapi(异步——必须等待):
const Hapi = require("@hapi/hapi");
const Sentry = require("@sentry/node");
const server = Hapi.server({ port: 3000 });
// ... your routes
// Must await — Hapi registration is async
await Sentry.setupHapiErrorHandler(server);
await server.start();
Connect:
const connect = require("connect");
const Sentry = require("@sentry/node");
const app = connect();
// Add BEFORE routes (like Fastify and Koa)
Sentry.setupConnectErrorHandler(app);
// ... your middleware and routes
require("http").createServer(app).listen(3000);
NestJS — 有专门的技能,提供完整支持:
请改用
sentry-nestjs-sdk技能。 NestJS 使用单独的程序包(@sentry/nestjs),其中包含 NestJS 原生构造:SentryModule.forRoot()、SentryGlobalFilter、@SentryTraced、@SentryCron装饰器, 以及 GraphQL/微服务支持。请加载该技能以完成 NestJS 设置。
原生 Node.js http 模块 — 手动包装请求处理器:
const http = require("http");
const Sentry = require("@sentry/node");
const server = http.createServer((req, res) => {
Sentry.withIsolationScope(() => {
try {
// your handler
res.end("OK");
} catch (err) {
Sentry.captureException(err);
res.writeHead(500);
res.end("Internal Server Error");
}
});
});
server.listen(3000);
框架错误处理器摘要:
| 框架 | 函数 | 放置位置 | 异步? |
|---|---|---|---|
| Express | setupExpressErrorHandler(app) | 所有路由之后 | 否 |
| Fastify | setupFastifyErrorHandler(fastify) | 路由之前 | 否 |
| Koa | setupKoaErrorHandler(app) | 第一个中间件 | 否 |
| Hapi | setupHapiErrorHandler(server) | 在 server.start() 之前 | 是 |
| Connect | setupConnectErrorHandler(app) | 路由之前 | 否 |
| NestJS | → 请使用 sentry-nestjs-sdk | 专门技能 | — |
运行时:Bun
**Bun 不提供向导。**只能手动设置。
安装
bun add @sentry/bun
创建 instrument.ts(或 instrument.js)
// instrument.ts
import * as Sentry from "@sentry/bun";
Sentry.init({
dsn: process.env.SENTRY_DSN ?? "___DSN___",
dataCollection: {
// To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit:
// https://docs.sentry.io/platforms/javascript/guides/node/configuration/options/#dataCollection
// userInfo: false,
// httpBodies: [],
},
tracesSampleRate: process.env.NODE_ENV === "development" ? 1.0 : 0.1,
enableLogs: true,
});
使用 --preload 启动应用
bun --preload ./instrument.ts server.ts
添加到 package.json:
{
"scripts": {
"start": "bun --preload ./instrument.ts server.ts",
"dev": "bun --watch --preload ./instrument.ts server.ts"
}
}
Bun.serve() — 自动检测
@sentry/bun 通过 JavaScript Proxy 自动检测 Bun.serve()。无需额外设置——只需使用 --preload 初始化,Bun.serve() 调用就会被追踪:
// server.ts
const server = Bun.serve({
port: 3000,
fetch(req) {
return new Response("Hello from Bun!");
},
});
Bun 上的框架错误处理器
Bun 可以运行 Express、Fastify、Hono 和 Elysia。使用相同的 @sentry/bun 导入以及 @sentry/node 错误处理器函数(由 @sentry/bun 重新导出):
import * as Sentry from "@sentry/bun";
import express from "express";
const app = express();
// ... routes
Sentry.setupExpressErrorHandler(app);
app.listen(3000);
Bun 功能支持
| 功能 | Bun 支持情况 | 说明 |
|---|---|---|
| 错误监控 | ✅ 完全支持 | 与 Node 使用相同的 API |
| 追踪 | ✅ 通过 @sentry/node OTel | 大多数自动检测功能均可使用 |
| 日志 | ✅ 完全支持 | enableLogs: true + Sentry.logger.* |
| 性能分析 | ❌ 不可用 | @sentry/profiling-node 使用了与 Bun 不兼容的原生扩展 |
| 指标 | ✅ 完全支持 | Sentry.metrics.* |
| 运行时指标 | ✅ 完全支持 | bunRuntimeMetricsIntegration() — 内存、CPU、事件循环(不提供事件循环延迟百分位数) |
| 定时任务 | ✅ 完全支持 | Sentry.withMonitor() |
| AI 监控 | ✅ 完全支持 | OpenAI、Anthropic 集成都可使用 |
运行时:Deno
**Deno 不提供向导。**只能手动设置。 **需要 Deno 2.0+。**不支持 Deno 1.x。 请使用
npm:说明符。deno.land/x/sentry注册表已弃用。
通过 deno.json 安装(推荐)
{
"imports": {
"@sentry/deno": "npm:@sentry/[email protected]"
}
}
或者使用 npm: 说明符直接导入:
import * as Sentry from "npm:@sentry/deno";
初始化 — 添加到入口文件
// main.ts — Sentry.init() must be called before any other code
import * as Sentry from "@sentry/deno";
Sentry.init({
dsn: Deno.env.get("SENTRY_DSN") ?? "___DSN___",
dataCollection: {
// To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit:
// https://docs.sentry.io/platforms/javascript/guides/node/configuration/options/#dataCollection
// userInfo: false,
// httpBodies: [],
},
tracesSampleRate: Deno.env.get("DENO_ENV") === "development" ? 1.0 : 0.1,
enableLogs: true,
});
// Your application code follows
Deno.serve({ port: 8000 }, (req) => {
return new Response("Hello from Deno!");
});
与 Node.js 和 Bun 不同,Deno 没有
--preload或--import标志。Sentry 必须是入口文件中的第一个import。
所需的 Deno 权限
SDK 需要网络访问权限,以连接到 Sentry 数据接收域:
deno run \
--allow-net=o<ORG_ID>.ingest.sentry.io \
--allow-read=./src \
--allow-env=SENTRY_DSN,SENTRY_RELEASE \
main.ts
在开发环境中,可以使用 --allow-all,但不建议在生产环境中使用。
Deno 定时任务集成
Deno 提供原生定时任务调度。使用 denoCronIntegration 自动进行监控:
import * as Sentry from "@sentry/deno";
import { denoCronIntegration } from "@sentry/deno";
Sentry.init({
dsn: Deno.env.get("SENTRY_DSN") ?? "___DSN___",
integrations: [denoCronIntegration()],
});
// Cron is automatically monitored
Deno.cron("daily-cleanup", "0 0 * * *", () => {
// cleanup logic
});
Deno 功能支持
| 功能 | Deno 支持情况 | 说明 |
|---|---|---|
| 错误监控 | ✅ 完全支持 | 未处理的异常 + captureException |
| 追踪 | ✅ 自定义 OTel | 为 Deno.serve() 和 fetch 自动创建 Span |
| 日志 | ✅ 完全支持 | enableLogs: true + Sentry.logger.* |
| 性能分析 | ❌ 不可用 | Deno 没有性能分析插件 |
| 指标 | ✅ 完全支持 | Sentry.metrics.* |
| 运行时指标 | ❌ 不可用 | Deno 没有运行时指标集成 |
| 定时任务 | ✅ 完全支持 | denoCronIntegration() + Sentry.withMonitor() |
| AI 监控 | ✅ 部分支持 | Vercel AI SDK 集成可用;OpenAI/Anthropic 通过 npm: 使用 |
OTLP 集成(以 OTel 为首选的项目——仅限 Node.js)
仅当在第 1 阶段检测到 OpenTelemetry 追踪时,才使用此路径 (例如,
package.json中包含@opentelemetry/sdk-node或@opentelemetry/sdk-trace-node)。 对于没有现有 OTel 配置的项目,请使用上文的标准@sentry/node路径。
OTLP 集成使用 @sentry/node-core/light——这是一个轻量级的 Sentry SDK,不会捆绑自己的 OpenTelemetry。它会接入用户现有的 OTel TracerProvider,并通过 OTLP 将 Span 导出到 Sentry。
适用场景
| 场景 | 推荐路径 |
|---|---|
| 新项目,没有现有 OTel | 标准 @sentry/node(上文)——内置 OTel |
| 已有 OTel 配置,希望使用 Sentry 追踪 | @sentry/node-core/light + otlpIntegration() |
| 已有 OTel 配置,要发送到自己的 Collector | @sentry/node-core/light + otlpIntegration({ collectorUrl }) |
安装
npm install @sentry/node-core @opentelemetry/api @opentelemetry/sdk-trace-node @opentelemetry/sdk-trace-base
# or
yarn add @sentry/node-core @opentelemetry/api @opentelemetry/sdk-trace-node @opentelemetry/sdk-trace-base
# or
pnpm add @sentry/node-core @opentelemetry/api @opentelemetry/sdk-trace-node @opentelemetry/sdk-trace-base
@opentelemetry/*包是对等依赖。如果项目已安装这些包,请跳过重复安装。
初始化
// instrument.mjs — load via --import flag before any other module
import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node';
import * as Sentry from '@sentry/node-core/light';
import { otlpIntegration } from '@sentry/node-core/light/otlp';
// Register the user's OTel TracerProvider first
const provider = new NodeTracerProvider();
provider.register();
Sentry.init({
dsn: process.env.SENTRY_DSN ?? '___DSN___',
dataCollection: {
// To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit:
// https://docs.sentry.io/platforms/javascript/guides/node/configuration/options/#dataCollection
// userInfo: false,
// httpBodies: [],
},
enableLogs: true,
// Do NOT set tracesSampleRate — OTel controls sampling
integrations: [
otlpIntegration({
// Export OTel spans to Sentry via OTLP (default: true)
setupOtlpTracesExporter: true,
}),
],
});
使用自定义 Collector 端点:
Sentry.init({
dsn: process.env.SENTRY_DSN ?? '___DSN___',
integrations: [
otlpIntegration({
collectorUrl: 'http://localhost:4318/v1/traces',
}),
],
});
启动应用
与标准 Node.js 配置使用相同的 --import 模式:
node --import ./instrument.mjs app.mjs
与标准 @sentry/node 的主要区别
| 方面 | @sentry/node(标准) | @sentry/node-core/light(OTLP) |
|---|---|---|
| 是否捆绑 OTel | ✅ 是——内置 TracerProvider | ❌ 否——使用现有的 Provider |
| 追踪控制 | Sentry.init() 中的 tracesSampleRate | OTel SDK 控制采样 |
| 自动插桩 | ✅ 内置(HTTP、DB 等) | ❌ 由你管理 OTel 插桩 |
| 性能分析 | ✅ 可用 | ❌ 不兼容 |
| 错误与追踪关联 | ✅ 自动 | ✅ 自动(通过 otlpIntegration) |
| 包大小 | 较大(包含 OTel) | 较小(轻量模式) |
对每项已商定的功能
加载相应的参考文件并遵循其中的步骤:
| 功能 | 参考文件 | 在以下情况下加载…… |
|---|---|---|
| 错误监控 | references/error-monitoring.md | 始终加载(基线)——捕获、作用域、丰富信息、beforeSend |
| OTLP 集成 | 参见上文 OTLP 集成 | 检测到 OTel 追踪——替代原生追踪 |
| 追踪 | references/tracing.md | OTel 自动插桩、自定义 Span、分布式追踪、采样;如果检测到 OTel 追踪,则跳过 |
| 日志 | references/logging.md | 结构化日志、Sentry.logger.*、日志与追踪的关联 |
| 性能分析 | references/profiling.md | 仅限 Node.js——文档记录了 Bun/Deno 的限制;如果检测到 OTel 追踪,则跳过 |
| 指标 | references/metrics.md | 自定义计数器、仪表、分布 |
| 运行时指标 | 见下文内嵌内容 | Node.js 和 Bun 的自动内存、CPU 和事件循环指标 |
| 定时任务 | references/crons.md | 定时任务监控、node-cron、Bull、Agenda、Deno.cron |
| AI 监控 | 加载 sentry-setup-ai-monitoring 技能 | OpenAI、Anthropic、LangChain、Vercel AI、Google GenAI |
对于每项功能:阅读参考文件,严格遵循其中的步骤,并在继续之前进行验证。
运行时指标
按可配置的间隔自动收集 Node.js 和 Bun 的运行时健康指标(内存、CPU 利用率、事件循环延迟/利用率、运行时间)。这些指标会显示在 Sentry 的 Metrics 产品中,位于 node.runtime.* / bun.runtime.* 命名空间下。
Node.js — 在 instrument.js 中添加 nodeRuntimeMetricsIntegration():
const Sentry = require("@sentry/node");
Sentry.init({
dsn: process.env.SENTRY_DSN,
integrations: [
Sentry.nodeRuntimeMetricsIntegration(),
// Optional: change collection interval (default 30 000 ms)
// Sentry.nodeRuntimeMetricsIntegration({ collectionIntervalMs: 60_000 }),
],
});
默认收集的指标:node.runtime.mem.rss、node.runtime.mem.heap_used、node.runtime.mem.heap_total、node.runtime.cpu.utilization、node.runtime.event_loop.delay.p50、node.runtime.event_loop.delay.p99、node.runtime.event_loop.utilization、node.runtime.process.uptime。
Bun — 在 instrument.ts 中添加 bunRuntimeMetricsIntegration():
import * as Sentry from "@sentry/bun";
import { bunRuntimeMetricsIntegration } from "@sentry/bun";
Sentry.init({
dsn: process.env.SENTRY_DSN,
integrations: [
bunRuntimeMetricsIntegration(),
// Optional: change collection interval (default 30 000 ms)
// bunRuntimeMetricsIntegration({ collectionIntervalMs: 60_000 }),
],
});
收集的指标:与 Node.js 相同,但不包括事件循环延迟百分位数(Bun 中不可用)。前缀为 bun.runtime.*。
配置参考
Sentry.init() 核心选项
| 选项 | 类型 | 默认值 | 备注 |
|---|---|---|---|
dsn | string | — | 必填。也可通过 SENTRY_DSN 环境变量设置 |
tracesSampleRate | number | — | 0–1;启用追踪必填;使用 OTLP 路径时不要设置 |
dataCollection | object | 未设置时采用保守配置 | 对自动收集的类别(userInfo、cookies、httpHeaders、httpBodies、queryParams、genAI)进行精细控制。省略时,SDK 会回退至 sendDefaultPii(默认值为 false)。传入该对象(即使是 {})也会将未设置类别切换为宽松默认值;可按类别选择退出。 |
includeLocalVariables | boolean | false | 将局部变量值添加到堆栈帧中(Node.js) |
enableLogs | boolean | false | 启用 Sentry Logs 产品(v9.41.0+) |
environment | string | "production" | 也可通过 SENTRY_ENVIRONMENT 环境变量设置 |
release | string | — | 也可通过 SENTRY_RELEASE 环境变量设置 |
debug | boolean | false | 将 SDK 活动记录到控制台 |
enabled | boolean | true | 在测试中设为 false 可禁用发送 |
sampleRate | number | 1.0 | 要发送的错误事件比例(0–1) |
shutdownTimeout | number | 2000 | 进程退出前刷新事件的毫秒数 |
nativeNodeFetchIntegration() 选项
配置传出的 fetch/undici Span 捕获。自 @opentelemetry/[email protected] 起,不再自动捕获 content-length 等响应标头;使用 headersToSpanAttributes 可选择启用:
Sentry.init({
integrations: [
Sentry.nativeNodeFetchIntegration({
headersToSpanAttributes: {
requestHeaders: ["x-request-id"],
responseHeaders: ["content-length", "content-type"],
},
}),
],
});
| 选项 | 类型 | 默认值 | 备注 |
|---|---|---|---|
breadcrumbs | boolean | true | 为传出的 fetch 请求记录面包屑 |
headersToSpanAttributes.requestHeaders | string[] | — | 要作为 Span 属性捕获的请求标头名称 |
headersToSpanAttributes.responseHeaders | string[] | — | 要作为 Span 属性捕获的响应标头名称 |
otlpIntegration() 选项(@sentry/node-core/light/otlp)
适用于使用 @sentry/node-core/light 的 OTel 优先项目。导入方式:import { otlpIntegration } from '@sentry/node-core/light/otlp'。
| 选项 | 类型 | 默认值 | 用途 |
|---|---|---|---|
setupOtlpTracesExporter | boolean | true | 自动配置 OTLP 导出器,将 Span 发送到 Sentry;如果已将数据导出到自己的 Collector,则设为 false |
collectorUrl | string | undefined | OTel Collector 的 OTLP HTTP 端点(例如 http://localhost:4318/v1/traces);设置后,Span 会发送到该 Collector,而不是根据 DSN 推导出的 Sentry 端点 |
优雅关闭
在进程退出前刷新缓冲的事件——这对短时运行的脚本和无服务器环境很重要:
process.on("SIGTERM", async () => {
await Sentry.close(2000); // flush with 2s timeout
process.exit(0);
});
环境变量
| 变量 | 用途 | 运行时 |
|---|---|---|
SENTRY_DSN | DSN(可替代在 init() 中硬编码) | 全部 |
SENTRY_ENVIRONMENT | 部署环境 | 全部 |
SENTRY_RELEASE | 发布版本字符串(从 git 自动检测) | 全部 |
SENTRY_AUTH_TOKEN | Source map 上传令牌 | 构建时 |
SENTRY_ORG | Source map 上传所用的组织 slug | 构建时 |
SENTRY_PROJECT | Source map 上传所用的项目 slug | 构建时 |
NODE_OPTIONS | 为 ESM 设置 --import ./instrument.mjs | Node.js |
Source Maps(Node.js)
要在生产环境中获得可读的堆栈跟踪,需要使用 @sentry/cli 或 webpack/esbuild/rollup 插件上传 source maps,例如,在构建过程中添加 inject + upload 步骤:
{
"scripts": {
"build": "tsc && sentry-cli sourcemaps inject ./dist && sentry-cli sourcemaps upload ./dist"
}
}
上传需要 SENTRY_AUTH_TOKEN(构建时密钥)。如需创建令牌并将其配置到 CI 中,请参阅 sentry-source-maps。
验证
设置完成后,验证 Sentry 是否正在接收事件:
// Add temporarily to your entry file or a test route, then remove
import * as Sentry from "@sentry/node"; // or @sentry/bun / @sentry/deno
Sentry.captureException(new Error("Sentry test error — delete me"));
或者触发一个未处理的异常:
// In a route handler or startup — will be captured automatically
throw new Error("Sentry test error — delete me");
然后查看 Sentry 问题面板——错误应在约 30 秒内出现。
验证清单:
| 检查项 | 方法 |
|---|---|
| 已捕获错误 | 在处理程序中抛出错误,并在 Sentry Issues 中验证 |
| 跟踪正常工作 | 查看 Performance 选项卡——应显示 HTTP spans |
includeLocalVariables 正常工作 | Sentry 中的堆栈帧应显示变量值 |
| Source maps 正常工作 | 堆栈跟踪显示可读的文件名,而非压缩后的文件名 |
第 4 阶段:交叉链接
完成后端设置后,检查是否有配套服务:
# Frontend companion
ls frontend/ web/ client/ ui/ 2>/dev/null
cat package.json 2>/dev/null | grep -E '"react"|"vue"|"svelte"|"next"'
# Other backend services
ls ../go.mod ../requirements.txt ../Gemfile 2>/dev/null
如果发现前端、特定框架的 SDK 或其他后端,请推荐相应的技能:
专用 JavaScript 框架技能(优先于通用 node-sdk):
| 检测到 | 优先选择的技能 | 原因 |
|---|---|---|
NestJS(package.json 中包含 @nestjs/core) | sentry-nestjs-sdk | 使用 @sentry/nestjs,支持 NestJS 原生装饰器、过滤器和 GraphQL |
Next.js(package.json 中包含 next) | sentry-nextjs-sdk | 三运行时架构(浏览器、服务端、边缘),withSentryConfig,source map 上传 |
前端配套项:
| 检测到 | 推荐 |
|---|---|
React 应用(package.json 中包含 react) | sentry-react-sdk |
| Svelte/SvelteKit | sentry-svelte-sdk |
其他后端配套项:
| 检测到 | 推荐 |
|---|---|
Go 后端(go.mod) | sentry-go-sdk |
Python 后端(requirements.txt、pyproject.toml) | sentry-python-sdk |
Ruby 后端(Gemfile) | sentry-ruby-sdk |
使用相同的 DSN 或关联项目连接前端和后端,可启用分布式跟踪——在单个跟踪视图中查看跨越浏览器、API 服务和数据库的堆栈跟踪。
故障排查
| 问题 | 原因 | 解决方案 |
|---|---|---|
| 未显示事件 | instrument.js 加载过晚 | 确保它是第一个 require(),或通过 --import 或 --preload 加载 |
| 缺少追踪 Span | 未设置 tracesSampleRate | 在 Sentry.init() 中添加 tracesSampleRate: 1.0 |
| ESM 插桩不起作用 | 缺少 --import 标志 | 使用 node --import ./instrument.mjs 运行;在应用中执行 import "./instrument.mjs" 并不足够 |
在 Bun 上安装 @sentry/profiling-node 失败 | 原生插件不兼容 | Bun 不支持性能分析——移除 @sentry/profiling-node |
| Deno:未发送事件 | 缺少 --allow-net 权限 | 使用 --allow-net=o<ORG_ID>.ingest.sentry.io 运行 |
Deno:deno.land/x/sentry 不起作用 | 已弃用,且版本冻结在 v8.55.0 | 改用 npm:@sentry/deno 标识符 |
includeLocalVariables 未显示值 | 集成未激活或代码已压缩 | 确保在初始化时设置 includeLocalVariables: true;检查 Source Map |
| NestJS:未捕获错误 | SDK 错误或缺少过滤器 | 使用 sentry-nestjs-sdk——NestJS 需要 @sentry/nestjs,而不是 @sentry/node |
Hapi:setupHapiErrorHandler 时序问题 | 未等待调用完成 | 必须在 server.start() 之前执行 await Sentry.setupHapiErrorHandler(server) |
| 关闭时丢失事件 | 进程在刷新完成前退出 | 在 SIGTERM/SIGINT 处理程序中添加 await Sentry.close(2000) |
| 堆栈追踪显示压缩后的代码 | 未上传 Source Map | 在构建步骤中配置 @sentry/cli 上传 Source Map |
| 未显示追踪(OTLP) | 缺少 @opentelemetry/* 包或未添加 otlpIntegration | 确认已安装 @opentelemetry/sdk-trace-node;将 otlpIntegration() 添加到 integrations;不要设置 tracesSampleRate |
| OTLP:错误未关联到追踪 | 未注册 otlpIntegration | 确保 integrations 数组中包含 otlpIntegration()——它会注册传播上下文,将错误与 OTel 追踪关联起来 |
| 性能分析未启动(OTLP) | 性能分析需要 tracesSampleRate | 性能分析与 OTLP 路径不兼容;请改用标准的 @sentry/node 配置 |