🚀 快速安装
复制以下命令并运行,立即安装此 Skill:
npx skills add https://skills.sh/getsentry/sentry-for-ai/sentry-node-sdk
💡 提示:需要 Node.js 和 NPM
Sentry Node.js / Bun / Deno SDK
有主见的向导,扫描您的项目并引导您完成为服务端 JavaScript 和 TypeScript 运行时(Node.js、Bun 和 Deno)配置 Sentry 的完整流程。
何时调用此技能 (Invoke This Skill When)
- 用户要求“为 Node.js”、“Bun”或“Deno”添加 Sentry
- 用户想要安装或配置
@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:检测 (Phase 1: Detect)
运行以下命令以识别运行时、框架和现有的 Sentry 设置:
# 检测运行时 (Detect runtime)
bun --version 2>/dev/null && echo "检测到 Bun (Bun detected)"
deno --version 2>/dev/null && echo "检测到 Deno (Deno detected)"
node --version 2>/dev/null && echo "检测到 Node.js (Node.js detected)"
# 检测现有的 Sentry 包 (Detect existing Sentry packages)
cat package.json 2>/dev/null | grep -E '"@sentry/'
cat deno.json deno.jsonc 2>/dev/null | grep -i sentry
# 检测 Node.js 框架 (Detect Node.js framework)
cat package.json 2>/dev/null | grep -E '"express"|"fastify"|"@hapi/hapi"|"koa"|"@nestjs/core"|"connect"'
# 检测 Bun 特定框架 (Detect Bun-specific frameworks)
cat package.json 2>/dev/null | grep -E '"elysia"|"hono"'
# 检测 Deno 框架(deno.json 中的导入)(Detect Deno frameworks - deno.json imports)
cat deno.json deno.jsonc 2>/dev/null | grep -E '"oak"|"hono"|"fresh"'
# 检测模块系统(Node.js)(Detect module system - Node.js)
cat package.json 2>/dev/null | grep '"type"'
ls *.mjs *.cjs 2>/dev/null | head -5
# 检测现有的 instrument 文件 (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"'
# 检测 cron / 调度 (Detect cron / scheduling)
cat package.json 2>/dev/null | grep -E '"node-cron"|"cron"|"agenda"|"bull"|"bullmq"'
# 检测 AI / LLM 使用 (Detect AI / LLM usage)
cat package.json 2>/dev/null | grep -E '"openai"|"@anthropic-ai"|"@langchain"|"@vercel/ai"|"@google/generative-ai"'
# 检查配套前端 (Check for companion frontend)
ls frontend/ web/ client/ ui/ 2>/dev/null
cat package.json 2>/dev/null | grep -E '"react"|"vue"|"svelte"|"next"'
需要确定的内容 (What to determine):
| 问题 (Question) | 影响 (Impact) |
|---|---|
| 哪个运行时?(Node.js / Bun / Deno) | 决定包、初始化模式和预加载标志 |
| Node.js: ESM 还是 CJS? | ESM 需要 --import ./instrument.mjs;CJS 使用 require("./instrument") |
| 检测到框架? | 决定注册哪个错误处理器 |
@sentry/* 已安装? |
跳过安装,直接进入功能配置 |
instrument.js / instrument.mjs 已存在? |
合并到其中,而不是覆盖 |
| 检测到日志库? | 推荐 Sentry Logs |
| 检测到 cron / 任务调度器? | 推荐 Crons 监控 |
| 检测到 AI 库? | 推荐 AI 监控 (AI Monitoring) |
| 找到配套前端? | 触发阶段 4 交叉链接 (Trigger Phase 4 cross-link) |
阶段 2:推荐 (Phase 2: Recommend)
根据检测结果提出具体建议。不要问开放式问题——直接给出方案:
推荐(核心覆盖)(Recommended – core coverage):
- ✅ 错误监控 (Error Monitoring) — 始终推荐;捕获未处理的异常、未处理的 Promise 拒绝和框架错误
- ✅ 追踪 (Tracing) — 通过 OpenTelemetry 自动进行 HTTP、数据库和队列埋点
可选(增强可观测性)(Optional – enhanced observability):
- ⚡ 日志 (Logging) — 通过
Sentry.logger.*实现结构化日志;当检测到winston/pino/bunyan或需要日志搜索时推荐 - ⚡ 性能分析 (Profiling) — 持续 CPU 分析(仅限 Node.js;Bun 或 Deno 不可用)
- ⚡ AI 监控 (AI Monitoring) — OpenAI、Anthropic、LangChain、Vercel AI SDK;检测到 AI/LLM 调用时推荐
- ⚡ 定时任务 (Crons) — 检测错过的或失败的定时任务;检测到 node-cron、Bull 或 Agenda 时推荐
- ⚡ 指标 (Metrics) — 自定义计数器、仪表、分布;需要自定义 KPI 时推荐
推荐逻辑 (Recommendation logic):
| 功能 (Feature) | 推荐条件 (Recommend when…) |
|---|---|
| 错误监控 (Error Monitoring) | 始终 (Always) — 不可协商的基础 (non-negotiable baseline) |
| 追踪 (Tracing) | 始终用于服务端应用 (Always for server apps) — HTTP span + 数据库 span 价值很高 |
| 日志 (Logging) | 应用使用 winston、pino、bunyan,或需要日志与追踪关联时 (App uses winston, pino, bunyan, or needs log-to-trace correlation) |
| 性能分析 (Profiling) | 仅限 Node.js (Node.js only) — 性能关键型服务;兼容原生扩展 (performance-critical service; native addon compatible) |
| AI 监控 (AI Monitoring) | 应用调用 OpenAI、Anthropic、LangChain、Vercel AI 或 Google GenAI (App calls OpenAI, Anthropic, LangChain, Vercel AI, or Google GenAI) |
| 定时任务 (Crons) | 应用使用 node-cron、Bull、BullMQ、Agenda 或任何定时任务模式 (App uses node-cron, Bull, BullMQ, Agenda, or any scheduled task pattern) |
| 指标 (Metrics) | 应用需要自定义计数器、仪表或直方图 (App needs custom counters, gauges, or histograms) |
提议:“我建议设置错误监控 + 追踪。您需要我同时添加日志或性能分析吗?” (I recommend setting up Error Monitoring + Tracing. Want me to also add Logging or Profiling?)
阶段 3:引导 (Phase 3: Guide)
运行时:Node.js (Runtime: Node.js)
选项 1:向导(推荐用于 Node.js)(Option 1: Wizard – Recommended for Node.js)
您需要自己运行此命令 (You need to run this yourself) — 向导会打开浏览器进行登录,并需要智能体无法处理的交互式输入。复制粘贴到您的终端:
npx @sentry/wizard@latest -i node它处理登录、组织/项目选择、SDK 安装、
instrument.js创建和 package.json 脚本更新。完成后,返回并跳至 验证 (Verification)。
如果用户跳过向导,请继续下面的选项 2(手动设置)。
选项 2:手动设置 — Node.js (Option 2: Manual Setup — Node.js)
安装 (Install)
npm install @sentry/node --save
# 或 (or)
yarn add @sentry/node
# 或 (or)
pnpm add @sentry/node
创建 instrument 文件 (Create the Instrument File)
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___",
sendDefaultPii: true,
// 开发环境 100%,生产环境降低 (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 — 通过 --import 标志在其他模块之前加载 (loaded via --import flag before any other module)
import * as Sentry from "@sentry/node";
Sentry.init({
dsn: process.env.SENTRY_DSN ?? "___DSN___",
sendDefaultPii: true,
tracesSampleRate: process.env.NODE_ENV === "development" ? 1.0 : 0.1,
includeLocalVariables: true,
enableLogs: true,
});
首先加载 Sentry 启动您的应用 (Start Your App with Sentry Loaded First)
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
框架错误处理器 (Framework Error Handlers)
在所有路由之后注册 Sentry 错误处理器,以便捕获框架错误:
Express:
const express = require("express");
const Sentry = require("@sentry/node");
const app = express();
// ... 您的路由 (... your routes)
// 在所有路由之后添加 — 默认捕获 5xx 错误 (Add AFTER all routes — captures 5xx errors by default)
Sentry.setupExpressErrorHandler(app);
// 可选:也捕获 4xx 错误 (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();
// 在路由之前添加(与 Express 不同!)(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(异步 — 必须等待)(Hapi – async — must await):
const Hapi = require("@hapi/hapi");
const Sentry = require("@sentry/node");
const server = Hapi.server({ port: 3000 });
// ... 您的路由 (... your routes)
// 必须等待 — Hapi 注册是异步的 (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();
// 在路由之前添加(与 Fastify 和 Koa 类似)(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 模块 (Vanilla Node.js http module) — 手动包装请求处理器:
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);
框架错误处理器摘要 (Framework error handler summary):
| 框架 (Framework) | 函数 (Function) | 放置位置 (Placement) | 异步? (Async?) |
|---|---|---|---|
| Express | setupExpressErrorHandler(app) |
所有路由之后 (After) all routes | 否 (No) |
| Fastify | setupFastifyErrorHandler(fastify) |
路由之前 (Before) routes | 否 (No) |
| Koa | setupKoaErrorHandler(app) |
第一个 (First) middleware | 否 (No) |
| Hapi | setupHapiErrorHandler(server) |
server.start() 之前 (Before) |
是 (Yes) |
| Connect | setupConnectErrorHandler(app) |
路由之前 (Before) routes | 否 (No) |
| NestJS | → 使用 sentry-nestjs-sdk |
专用技能 (Dedicated skill) | — |
运行时:Bun (Runtime: Bun)
Bun 没有向导可用 (No wizard available for Bun)。 仅限手动设置。
安装 (Install)
bun add @sentry/bun
创建 instrument.ts(或 instrument.js)(Create instrument.ts – or instrument.js)
// instrument.ts
import * as Sentry from "@sentry/bun";
Sentry.init({
dsn: process.env.SENTRY_DSN ?? "___DSN___",
sendDefaultPii: true,
tracesSampleRate: process.env.NODE_ENV === "development" ? 1.0 : 0.1,
enableLogs: true,
});
使用 --preload 启动您的应用 (Start Your App with --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() — 自动埋点 (Auto-Instrumentation)
@sentry/bun 通过 JavaScript 代理自动对 Bun.serve() 进行埋点。无需额外设置 — 只需使用 --preload 初始化,您的 Bun.serve() 调用就会被追踪:
// server.ts
const server = Bun.serve({
port: 3000,
fetch(req) {
return new Response("Hello from Bun!");
},
});
Bun 上的框架错误处理器 (Framework Error Handlers on 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 Feature Support)
| 功能 (Feature) | Bun 支持 (Bun Support) | 说明 (Notes) |
|---|---|---|
| 错误监控 (Error Monitoring) | ✅ 完整 (Full) | 与 Node 相同的 API (Same API as Node) |
| 追踪 (Tracing) | ✅ 通过 @sentry/node OTel (Via @sentry/node OTel) |
大多数自动埋点有效 (Most auto-instrumentations work) |
| 日志 (Logging) | ✅ 完整 (Full) | enableLogs: true + Sentry.logger.* |
| 性能分析 (Profiling) | ❌ 不可用 (Not available) | @sentry/profiling-node 使用与 Bun 不兼容的原生插件 (uses native addons incompatible with Bun) |
| 指标 (Metrics) | ✅ 完整 (Full) | Sentry.metrics.* |
| 定时任务 (Crons) | ✅ 完整 (Full) | Sentry.withMonitor() |
| AI 监控 (AI Monitoring) | ✅ 完整 (Full) | OpenAI、Anthropic 集成有效 (OpenAI, Anthropic integrations work) |
运行时:Deno (Runtime: Deno)
Deno 没有向导可用 (No wizard available for Deno)。 仅限手动设置。
需要 Deno 2.0+。 不支持 Deno 1.x。
使用npm:说明符。deno.land/x/sentry仓库已弃用。
通过 deno.json 安装(推荐)(Install via deno.json – Recommended)
{
"imports": {
"@sentry/deno": "npm:@sentry/deno@10.42.0"
}
}
或直接使用 npm: 说明符导入 (Or import directly with the npm: specifier):
import * as Sentry from "npm:@sentry/deno";
初始化 — 添加到入口文件 (Initialize — Add to Entry File)
// 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___",
sendDefaultPii: true,
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 权限 (Required Deno Permissions)
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 Cron 集成 (Deno Cron Integration)
Deno 提供了原生的 cron 调度。使用 denoCronIntegration 进行自动监控:
import * as Sentry from "@sentry/deno";
import { denoCronIntegration } from "@sentry/deno";
Sentry.init({
dsn: Deno.env.get("SENTRY_DSN") ?? "___DSN___",
integrations: [denoCronIntegration()],
});
// Cron 会被自动监控 (Cron is automatically monitored)
Deno.cron("daily-cleanup", "0 0 * * *", () => {
// 清理逻辑 (cleanup logic)
});
Deno 功能支持 (Deno Feature Support)
| 功能 (Feature) | Deno 支持 (Deno Support) | 说明 (Notes) |
|---|---|---|
| 错误监控 (Error Monitoring) | ✅ 完整 (Full) | 未处理异常 + captureException |
| 追踪 (Tracing) | ✅ 自定义 OTel (Custom OTel) | 自动为 Deno.serve() 和 fetch 创建 span |
| 日志 (Logging) | ✅ 完整 (Full) | enableLogs: true + Sentry.logger.* |
| 性能分析 (Profiling) | ❌ 不可用 (Not available) | Deno 没有性能分析插件 (No profiling addon for Deno) |
| 指标 (Metrics) | ✅ 完整 (Full) | Sentry.metrics.* |
| 定时任务 (Crons) | ✅ 完整 (Full) | denoCronIntegration() + Sentry.withMonitor() |
| AI 监控 (AI Monitoring) | ✅ 部分 (Partial) | Vercel AI SDK 集成有效;OpenAI/Anthropic 通过 npm: 使用 |
对于每个已商定的功能 (For Each Agreed Feature)
加载相应的参考文件并按照其步骤操作:
| 功能 (Feature) | 参考文件 (Reference file) | 何时加载 (Load when…) |
|---|---|---|
| 错误监控 (Error Monitoring) | references/error-monitoring.md |
始终(基线)— 捕获、作用域、丰富、beforeSend (Always – baseline — captures, scopes, enrichment, beforeSend) |
| 追踪 (Tracing) | references/tracing.md |
OTel 自动埋点、自定义 span、分布式追踪、采样 |
| 日志 (Logging) | references/logging.md |
结构化日志、Sentry.logger.*、日志与追踪关联 |
| 性能分析 (Profiling) | references/profiling.md |
仅限 Node.js — CPU 分析,记录 Bun/Deno 的差距 (Node.js only — CPU profiling, Bun/Deno gaps documented) |
| 指标 (Metrics) | references/metrics.md |
自定义计数器、仪表、分布 (Custom counters, gauges, distributions) |
| 定时任务 (Crons) | references/crons.md |
定时任务监控、node-cron、Bull、Agenda、Deno.cron (Scheduled job monitoring, node-cron, Bull, Agenda, Deno.cron) |
| AI 监控 (AI Monitoring) | 加载 sentry-setup-ai-monitoring 技能 (Load sentry-setup-ai-monitoring skill) |
OpenAI、Anthropic、LangChain、Vercel AI、Google GenAI |
对于每个功能:阅读参考文件,严格按照其步骤操作,并在继续之前进行验证。
验证 (Verification)
设置后,验证 Sentry 是否正在接收事件:
// 临时添加到您的入口文件或测试路由,然后删除 (Add temporarily to your entry file or a test route, then remove)
import * as Sentry from "@sentry/node"; // 或 @sentry/bun / @sentry/deno
Sentry.captureException(new Error("Sentry 测试错误 — 请删除我 (Sentry test error — delete me)"));
或触发一个未处理的异常:
// 在路由处理器或启动时 — 将被自动捕获 (In a route handler or startup — will be captured automatically)
throw new Error("Sentry 测试错误 — 请删除我 (Sentry test error — delete me)");
然后检查您的 Sentry Issues 仪表板 (Sentry Issues dashboard) — 错误应在约 30 秒内出现。
验证清单 (Verification checklist):
| 检查项 (Check) | 如何检查 (How) |
|---|---|
| 错误已捕获 (Error captured) | 在处理程序中抛出异常,在 Sentry Issues 中验证 (Throw in a handler, verify in Sentry Issues) |
| 追踪正常工作 (Tracing working) | 检查性能选项卡 — 应显示 HTTP span (Check Performance tab — should show HTTP spans) |
includeLocalVariables 有效 |
Sentry 中的堆栈帧应显示变量值 (Stack frame in Sentry should show variable values) |
| Source maps 有效 (Source maps working) | 堆栈跟踪显示可读文件名,非压缩版本 (Stack trace shows readable file names, not minified) |
配置参考 (Config Reference)
Sentry.init() 核心选项 (Core Options)
| 选项 (Option) | 类型 (Type) | 默认 (Default) | 说明 (Notes) |
|---|---|---|---|
dsn |
string |
— | 必需。也可从 SENTRY_DSN 环境变量获取 (Required. Also from SENTRY_DSN env var) |
tracesSampleRate |
number |
— | 0–1;启用追踪需要 (0–1; required to enable tracing) |
sendDefaultPii |
boolean |
false |
包括 IP、请求头、用户信息 (Include IP, request headers, user info) |
includeLocalVariables |
boolean |
false |
将局部变量值添加到堆栈帧(Node.js)(Add local variable values to stack frames – Node.js) |
enableLogs |
boolean |
false |
启用 Sentry Logs 产品(v9.41.0+)(Enable Sentry Logs product – v9.41.0+) |
environment |
string |
"production" |
也可从 SENTRY_ENVIRONMENT 环境变量获取 (Also from SENTRY_ENVIRONMENT env var) |
release |
string |
— | 也可从 SENTRY_RELEASE 环境变量获取 (Also from SENTRY_RELEASE env var) |
debug |
boolean |
false |
将 SDK 活动记录到控制台 (Log SDK activity to console) |
enabled |
boolean |
true |
在测试中设置为 false 以禁用发送 (Set false in tests to disable sending) |
sampleRate |
number |
1.0 |
要发送的错误事件的比例 (0–1) (Fraction of error events to send – 0–1) |
shutdownTimeout |
number |
2000 |
进程退出前刷新事件的毫秒数 (Milliseconds to flush events before process exit) |
优雅关闭 (Graceful Shutdown)
在进程退出前刷新缓冲的事件 — 对短生命周期的脚本和无服务器很重要:
process.on("SIGTERM", async () => {
await Sentry.close(2000); // 刷新,超时 2 秒 (flush with 2s timeout)
process.exit(0);
});
环境变量 (Environment Variables)
| 变量 (Variable) | 用途 (Purpose) | 运行时 (Runtime) |
|---|---|---|
SENTRY_DSN |
DSN(替代在 init() 中硬编码)(DSN – alternative to hardcoding in init()) |
所有 (All) |
SENTRY_ENVIRONMENT |
部署环境 (Deployment environment) | 所有 (All) |
SENTRY_RELEASE |
版本字符串(从 git 自动检测)(Release version string – auto-detected from git) | 所有 (All) |
SENTRY_AUTH_TOKEN |
Source map 上传令牌 (Source map upload token) | 构建时 (Build time) |
SENTRY_ORG |
用于 source map 上传的组织简称 (Org slug for source map upload) | 构建时 (Build time) |
SENTRY_PROJECT |
用于 source map 上传的项目简称 (Project slug for source map upload) | 构建时 (Build time) |
NODE_OPTIONS |
为 ESM 设置 --import ./instrument.mjs (Set --import ./instrument.mjs for ESM) |
Node.js |
Source Maps (Node.js)
在生产环境中获得可读的堆栈跟踪需要上传 source map。使用 @sentry/cli 或 webpack/esbuild/rollup 插件:
npm install @sentry/cli --save-dev
# 在 sentry.io/settings/auth-tokens/ 创建一个 Sentry 认证令牌 (Create a Sentry auth token at sentry.io/settings/auth-tokens/)
# 在 .env.sentry-build-plugin 中设置(将此文件加入 gitignore)(Set in .env.sentry-build-plugin - gitignore this file):
SENTRY_AUTH_TOKEN=sntrys_eyJ...
将上传步骤添加到您的构建中:
{
"scripts": {
"build": "tsc && sentry-cli sourcemaps inject ./dist && sentry-cli sourcemaps upload ./dist"
}
}
阶段 4:交叉链接 (Phase 4: Cross-Link)
完成后端设置后,检查配套服务:
# 前端配套 (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)(Dedicated JavaScript framework skills – prefer these over generic node-sdk):
| 检测到 (Detected) | 优先使用技能 (Prefer skill) | 原因 (Why) |
|---|---|---|
NestJS(package.json 中有 @nestjs/core) |
sentry-nestjs-sdk |
使用 @sentry/nestjs 并集成了 NestJS 原生的装饰器、过滤器和 GraphQL 支持 (Uses @sentry/nestjs with NestJS-native decorators, filters, and GraphQL support) |
Next.js(package.json 中有 next) |
sentry-nextjs-sdk |
三运行时架构(浏览器、服务器、边缘)、withSentryConfig、source map 上传 (Three-runtime architecture – browser, server, edge, withSentryConfig, source map upload) |
前端配套 (Frontend companions):
| 检测到 (Detected) | 建议 (Suggest) |
|---|---|
React 应用(package.json 中有 react) |
sentry-react-sdk |
| Svelte/SvelteKit | sentry-svelte-sdk |
其他后端配套 (Other backend companions):
| 检测到 (Detected) | 建议 (Suggest) |
|---|---|
Go 后端(go.mod) |
sentry-go-sdk |
Python 后端(requirements.txt、pyproject.toml) |
sentry-python-sdk |
Ruby 后端(Gemfile) |
sentry-ruby-sdk |
使用相同的 DSN 或关联项目连接前端和后端,可以实现分布式追踪 (distributed tracing) — 在单个追踪视图中查看跨越您的浏览器、API 服务器和数据库的堆栈跟踪。
故障排除 (Troubleshooting)
| 问题 (Issue) | 原因 (Cause) | 解决方案 (Solution) |
|---|---|---|
| 事件未出现 (Events not appearing) | instrument.js 加载过晚 (loaded too late) |
确保它是第一个 require() / 通过 --import 或 --preload 加载 |
| 追踪 span 缺失 (Tracing spans missing) | 未设置 tracesSampleRate |
在 Sentry.init() 中添加 tracesSampleRate: 1.0 |
| ESM 埋点无效 (ESM instrumentation not working) | 缺少 --import 标志 (Missing --import flag) |
使用 node --import ./instrument.mjs 运行;在应用中 import "./instrument.mjs" 是不够的 |
@sentry/profiling-node 在 Bun 上安装失败 |
原生插件不兼容 (Native addon incompatible) | Bun 不支持性能分析 — 移除 @sentry/profiling-node |
| Deno: 事件未发送 (events not sent) | 缺少 --allow-net 权限 (Missing --allow-net permission) |
使用 --allow-net=o<ORG_ID>.ingest.sentry.io 运行 |
Deno: deno.land/x/sentry 无效 |
已弃用并冻结在 v8.55.0 (Deprecated and frozen at v8.55.0) | 切换到 npm:@sentry/deno 说明符 |
includeLocalVariables 不显示值 |
集成未激活或代码已压缩 (Integration not activated or minified code) | 确保在 init 中设置 includeLocalVariables: true;检查 source maps |
| NestJS: 错误未被捕获 | 使用了错误的 SDK 或缺少过滤器 (Wrong SDK or missing filter) | 使用 sentry-nestjs-sdk — NestJS 需要 @sentry/nestjs,而不是 @sentry/node |
Hapi: setupHapiErrorHandler 时序问题 |
未等待 (Not awaited) | 必须在 server.start() 之前 await Sentry.setupHapiErrorHandler(server) |
| 关闭:事件丢失 (Shutdown: events lost) | 进程在刷新前退出 (Process exits before flush) | 在 SIGTERM/SIGINT 处理程序中添加 await Sentry.close(2000) |
| 堆栈跟踪显示压缩后的代码 | 未上传 Source maps (Source maps not uploaded) | 在构建步骤中配置 @sentry/cli source map 上传 |
📄 原始文档
完整文档(英文):
https://skills.sh/getsentry/sentry-for-ai/sentry-node-sdk
💡 提示:点击上方链接查看 skills.sh 原始英文文档,方便对照翻译。

评论(0)