[ PROMPT_NODE_23766 ]
Sentry 集成与监控
[ SKILL_DOCUMENTATION ]
# Sentry 集成与监控
使用 Sentry v8 进行错误追踪和性能监控的完整指南。
## 目录
- [核心原则](#core-principles)
- [Sentry 初始化](#sentry-initialization)
- [错误捕获模式](#error-capture-patterns)
- [性能监控](#performance-monitoring)
- [定时任务监控](#cron-job-monitoring)
- [错误上下文最佳实践](#error-context-best-practices)
- [常见错误](#common-mistakes)
---
## 核心原则
**强制要求**:所有错误必须捕获到 Sentry。没有例外。
**所有错误必须被捕获** - 在所有服务中使用 Sentry v8 进行全面的错误追踪。
---
## Sentry 初始化
### instrument.ts 模式
**位置:** `src/instrument.ts`(必须是 server.ts 和所有定时任务中的第一个导入)
**微服务模板:**
typescript
import * as Sentry from '@sentry/node';
import * as fs from 'fs';
import * as path from 'path';
import * as ini from 'ini';
const sentryConfigPath = path.join(__dirname, '../sentry.ini');
const sentryConfig = ini.parse(fs.readFileSync(sentryConfigPath, 'utf-8'));
Sentry.init({
dsn: sentryConfig.sentry?.dsn,
environment: process.env.NODE_ENV || 'development',
tracesSampleRate: parseFloat(sentryConfig.sentry?.tracesSampleRate || '0.1'),
profilesSampleRate: parseFloat(sentryConfig.sentry?.profilesSampleRate || '0.1'),
integrations: [
...Sentry.getDefaultIntegrations({}),
Sentry.extraErrorDataIntegration({ depth: 5 }),
Sentry.localVariablesIntegration(),
Sentry.requestDataIntegration({
include: {
cookies: false,
data: true,
headers: true,
ip: true,
query_string: true,
url: true,
user: { id: true, email: true, username: true },
},
}),
Sentry.consoleIntegration(),
Sentry.contextLinesIntegration(),
Sentry.prismaIntegration(),
],
beforeSend(event, hint) {
// 过滤健康检查
if (event.request?.url?.includes('/healthcheck')) {
return null;
}
// 清除敏感头部信息
if (event.request?.headers) {
delete event.request.headers['authorization'];
delete event.request.headers['cookie'];
}
// 为 PII 屏蔽电子邮件
if (event.user?.email) {
event.user.email = event.user.email.r