sentry-node-sdk
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAll Skills > SDK Setup > Node.js / Bun / Deno SDK
All Skills > SDK Setup > Node.js / Bun / Deno SDK
Sentry Node.js / Bun / Deno SDK
Sentry Node.js / Bun / Deno SDK
Opinionated wizard that scans your project and guides you through complete Sentry setup for server-side JavaScript and TypeScript runtimes: Node.js, Bun, and Deno.
本工具是开箱即用的配置引导,可扫描你的项目,指导你完成服务端JavaScript和TypeScript运行时(Node.js、Bun、Deno)的完整Sentry配置。
Invoke This Skill When
何时调用本技能
- User asks to "add Sentry to Node.js", "Bun", or "Deno"
- User wants to install or configure ,
@sentry/node, or@sentry/bun@sentry/deno - User wants error monitoring, tracing, logging, profiling, crons, metrics, or AI monitoring for a backend JS/TS app
- User asks about ,
instrument.js,--import ./instrument.mjs, orbun --preloadnpm:@sentry/deno - User wants to monitor Express, Fastify, Koa, Hapi, Connect, Bun.serve(), or Deno.serve()
NestJS? Useinstead — it usessentry-nestjs-sdkwith NestJS-native decorators and filters. Next.js? Use@sentry/nestjsinstead — it handles the three-runtime architecture (browser, server, edge).sentry-nextjs-sdk
Note: SDK versions below reflect current Sentry docs at time of writing (≥10.42.0,@sentry/node≥10.42.0,@sentry/bun≥10.42.0). Always verify against docs.sentry.io/platforms/javascript/guides/node/ before implementing.@sentry/deno
- 用户要求「给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,支持NestJS原生装饰器和过滤器。 使用Next.js? 请改用@sentry/nestjs——它适配了三运行时架构(浏览器、服务端、边缘端)。sentry-nextjs-sdk
注意: 本文档中的SDK版本对应编写时的官方Sentry文档要求(≥10.42.0、@sentry/node≥10.42.0、@sentry/bun≥10.42.0)。 配置前请始终对照docs.sentry.io/platforms/javascript/guides/node/确认最新要求。@sentry/deno
Phase 1: Detect
阶段1:环境检测
Run these commands to identify the runtime, framework, and existing Sentry setup:
bash
undefined运行以下命令识别运行时、框架和现有Sentry配置:
bash
undefinedDetect 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"
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
检测已安装的Sentry包
cat package.json 2>/dev/null | grep -E '"@sentry/'
cat deno.json deno.jsonc 2>/dev/null | grep -i sentry
cat package.json 2>/dev/null | grep -E '"@sentry/'
cat deno.json deno.jsonc 2>/dev/null | grep -i sentry
Detect Node.js framework
检测Node.js框架
cat package.json 2>/dev/null | grep -E '"express"|"fastify"|"@hapi/hapi"|"koa"|"@nestjs/core"|"connect"'
cat package.json 2>/dev/null | grep -E '"express"|"fastify"|"@hapi/hapi"|"koa"|"@nestjs/core"|"connect"'
Detect Bun-specific frameworks
检测Bun专属框架
cat package.json 2>/dev/null | grep -E '"elysia"|"hono"'
cat package.json 2>/dev/null | grep -E '"elysia"|"hono"'
Detect Deno frameworks (deno.json imports)
检测Deno框架(deno.json导入项)
cat deno.json deno.jsonc 2>/dev/null | grep -E '"oak"|"hono"|"fresh"'
cat deno.json deno.jsonc 2>/dev/null | grep -E '"oak"|"hono"|"fresh"'
Detect module system (Node.js)
检测Node.js模块系统
cat package.json 2>/dev/null | grep '"type"'
ls *.mjs *.cjs 2>/dev/null | head -5
cat package.json 2>/dev/null | grep '"type"'
ls *.mjs *.cjs 2>/dev/null | head -5
Detect existing instrument file
检测现有instrument配置文件
ls instrument.js instrument.mjs instrument.ts instrument.cjs 2>/dev/null
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"'
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"'
cat package.json 2>/dev/null | grep -E '"node-cron"|"cron"|"agenda"|"bull"|"bullmq"'
Detect AI / LLM usage
检测AI/LLM使用情况
cat package.json 2>/dev/null | grep -E '"openai"|"@anthropic-ai"|"@langchain"|"@vercel/ai"|"@google/generative-ai"'
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 |
|----------|--------|
| Which runtime? (Node.js / Bun / Deno) | Determines package, init pattern, and preload flag |
| Node.js: ESM or CJS? | ESM requires `--import ./instrument.mjs`; CJS uses `require("./instrument")` |
| Framework detected? | Determines which error handler to register |
| `@sentry/*` already installed? | Skip install, go straight to feature config |
| `instrument.js` / `instrument.mjs` already exists? | Merge into it rather than overwrite |
| Logging library detected? | Recommend Sentry Logs |
| Cron / job scheduler detected? | Recommend Crons monitoring |
| AI library detected? | Recommend AI Monitoring |
| Companion frontend found? | Trigger Phase 4 cross-link |
---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日志功能 |
| 是否检测到定时任务/调度工具? | 推荐开启Crons定时任务监控 |
| 是否检测到AI库? | 推荐开启AI监控 |
| 是否找到配套前端项目? | 触发阶段4的关联配置引导 |
---Phase 2: Recommend
阶段2:方案推荐
Present a concrete recommendation based on what you found. Don't ask open-ended questions — lead with a proposal:
Recommended (core coverage):
- ✅ Error Monitoring — always; captures unhandled exceptions, promise rejections, and framework errors
- ✅ Tracing — automatic HTTP, DB, and queue instrumentation via OpenTelemetry
Optional (enhanced observability):
- ⚡ Logging — structured logs via ; recommend when
Sentry.logger.*/winston/pinoor log search is neededbunyan - ⚡ Profiling — continuous CPU profiling (Node.js only; not available on Bun or Deno)
- ⚡ AI Monitoring — OpenAI, Anthropic, LangChain, Vercel AI SDK; recommend when AI/LLM calls detected
- ⚡ Crons — detect missed or failed scheduled jobs; recommend when node-cron, Bull, or Agenda is detected
- ⚡ Metrics — custom counters, gauges, distributions; recommend when custom KPIs needed
Recommendation logic:
| Feature | Recommend when... |
|---|---|
| Error Monitoring | Always — non-negotiable baseline |
| Tracing | Always for server apps — HTTP spans + DB spans are high-value |
| Logging | App uses winston, pino, bunyan, or needs log-to-trace correlation |
| Profiling | Node.js only — performance-critical service; native addon compatible |
| AI Monitoring | App calls OpenAI, Anthropic, LangChain, Vercel AI, or Google GenAI |
| Crons | App uses node-cron, Bull, BullMQ, Agenda, or any scheduled task pattern |
| Metrics | App needs custom counters, gauges, or histograms |
Propose: "I recommend setting up Error Monitoring + Tracing. Want me to also add Logging or Profiling?"
根据检测结果给出具体的配置建议,不要提出开放式问题,直接给出方案:
推荐核心功能(基础覆盖):
- ✅ 错误监控 — 必选,可捕获未处理异常、Promise拒绝和框架错误
- ✅ 链路追踪 — 基于OpenTelemetry自动埋点HTTP、数据库和队列操作
可选增强功能(提升可观测性):
- ⚡ 日志功能 — 通过输出结构化日志;检测到
Sentry.logger.*/winston/pino或有日志检索需求时推荐开启bunyan - ⚡ 性能分析 — 持续CPU性能分析(仅支持Node.js,Bun和Deno暂不支持)
- ⚡ AI监控 — 支持OpenAI、Anthropic、LangChain、Vercel AI SDK;检测到AI/LLM调用时推荐开启
- ⚡ 定时任务监控 — 检测漏执行或失败的定时任务;检测到node-cron、Bull或Agenda时推荐开启
- ⚡ 指标统计 — 自定义计数器、计量器、分布统计;有自定义KPI统计需求时推荐开启
推荐逻辑:
| 功能 | 推荐开启时机 |
|---|---|
| 错误监控 | 始终开启 — 基础必选功能 |
| 链路追踪 | 服务端应用始终开启 — HTTP和数据库埋点价值极高 |
| 日志功能 | 应用使用winston、pino、bunyan,或者需要日志与链路关联能力 |
| 性能分析 | 仅Node.js — 性能敏感的服务,且兼容原生扩展 |
| AI监控 | 应用调用OpenAI、Anthropic、LangChain、Vercel AI或Google GenAI |
| 定时任务监控 | 应用使用node-cron、Bull、BullMQ、Agenda或任何定时任务模式 |
| 指标统计 | 应用需要自定义计数器、计量器或直方图统计 |
建议话术:「我推荐配置错误监控+链路追踪。需要我同时添加日志或性能分析功能吗?」
Phase 3: Guide
阶段3:配置引导
Runtime: Node.js
运行时:Node.js
Option 1: Wizard (Recommended for Node.js)
选项1:引导工具(Node.js推荐方案)
You need to run this yourself — the wizard opens a browser for login and requires interactive input that the agent can't handle. Copy-paste into your terminal:npx @sentry/wizard@latest -i nodeIt handles login, org/project selection, SDK installation,creation, and package.json script updates.instrument.jsOnce it finishes, come back and skip to Verification.
If the user skips the wizard, proceed with Option 2 (Manual Setup) below.
需要你手动执行 — 引导工具会打开浏览器完成登录,需要交互输入,Agent无法自动处理。复制到终端运行即可:npx @sentry/wizard@latest -i node它会自动处理登录、组织/项目选择、SDK安装、创建和package.json脚本更新。instrument.js执行完成后返回此处,直接跳转到验证环节。
如果用户跳过引导工具,继续使用下方选项2手动配置。
Option 2: Manual Setup — Node.js
选项2:手动配置 — Node.js
Install
安装依赖
bash
npm install @sentry/node --savebash
npm install @sentry/node --saveor
或
yarn add @sentry/node
yarn add @sentry/node
or
或
pnpm add @sentry/node
undefinedpnpm add @sentry/node
undefinedCreate the Instrument File
创建Instrument配置文件
CommonJS ():
instrument.jsjavascript
// 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% 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.mjsjavascript
// instrument.mjs — 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,
});CommonJS规范():
instrument.jsjavascript
// instrument.js — 必须在所有其他模块之前加载
const Sentry = require("@sentry/node");
Sentry.init({
dsn: process.env.SENTRY_DSN ?? "___DSN___",
sendDefaultPii: true,
// 开发环境100%采样,生产环境降低采样率
tracesSampleRate: process.env.NODE_ENV === "development" ? 1.0 : 0.1,
// 捕获栈帧中的本地变量值
includeLocalVariables: true,
enableLogs: true,
});ESM规范():
instrument.mjsjavascript
// instrument.mjs — 通过--import参数在所有其他模块之前加载
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,
});Start Your App with Sentry Loaded First
启动应用时优先加载Sentry
CommonJS — add as the very first line of your entry file:
require("./instrument")javascript
// app.js
require("./instrument"); // must be first
const express = require("express");
// ... rest of your appESM — use the flag so Sentry loads before all other modules (Node.js 18.19.0+ required):
--importbash
node --import ./instrument.mjs app.mjsAdd to scripts:
package.jsonjson
{
"scripts": {
"start": "node --import ./instrument.mjs server.mjs",
"dev": "node --import ./instrument.mjs --watch server.mjs"
}
}Or via environment variable (useful for wrapping existing start commands):
bash
NODE_OPTIONS="--import ./instrument.mjs" npm startCommonJS — 在入口文件的最顶部添加:
require("./instrument")javascript
// app.js
require("./instrument"); // 必须是第一行
const express = require("express");
// ... 应用其他代码ESM — 使用参数确保Sentry在所有其他模块之前加载(需要Node.js 18.19.0+版本):
--importbash
node --import ./instrument.mjs app.mjs添加到脚本:
package.jsonjson
{
"scripts": {
"start": "node --import ./instrument.mjs server.mjs",
"dev": "node --import ./instrument.mjs --watch server.mjs"
}
}或通过环境变量设置(适合包装现有启动命令):
bash
NODE_OPTIONS="--import ./instrument.mjs" npm startFramework Error Handlers
框架错误处理器注册
Register the Sentry error handler after all routes so it can capture framework errors:
Express:
javascript
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:
javascript
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:
javascript
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 (async — must await):
javascript
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:
javascript
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 — has its own dedicated skill with full coverage:
Use theskill instead. NestJS uses a separate package (sentry-nestjs-sdk) with NestJS-native constructs:@sentry/nestjs,SentryModule.forRoot(),SentryGlobalFilter,@SentryTraceddecorators, and GraphQL/Microservices support. Load that skill for complete NestJS setup.@SentryCron
Vanilla Node.js module — wrap request handler manually:
httpjavascript
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 | | After all routes | No |
| Fastify | | Before routes | No |
| Koa | | First middleware | No |
| Hapi | | Before | Yes |
| Connect | | Before routes | No |
| NestJS | → Use | Dedicated skill | — |
在所有路由之后注册Sentry错误处理器,才能捕获框架抛出的错误:
Express:
javascript
const express = require("express");
const Sentry = require("@sentry/node");
const app = express();
// ... 你的路由
// 添加在所有路由之后 — 默认捕获5xx错误
Sentry.setupExpressErrorHandler(app);
// 可选:同时捕获4xx错误
// Sentry.setupExpressErrorHandler(app, {
// shouldHandleError(error) { return error.status >= 400; },
// });
app.listen(3000);Fastify:
javascript
const Fastify = require("fastify");
const Sentry = require("@sentry/node");
const fastify = Fastify();
// 添加在路由之前(和Express相反!)
Sentry.setupFastifyErrorHandler(fastify);
// ... 你的路由
await fastify.listen({ port: 3000 });Koa:
javascript
const Koa = require("koa");
const Sentry = require("@sentry/node");
const app = new Koa();
// 添加为第一个中间件(捕获后续中间件抛出的错误)
Sentry.setupKoaErrorHandler(app);
// ... 其他中间件和路由
app.listen(3000);Hapi(异步,必须await):
javascript
const Hapi = require("@hapi/hapi");
const Sentry = require("@sentry/node");
const server = Hapi.server({ port: 3000 });
// ... 你的路由
// 必须await — Hapi注册是异步操作
await Sentry.setupHapiErrorHandler(server);
await server.start();Connect:
javascript
const connect = require("connect");
const Sentry = require("@sentry/node");
const app = connect();
// 添加在路由之前(和Fastify、Koa一致)
Sentry.setupConnectErrorHandler(app);
// ... 中间件和路由
require("http").createServer(app).listen(3000);NestJS — 有专属的完整配置技能:
请改用技能。 NestJS需要使用单独的包sentry-nestjs-sdk,支持原生NestJS能力:@sentry/nestjs、SentryModule.forRoot()、SentryGlobalFilter、@SentryTraced装饰器,以及GraphQL/微服务支持。调用对应技能获取完整NestJS配置方案。@SentryCron
原生Node.js 模块 — 手动包装请求处理器:
httpjavascript
const http = require("http");
const Sentry = require("@sentry/node");
const server = http.createServer((req, res) => {
Sentry.withIsolationScope(() => {
try {
// 你的处理器逻辑
res.end("OK");
} catch (err) {
Sentry.captureException(err);
res.writeHead(500);
res.end("Internal Server Error");
}
});
});
server.listen(3000);框架错误处理器汇总:
| 框架 | 方法 | 放置位置 | 是否异步? |
|---|---|---|---|
| Express | | 所有路由之后 | 否 |
| Fastify | | 路由之前 | 否 |
| Koa | | 第一个中间件 | 否 |
| Hapi | | | 是 |
| Connect | | 路由之前 | 否 |
| NestJS | → 参考 | 专属技能 | — |
Runtime: Bun
运行时:Bun
No wizard available for Bun. Manual setup only.
Bun暂不支持引导工具,仅支持手动配置。
Install
安装依赖
bash
bun add @sentry/bunbash
bun add @sentry/bunCreate instrument.ts
(or instrument.js
)
instrument.tsinstrument.js创建instrument.ts
(或instrument.js
)
instrument.tsinstrument.jstypescript
// 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,
});typescript
// 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,
});Start Your App with --preload
--preload使用--preload
参数启动应用
--preloadbash
bun --preload ./instrument.ts server.tsAdd to :
package.jsonjson
{
"scripts": {
"start": "bun --preload ./instrument.ts server.ts",
"dev": "bun --watch --preload ./instrument.ts server.ts"
}
}bash
bun --preload ./instrument.ts server.ts添加到:
package.jsonjson
{
"scripts": {
"start": "bun --preload ./instrument.ts server.ts",
"dev": "bun --watch --preload ./instrument.ts server.ts"
}
}Bun.serve() — Auto-Instrumentation
Bun.serve() — 自动埋点
@sentry/bunBun.serve()--preloadBun.serve()typescript
// server.ts
const server = Bun.serve({
port: 3000,
fetch(req) {
return new Response("Hello from Bun!");
},
});@sentry/bunBun.serve()--preloadBun.serve()typescript
// server.ts
const server = Bun.serve({
port: 3000,
fetch(req) {
return new Response("Hello from Bun!");
},
});Framework Error Handlers on Bun
Bun平台的框架错误处理器
Bun can run Express, Fastify, Hono, and Elysia. Use the same import and the error handler functions (re-exported by ):
@sentry/bun@sentry/node@sentry/buntypescript
import * as Sentry from "@sentry/bun";
import express from "express";
const app = express();
// ... routes
Sentry.setupExpressErrorHandler(app);
app.listen(3000);Bun可以运行Express、Fastify、Hono和Elysia,使用相同的导入,错误处理器方法和一致(已经重新导出了这些方法):
@sentry/bun@sentry/node@sentry/buntypescript
import * as Sentry from "@sentry/bun";
import express from "express";
const app = express();
// ... 路由
Sentry.setupExpressErrorHandler(app);
app.listen(3000);Bun Feature Support
Bun功能支持情况
| Feature | Bun Support | Notes |
|---|---|---|
| Error Monitoring | ✅ Full | Same API as Node |
| Tracing | ✅ Via | Most auto-instrumentations work |
| Logging | ✅ Full | |
| Profiling | ❌ Not available | |
| Metrics | ✅ Full | |
| Crons | ✅ Full | |
| AI Monitoring | ✅ Full | OpenAI, Anthropic integrations work |
| 功能 | Bun支持情况 | 说明 |
|---|---|---|
| 错误监控 | ✅ 完整支持 | 和Node.js API一致 |
| 链路追踪 | ✅ 通过 | 大部分自动埋点都可正常工作 |
| 日志功能 | ✅ 完整支持 | 开启 |
| 性能分析 | ❌ 暂不支持 | |
| 指标统计 | ✅ 完整支持 | 使用 |
| 定时任务监控 | ✅ 完整支持 | 使用 |
| AI监控 | ✅ 完整支持 | OpenAI、Anthropic集成可正常工作 |
Runtime: Deno
运行时:Deno
No wizard available for Deno. Manual setup only. Requires Deno 2.0+. Deno 1.x is not supported. Usespecifier. Thenpm:registry is deprecated.deno.land/x/sentry
Deno暂不支持引导工具,仅支持手动配置。 需要Deno 2.0+版本,Deno 1.x不支持。 请使用导入规范,npm:registry已经废弃。deno.land/x/sentry
Install via deno.json
(Recommended)
deno.json通过deno.json
安装(推荐)
deno.jsonjson
{
"imports": {
"@sentry/deno": "npm:@sentry/deno@10.42.0"
}
}Or import directly with the specifier:
npm:typescript
import * as Sentry from "npm:@sentry/deno";json
{
"imports": {
"@sentry/deno": "npm:@sentry/deno@10.42.0"
}
}或直接使用规范导入:
npm:typescript
import * as Sentry from "npm:@sentry/deno";Initialize — Add to Entry File
初始化 — 添加到入口文件
typescript
// 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!");
});Unlike Node.js and Bun, Deno does not have aor--preloadflag. Sentry must be the first--importin your entry file.import
typescript
// main.ts — 必须在所有其他代码之前调用Sentry.init()
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,
});
// 应用代码放在后面
Deno.serve({ port: 8000 }, (req) => {
return new Response("Hello from Deno!");
});和Node.js、Bun不同,Deno没有或--preload参数,Sentry必须是入口文件中的第一个--import。import
Required Deno Permissions
必要的Deno权限
The SDK requires network access to reach your Sentry ingest domain:
bash
deno run \
--allow-net=o<ORG_ID>.ingest.sentry.io \
--allow-read=./src \
--allow-env=SENTRY_DSN,SENTRY_RELEASE \
main.tsFor development, works but is not recommended for production.
--allow-allSDK需要网络权限访问Sentry数据上报域名:
bash
deno run \
--allow-net=o<ORG_ID>.ingest.sentry.io \
--allow-read=./src \
--allow-env=SENTRY_DSN,SENTRY_RELEASE \
main.ts开发环境可以使用,但生产环境不推荐。
--allow-allDeno Cron Integration
Deno Cron集成
Deno provides native cron scheduling. Use for automatic monitoring:
denoCronIntegrationtypescript
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提供原生定时任务调度能力,使用即可实现自动监控:
denoCronIntegrationtypescript
import * as Sentry from "@sentry/deno";
import { denoCronIntegration } from "@sentry/deno";
Sentry.init({
dsn: Deno.env.get("SENTRY_DSN") ?? "___DSN___",
integrations: [denoCronIntegration()],
});
// 定时任务会被自动监控
Deno.cron("daily-cleanup", "0 0 * * *", () => {
// 清理逻辑
});Deno Feature Support
Deno功能支持情况
| Feature | Deno Support | Notes |
|---|---|---|
| Error Monitoring | ✅ Full | Unhandled exceptions + |
| Tracing | ✅ Custom OTel | Automatic spans for |
| Logging | ✅ Full | |
| Profiling | ❌ Not available | No profiling addon for Deno |
| Metrics | ✅ Full | |
| Crons | ✅ Full | |
| AI Monitoring | ✅ Partial | Vercel AI SDK integration works; OpenAI/Anthropic via |
| 功能 | Deno支持情况 | 说明 |
|---|---|---|
| 错误监控 | ✅ 完整支持 | 未处理异常 + |
| 链路追踪 | ✅ 自定义OTel实现 | 自动为 |
| 日志功能 | ✅ 完整支持 | 开启 |
| 性能分析 | ❌ 暂不支持 | Deno暂无可支持的性能分析扩展 |
| 指标统计 | ✅ 完整支持 | 使用 |
| 定时任务监控 | ✅ 完整支持 | |
| AI监控 | ✅ 部分支持 | Vercel AI SDK集成可正常工作;OpenAI/Anthropic通过 |
For Each Agreed Feature
每个确认开启的功能配置
Load the corresponding reference file and follow its steps:
| Feature | Reference file | Load when... |
|---|---|---|
| Error Monitoring | | Always (baseline) — captures, scopes, enrichment, beforeSend |
| Tracing | | OTel auto-instrumentation, custom spans, distributed tracing, sampling |
| Logging | | Structured logs, |
| Profiling | | Node.js only — CPU profiling, Bun/Deno gaps documented |
| Metrics | | Custom counters, gauges, distributions |
| Crons | | Scheduled job monitoring, node-cron, Bull, Agenda, Deno.cron |
| AI Monitoring | Load | OpenAI, Anthropic, LangChain, Vercel AI, Google GenAI |
For each feature: read the reference file, follow its steps exactly, and verify before moving on.
加载对应的参考文件并严格按照步骤操作:
| 功能 | 参考文件 | 加载时机 |
|---|---|---|
| 错误监控 | | 始终(基础功能) — 事件捕获、作用域、信息丰富、beforeSend钩子 |
| 链路追踪 | | OTel自动埋点、自定义span、分布式追踪、采样规则 |
| 日志功能 | | 结构化日志、 |
| 性能分析 | | 仅Node.js — CPU性能分析,注明Bun/Deno暂不支持 |
| 指标统计 | | 自定义计数器、计量器、分布统计 |
| 定时任务监控 | | 定时任务监控、node-cron、Bull、Agenda、Deno.cron |
| AI监控 | 加载 | OpenAI、Anthropic、LangChain、Vercel AI、Google GenAI |
每个功能配置完成后,先验证通过再进入下一个功能的配置。
Verification
验证
After setup, verify Sentry is receiving events:
javascript
// 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"));Or trigger an unhandled exception:
javascript
// In a route handler or startup — will be captured automatically
throw new Error("Sentry test error — delete me");Then check your Sentry Issues dashboard — the error should appear within ~30 seconds.
Verification checklist:
| Check | How |
|---|---|
| Error captured | Throw in a handler, verify in Sentry Issues |
| Tracing working | Check Performance tab — should show HTTP spans |
| Stack frame in Sentry should show variable values |
| Source maps working | Stack trace shows readable file names, not minified |
配置完成后,验证Sentry是否正常接收事件:
javascript
// 临时添加到入口文件或测试路由,验证后删除
import * as Sentry from "@sentry/node"; // 或 @sentry/bun / @sentry/deno
Sentry.captureException(new Error("Sentry测试错误 — 请删除我"));或触发一个未处理异常:
javascript
// 在路由处理器或启动代码中添加,会被自动捕获
throw new Error("Sentry测试错误 — 请删除我");然后检查你的Sentry Issues面板 — 错误应该会在30秒内出现。
验证检查清单:
| 检查项 | 验证方式 |
|---|---|
| 错误正常捕获 | 在处理器中抛出错误,在Sentry Issues中确认收到 |
| 链路追踪正常工作 | 检查Performance面板,应该能看到HTTP span |
| Sentry中的栈帧应该显示变量值 |
| 源码映射正常工作 | 栈追踪显示可读的文件名,不是压缩后的文件名 |
Config Reference
配置参考
Sentry.init()
Core Options
Sentry.init()Sentry.init()
核心参数
Sentry.init()| Option | Type | Default | Notes |
|---|---|---|---|
| | — | Required. Also from |
| | — | 0–1; required to enable tracing |
| | | Include IP, request headers, user info |
| | | Add local variable values to stack frames (Node.js) |
| | | Enable Sentry Logs product (v9.41.0+) |
| | | Also from |
| | — | Also from |
| | | Log SDK activity to console |
| | | Set |
| | | Fraction of error events to send (0–1) |
| | | Milliseconds to flush events before process exit |
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| | — | 必填,也可通过 |
| | — | 0–1之间的数值,开启链路追踪必填 |
| | | 是否包含IP、请求头、用户信息 |
| | | 栈帧中添加本地变量值(仅Node.js) |
| | | 开启Sentry日志功能(v9.41.0+版本支持) |
| | | 部署环境,也可通过 |
| | — | 发布版本号,也可通过 |
| | | 将SDK活动日志输出到控制台 |
| | | 测试环境可设为 |
| | | 错误事件采样率(0–1) |
| | | 进程退出前刷新事件的超时时间(毫秒) |
Graceful Shutdown
优雅关闭
Flush buffered events before process exit — important for short-lived scripts and serverless:
javascript
process.on("SIGTERM", async () => {
await Sentry.close(2000); // flush with 2s timeout
process.exit(0);
});进程退出前刷新缓存的事件 — 对短生命周期脚本和Serverless场景非常重要:
javascript
process.on("SIGTERM", async () => {
await Sentry.close(2000); // 2秒超时刷新
process.exit(0);
});Environment Variables
环境变量
| Variable | Purpose | Runtime |
|---|---|---|
| DSN (alternative to hardcoding in | All |
| Deployment environment | All |
| Release version string (auto-detected from git) | All |
| Source map upload token | Build time |
| Org slug for source map upload | Build time |
| Project slug for source map upload | Build time |
| Set | Node.js |
| 变量 | 用途 | 适用运行时 |
|---|---|---|
| DSN配置(替代在 | 所有 |
| 部署环境 | 所有 |
| 发布版本字符串(支持从git自动识别) | 所有 |
| 源码映射上传令牌 | 构建阶段 |
| 组织slug,用于源码映射上传 | 构建阶段 |
| 项目slug,用于源码映射上传 | 构建阶段 |
| 为ESM设置 | Node.js |
Source Maps (Node.js)
源码映射(Node.js)
Readable stack traces in production require source map upload. Use or the webpack/esbuild/rollup plugins:
@sentry/clibash
npm install @sentry/cli --save-devbash
undefined生产环境下要获得可读的栈追踪需要上传源码映射,使用或webpack/esbuild/rollup插件:
@sentry/clibash
npm install @sentry/cli --save-devbash
undefinedCreate a Sentry auth token at sentry.io/settings/auth-tokens/
在sentry.io/settings/auth-tokens/创建Sentry auth令牌
Set in .env.sentry-build-plugin (gitignore this file):
在.env.sentry-build-plugin中配置(将该文件加入.gitignore):
SENTRY_AUTH_TOKEN=sntrys_eyJ...
Add upload step to your build:
```json
{
"scripts": {
"build": "tsc && sentry-cli sourcemaps inject ./dist && sentry-cli sourcemaps upload ./dist"
}
}SENTRY_AUTH_TOKEN=sntrys_eyJ...
在构建流程中添加上传步骤:
```json
{
"scripts": {
"build": "tsc && sentry-cli sourcemaps inject ./dist && sentry-cli sourcemaps upload ./dist"
}
}Phase 4: Cross-Link
阶段4:关联配置引导
After completing backend setup, check for companion services:
bash
undefined后端配置完成后,检查是否有配套服务:
bash
undefinedFrontend companion
配套前端项目
ls frontend/ web/ client/ ui/ 2>/dev/null
cat package.json 2>/dev/null | grep -E '"react"|"vue"|"svelte"|"next"'
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
If a frontend, framework-specific SDK, or other backend is found, suggest the matching skill:
**Dedicated JavaScript framework skills (prefer these over generic node-sdk):**
| Detected | Prefer skill | Why |
|----------|-------------|-----|
| NestJS (`@nestjs/core` in `package.json`) | [`sentry-nestjs-sdk`](../sentry-nestjs-sdk/SKILL.md) | Uses `@sentry/nestjs` with NestJS-native decorators, filters, and GraphQL support |
| Next.js (`next` in `package.json`) | [`sentry-nextjs-sdk`](../sentry-nextjs-sdk/SKILL.md) | Three-runtime architecture (browser, server, edge), `withSentryConfig`, source map upload |
**Frontend companions:**
| Detected | Suggest |
|---------|---------|
| React app (`react` in `package.json`) | [`sentry-react-sdk`](../sentry-react-sdk/SKILL.md) |
| Svelte/SvelteKit | [`sentry-svelte-sdk`](../sentry-svelte-sdk/SKILL.md) |
**Other backend companions:**
| Detected | Suggest |
|---------|---------|
| Go backend (`go.mod`) | [`sentry-go-sdk`](../sentry-go-sdk/SKILL.md) |
| Python backend (`requirements.txt`, `pyproject.toml`) | [`sentry-python-sdk`](../sentry-python-sdk/SKILL.md) |
| Ruby backend (`Gemfile`) | [`sentry-ruby-sdk`](../sentry-ruby-sdk/SKILL.md) |
Connecting frontend and backend with the same DSN or linked projects enables **distributed tracing** — stack traces that span your browser, API server, and database in a single trace view.
---ls ../go.mod ../requirements.txt ../Gemfile 2>/dev/null
如果检测到前端、专属框架SDK或其他后端服务,推荐对应的配置技能:
**专属JavaScript框架技能(优先于通用node-sdk使用):**
| 检测到 | 优先使用的技能 | 原因 |
|----------|-------------|-----|
| NestJS(`package.json`中有`@nestjs/core`) | [`sentry-nestjs-sdk`](../sentry-nestjs-sdk/SKILL.md) | 使用`@sentry/nestjs`,支持NestJS原生装饰器、过滤器和GraphQL |
| Next.js(`package.json`中有`next`) | [`sentry-nextjs-sdk`](../sentry-nextjs-sdk/SKILL.md) | 适配三运行时架构(浏览器、服务端、边缘端),支持`withSentryConfig`和源码映射上传 |
**配套前端项目推荐:**
| 检测到 | 推荐技能 |
|---------|---------|
| React应用(`package.json`中有`react`) | [`sentry-react-sdk`](../sentry-react-sdk/SKILL.md) |
| Svelte/SvelteKit | [`sentry-svelte-sdk`](../sentry-svelte-sdk/SKILL.md) |
**其他配套后端服务推荐:**
| 检测到 | 推荐技能 |
|---------|---------|
| Go后端(有`go.mod`) | [`sentry-go-sdk`](../sentry-go-sdk/SKILL.md) |
| Python后端(有`requirements.txt`、`pyproject.toml`) | [`sentry-python-sdk`](../sentry-python-sdk/SKILL.md) |
| Ruby后端(有`Gemfile`) | [`sentry-ruby-sdk`](../sentry-ruby-sdk/SKILL.md) |
前端和后端使用相同DSN或关联项目可以开启**分布式追踪** — 栈追踪可以覆盖浏览器、API服务和数据库,在同一个追踪视图中展示。
---Troubleshooting
问题排查
| Issue | Cause | Solution |
|---|---|---|
| Events not appearing | | Ensure it's the first |
| Tracing spans missing | | Add |
| ESM instrumentation not working | Missing | Run with |
| Native addon incompatible | Profiling is not supported on Bun — remove |
| Deno: events not sent | Missing | Run with |
Deno: | Deprecated and frozen at v8.55.0 | Switch to |
| Integration not activated or minified code | Ensure |
| NestJS: errors not captured | Wrong SDK or missing filter | Use |
Hapi: | Not awaited | Must |
| Shutdown: events lost | Process exits before flush | Add |
| Stack traces show minified code | Source maps not uploaded | Configure |
| 问题 | 原因 | 解决方案 |
|---|---|---|
| 事件没有上报 | | 确保它是第一个 |
| 链路追踪span缺失 | 没有设置 | 在 |
| ESM instrumentation不生效 | 缺少 | 使用 |
Bun环境下 | 原生扩展不兼容 | Bun暂不支持性能分析,移除 |
| Deno环境下事件没有发送 | 缺少 | 使用 |
Deno环境下 | 该包已废弃,冻结在v8.55.0版本 | 切换到 |
| 集成未激活或代码被压缩 | 确保 |
| NestJS错误没有被捕获 | 使用了错误的SDK或缺少过滤器 | 使用 |
Hapi的 | 没有await | 在 |
| 关闭进程时事件丢失 | 进程在刷新完成前退出 | 在SIGTERM/SIGINT处理器中添加 |
| 栈追踪显示压缩后的代码 | 没有上传源码映射 | 在构建步骤中配置 |