sentry-and-otel-setup
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseSentry and OpenTelemetry Setup
Sentry和OpenTelemetry设置
Overview
概述
Configure comprehensive error tracking and performance monitoring using Sentry with OpenTelemetry (OTel) instrumentation for Next.js applications, including automatic error capture, distributed tracing, and custom logging.
为Next.js应用配置基于Sentry与OpenTelemetry(OTel)工具的全面错误追踪和性能监控,包括自动错误捕获、分布式追踪和自定义日志功能。
Installation and Configuration
安装与配置
1. Install Sentry
1. 安装Sentry
Install Sentry Next.js SDK:
bash
npm install @sentry/nextjsRun Sentry wizard for automatic configuration:
bash
npx @sentry/wizard@latest -i nextjsThis creates:
- - Client-side configuration
sentry.client.config.ts - - Server-side configuration
sentry.server.config.ts - - Edge runtime configuration
sentry.edge.config.ts - - OpenTelemetry setup
instrumentation.ts - Updates with Sentry webpack plugin
next.config.js
安装Sentry Next.js SDK:
bash
npm install @sentry/nextjs运行Sentry向导进行自动配置:
bash
npx @sentry/wizard@latest -i nextjs此操作会生成:
- - 客户端配置文件
sentry.client.config.ts - - 服务端配置文件
sentry.server.config.ts - - Edge运行时配置文件
sentry.edge.config.ts - - OpenTelemetry设置文件
instrumentation.ts - 更新,添加Sentry webpack插件
next.config.js
2. Configure Environment Variables
2. 配置环境变量
Add Sentry credentials to :
.env.localenv
SENTRY_DSN=https://your-dsn@sentry.io/project-id
SENTRY_ORG=your-org
SENTRY_PROJECT=your-project
NEXT_PUBLIC_SENTRY_DSN=https://your-dsn@sentry.io/project-idGet DSN from Sentry dashboard: Settings > Projects > [Your Project] > Client Keys (DSN)
For production, add these to deployment environment variables.
在中添加Sentry凭证:
.env.localenv
SENTRY_DSN=https://your-dsn@sentry.io/project-id
SENTRY_ORG=your-org
SENTRY_PROJECT=your-project
NEXT_PUBLIC_SENTRY_DSN=https://your-dsn@sentry.io/project-id从Sentry控制台获取DSN:设置 > 项目 > [你的项目] > 客户端密钥(DSN)
生产环境中,请将这些变量添加到部署环境变量中。
3. Update Sentry Configurations
3. 更新Sentry配置
Customize using the template from :
sentry.server.config.tsassets/sentry-server-config.ts- Set environment (development, staging, production)
- Configure sample rates for performance monitoring
- Enable tracing for Server Actions and API routes
- Set up error filtering and breadcrumbs
Customize using the template from :
sentry.client.config.tsassets/sentry-client-config.ts- Configure replay sessions for debugging
- Set error boundaries
- Enable performance monitoring for user interactions
使用中的模板自定义:
assets/sentry-server-config.tssentry.server.config.ts- 设置环境(开发、预发布、生产)
- 配置性能监控的采样率
- 启用Server Actions和API路由的追踪
- 设置错误过滤和面包屑追踪
使用中的模板自定义:
assets/sentry-client-config.tssentry.client.config.ts- 配置用于调试的会话重放
- 设置错误边界
- 启用用户交互的性能监控
4. Add Instrumentation Hook
4. 添加工具初始化钩子
Create or update in project root using the template from . This:
instrumentation.tsassets/instrumentation.ts- Initializes OpenTelemetry before app starts
- Registers Sentry as trace provider
- Enables distributed tracing across services
- Runs only once on server startup
Note: Requires in (added by Sentry wizard).
experimental.instrumentationHooknext.config.js使用中的模板在项目根目录创建或更新。该文件会:
assets/instrumentation.tsinstrumentation.ts- 在应用启动前初始化OpenTelemetry
- 注册Sentry作为追踪提供者
- 启用跨服务的分布式追踪
- 仅在服务端启动时运行一次
注意:需要在中开启(Sentry向导会自动添加)。
next.config.jsexperimental.instrumentationHook5. Create Logging Wrapper
5. 创建日志包装器
Create using the template from . This provides:
lib/logger.tsassets/logger.ts- Structured logging with context
- Automatic Sentry integration
- Different log levels (debug, info, warn, error)
- Request context capture
Use instead of for better debugging:
console.logtypescript
import { logger } from '@/lib/logger';
logger.info('User logged in', { userId: user.id });
logger.error('Failed to save data', { error, userId });使用中的模板创建。该文件提供:
assets/logger.tslib/logger.ts- 带上下文的结构化日志
- 自动集成Sentry
- 不同日志级别(debug、info、warn、error)
- 请求上下文捕获
替代以获得更好的调试体验:
console.logtypescript
import { logger } from '@/lib/logger';
logger.info('用户已登录', { userId: user.id });
logger.error('数据保存失败', { error, userId });6. Add Error Boundary (Client Components)
6. 添加错误边界(客户端组件)
Create using the template from . This:
components/error-boundary.tsxassets/error-boundary.tsx- Catches React errors in client components
- Sends errors to Sentry
- Shows fallback UI
- Provides error recovery
Use in layouts or pages:
typescript
import { ErrorBoundary } from '@/components/error-boundary';
export default function Layout({ children }) {
return (
<ErrorBoundary>
{children}
</ErrorBoundary>
);
}使用中的模板创建。该组件会:
assets/error-boundary.tsxcomponents/error-boundary.tsx- 捕获客户端组件中的React错误
- 将错误发送至Sentry
- 显示降级UI
- 提供错误恢复功能
在布局或页面中使用:
typescript
import { ErrorBoundary } from '@/components/error-boundary';
export default function Layout({ children }) {
return (
<ErrorBoundary>
{children}
</ErrorBoundary>
);
}7. Create Custom Error Page
7. 创建自定义错误页面
Update using the template from . This:
app/error.tsxassets/error-page.tsx- Shows user-friendly error messages
- Captures errors in Server Components
- Provides retry functionality
- Sends errors to Sentry
使用中的模板更新。该页面会:
assets/error-page.tsxapp/error.tsx- 显示用户友好的错误信息
- 捕获服务端组件中的错误
- 提供重试功能
- 将错误发送至Sentry
8. Add Global Error Handler
8. 添加全局错误处理器
Update using the template from . This:
app/global-error.tsxassets/global-error.tsx- Catches errors in root layout
- Last resort error boundary
- Required for catching layout errors
使用中的模板更新。该处理器会:
assets/global-error.tsxapp/global-error.tsx- 捕获根布局中的错误
- 作为最后的错误边界
- 是捕获布局错误的必需配置
Tracing Server Actions
追踪Server Actions
Manual Instrumentation
手动工具集成
Wrap Server Actions with Sentry tracing:
typescript
'use server';
import { logger } from '@/lib/logger';
import * as Sentry from '@sentry/nextjs';
export async function createPost(formData: FormData) {
return await Sentry.startSpan(
{ name: 'createPost', op: 'server.action' },
async () => {
try {
const title = formData.get('title') as string;
logger.info('Creating post', { title });
// Your logic here
const post = await prisma.post.create({
data: { title, content: '...' },
});
logger.info('Post created', { postId: post.id });
return { success: true, post };
} catch (error) {
logger.error('Failed to create post', { error });
Sentry.captureException(error);
throw error;
}
}
);
}使用Sentry追踪包装Server Actions:
typescript
'use server';
import { logger } from '@/lib/logger';
import * as Sentry from '@sentry/nextjs';
export async function createPost(formData: FormData) {
return await Sentry.startSpan(
{ name: 'createPost', op: 'server.action' },
async () => {
try {
const title = formData.get('title') as string;
logger.info('正在创建文章', { title });
// 你的业务逻辑
const post = await prisma.post.create({
data: { title, content: '...' },
});
logger.info('文章创建完成', { postId: post.id });
return { success: true, post };
} catch (error) {
logger.error('文章创建失败', { error });
Sentry.captureException(error);
throw error;
}
}
);
}Automatic Instrumentation
自动工具集成
Sentry automatically instruments:
- Next.js API routes
- Server Components (partial)
- Fetch requests
- Database queries (with OTel)
Sentry会自动集成以下内容:
- Next.js API路由
- 服务端组件(部分支持)
- Fetch请求
- 数据库查询(需配合OTel)
Monitoring Patterns
监控模式
1. Capture User Context
1. 捕获用户上下文
Associate errors with users:
typescript
import * as Sentry from '@sentry/nextjs';
import { getCurrentUser } from '@/lib/auth/utils';
export async function setUserContext() {
const user = await getCurrentUser();
if (user) {
Sentry.setUser({
id: user.id,
email: user.email,
});
}
}Call in layouts or middleware to track user context globally.
将错误与用户关联:
typescript
import * as Sentry from '@sentry/nextjs';
import { getCurrentUser } from '@/lib/auth/utils';
export async function setUserContext() {
const user = await getCurrentUser();
if (user) {
Sentry.setUser({
id: user.id,
email: user.email,
});
}
}在布局或中间件中调用,以全局追踪用户上下文。
2. Add Custom Tags
2. 添加自定义标签
Tag errors for filtering:
typescript
Sentry.setTag('feature', 'worldbuilding');
Sentry.setTag('entity_type', 'character');
// Now errors are tagged and filterable in Sentry dashboard为错误添加标签以便过滤:
typescript
Sentry.setTag('feature', 'worldbuilding');
Sentry.setTag('entity_type', 'character');
// 现在可以在Sentry控制台中通过标签过滤错误3. Add Breadcrumbs
3. 添加面包屑
Track user actions leading to errors:
typescript
Sentry.addBreadcrumb({
category: 'user_action',
message: 'User clicked create entity',
level: 'info',
data: {
entityType: 'character',
worldId: 'world-123',
},
});追踪错误发生前的用户操作:
typescript
Sentry.addBreadcrumb({
category: 'user_action',
message: '用户点击创建实体',
level: 'info',
data: {
entityType: 'character',
worldId: 'world-123',
},
});4. Performance Monitoring
4. 性能监控
Track custom operations:
typescript
import * as Sentry from '@sentry/nextjs';
export async function complexOperation() {
const transaction = Sentry.startTransaction({
name: 'Complex World Generation',
op: 'task',
});
// Step 1
const span1 = transaction.startChild({
op: 'generate.terrain',
description: 'Generate terrain data',
});
await generateTerrain();
span1.finish();
// Step 2
const span2 = transaction.startChild({
op: 'generate.biomes',
description: 'Generate biome data',
});
await generateBiomes();
span2.finish();
transaction.finish();
}追踪自定义操作:
typescript
import * as Sentry from '@sentry/nextjs';
export async function complexOperation() {
const transaction = Sentry.startTransaction({
name: '复杂世界生成',
op: 'task',
});
// 步骤1
const span1 = transaction.startChild({
op: 'generate.terrain',
description: '生成地形数据',
});
await generateTerrain();
span1.finish();
// 步骤2
const span2 = transaction.startChild({
op: 'generate.biomes',
description: '生成生物群系数据',
});
await generateBiomes();
span2.finish();
transaction.finish();
}5. Database Query Tracing
5. 数据库查询追踪
Prisma automatically integrates with OTel:
typescript
// Queries are automatically traced if OTel is configured
const users = await prisma.user.findMany();
// Shows up in Sentry as a database spanPrisma会自动与OTel集成:
typescript
// 若已配置OTel,查询会被自动追踪
const users = await prisma.user.findMany();
// 会在Sentry中显示为数据库追踪 spanConfiguration Options
配置选项
Sample Rates
采样率
Control how many events are sent to Sentry (avoid quota limits):
typescript
// sentry.server.config.ts
Sentry.init({
dsn: process.env.SENTRY_DSN,
// Percentage of errors to capture (1.0 = 100%)
sampleRate: 1.0,
// Percentage of transactions to trace
tracesSampleRate: process.env.NODE_ENV === 'production' ? 0.1 : 1.0,
// Percentage of sessions to replay
replaysSessionSampleRate: 0.1,
// Percentage of error sessions to replay
replaysOnErrorSampleRate: 1.0,
});控制发送到Sentry的事件数量(避免配额超限):
typescript
// sentry.server.config.ts
Sentry.init({
dsn: process.env.SENTRY_DSN,
// 错误捕获比例(1.0 = 100%)
sampleRate: 1.0,
// 事务追踪比例
tracesSampleRate: process.env.NODE_ENV === 'production' ? 0.1 : 1.0,
// 会话重放比例
replaysSessionSampleRate: 0.1,
// 错误会话的重放比例
replaysOnErrorSampleRate: 1.0,
});Environment Detection
环境检测
Configure different settings per environment:
typescript
Sentry.init({
environment: process.env.NODE_ENV,
enabled: process.env.NODE_ENV !== 'development', // Disable in dev
beforeSend(event, hint) {
// Filter out specific errors
if (event.exception?.values?.[0]?.value?.includes('ResizeObserver')) {
return null; // Don't send to Sentry
}
return event;
},
});为不同环境配置不同设置:
typescript
Sentry.init({
environment: process.env.NODE_ENV,
enabled: process.env.NODE_ENV !== 'development', // 在开发环境禁用
beforeSend(event, hint) {
// 过滤特定错误
if (event.exception?.values?.[0]?.value?.includes('ResizeObserver')) {
return null; // 不发送到Sentry
}
return event;
},
});Source Maps
源映射
Ensure source maps are uploaded for readable stack traces:
typescript
// next.config.js (added by Sentry wizard)
const { withSentryConfig } = require('@sentry/nextjs');
module.exports = withSentryConfig(
nextConfig,
{
silent: true,
org: process.env.SENTRY_ORG,
project: process.env.SENTRY_PROJECT,
},
{
hideSourceMaps: true,
widenClientFileUpload: true,
}
);确保上传源映射以获得可读的堆栈跟踪:
typescript
// next.config.js(Sentry向导会自动添加)
const { withSentryConfig } = require('@sentry/nextjs');
module.exports = withSentryConfig(
nextConfig,
{
silent: true,
org: process.env.SENTRY_ORG,
project: process.env.SENTRY_PROJECT,
},
{
hideSourceMaps: true,
widenClientFileUpload: true,
}
);Best Practices
最佳实践
- Use logger wrapper: Centralize logging for consistency
- Set user context: Associate errors with users for debugging
- Add breadcrumbs: Track user journey before errors
- Monitor performance: Use tracing for slow operations
- Filter noise: Exclude known non-critical errors
- Configure sample rates: Balance visibility with quota
- Test in staging: Verify Sentry integration before production
- Review regularly: Check Sentry dashboard for patterns
- 使用日志包装器:集中日志管理以保证一致性
- 设置用户上下文:将错误与用户关联以方便调试
- 添加面包屑:追踪错误发生前的用户操作路径
- 监控性能:使用追踪功能定位慢操作
- 过滤无效信息:排除已知的非关键错误
- 配置采样率:在可见性和配额之间取得平衡
- 在预发布环境测试:上线前验证Sentry集成效果
- 定期复查:查看Sentry控制台以发现错误模式
Troubleshooting
故障排除
Sentry not capturing errors: Check DSN is correct and Sentry is initialized. Verify exports .
instrumentation.tsregister()Source maps not working: Ensure auth token is set and source maps are uploaded during build. Check Sentry dashboard > Settings > Source Maps.
High quota usage: Reduce sample rates in production. Filter out noisy errors with .
beforeSendTraces not appearing: Verify > 0. Check OpenTelemetry is initialized in .
tracesSampleRateinstrumentation.tsClient errors not captured: Ensure is set and accessible from browser.
NEXT_PUBLIC_SENTRY_DSNSentry未捕获错误:检查DSN是否正确,Sentry是否已初始化。验证是否导出。
instrumentation.tsregister()源映射不生效:确保已设置认证令牌,且构建过程中已上传源映射。查看Sentry控制台 > 设置 > 源映射。
配额使用过高:降低生产环境的采样率。使用过滤无效错误。
beforeSend追踪数据未显示:验证 > 0。检查中是否已初始化OpenTelemetry。
tracesSampleRateinstrumentation.ts客户端错误未捕获:确保已设置,且浏览器可访问该变量。
NEXT_PUBLIC_SENTRY_DSNResources
资源
scripts/
scripts/
No executable scripts needed for this skill.
本技能无需可执行脚本。
references/
references/
- - Error handling patterns, performance monitoring strategies, and quota management
sentry-best-practices.md - - OpenTelemetry concepts, custom instrumentation, and distributed tracing setup
otel-integration.md
- - 错误处理模式、性能监控策略和配额管理
sentry-best-practices.md - - OpenTelemetry概念、自定义工具集成和分布式追踪设置
otel-integration.md
assets/
assets/
- - Server-side Sentry configuration with tracing and sampling
sentry-server-config.ts - - Client-side Sentry configuration with replay and error boundaries
sentry-client-config.ts - - OpenTelemetry initialization and Sentry integration
instrumentation.ts - - Structured logging wrapper with Sentry integration
logger.ts - - React error boundary component for client-side error handling
error-boundary.tsx - - Custom error page for Server Component errors
error-page.tsx - - Global error handler for root layout errors
global-error.tsx
- - 带追踪和采样配置的服务端Sentry配置文件
sentry-server-config.ts - - 带会话重放和错误边界配置的客户端Sentry配置文件
sentry-client-config.ts - - OpenTelemetry初始化与Sentry集成文件
instrumentation.ts - - 集成Sentry的结构化日志包装器
logger.ts - - 用于客户端错误处理的React错误边界组件
error-boundary.tsx - - 服务端组件错误的自定义错误页面
error-page.tsx - - 根布局的全局错误处理器
global-error.tsx