关于 error-tracking
用于在各类服务中实施 Sentry 错误跟踪和性能监控规范的技能,面向为 API、工作流、定时任务和数据库操作添加监控的开发者。
主要功能
- 01附带上下文的错误捕获
- 02使用 Sentry 跟踪操作
- 03数据库性能跟踪模式
- 04定时任务监控指导
- 05严重级别与集成清单
适用场景
- 01为 API 错误添加 Sentry 处理
- 02跟踪数据库查询性能
- 03为定时任务和工作流添加监控
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ diet103/ claude-code-infrastructure-showcase --skill error-tracking安装后在 Claude Code 中输入/error-tracking确认已加载。
详细介绍
Sentry 集成技能
目的
此技能要求所有服务遵循 Sentry v8 模式,全面进行 Sentry 错误跟踪和性能监控。
何时使用此技能
- 为任何代码添加错误处理
- 创建新的控制器或路由
- 为 cron 作业添加检测
- 跟踪数据库性能
- 添加性能 span
- 处理工作流错误
🚨 关键规则
所有错误都必须上报到 Sentry——无一例外。绝不能只使用 console.error。
当前状态
示例:API 服务 ✅ 已完成
- 已全面集成 Sentry v8
- 已跟踪所有工作流错误
- 已为后台作业处理器添加检测
- 提供测试端点
Sentry 集成模式
1. 控制器错误处理
// ✅ CORRECT - Use BaseController
import { BaseController } from '../controllers/BaseController';
export class MyController extends BaseController {
async myMethod() {
try {
// ... your code
} catch (error) {
this.handleError(error, 'myMethod'); // Automatically sends to Sentry
}
}
}
2. 路由错误处理(不使用 BaseController)
import * as Sentry from '@sentry/node';
router.get('/route', async (req, res) => {
try {
// ... your code
} catch (error) {
Sentry.captureException(error, {
tags: { route: '/route', method: 'GET' },
extra: { userId: req.user?.id }
});
res.status(500).json({ error: 'Internal server error' });
}
});
3. 工作流错误处理
这是原始生产项目中的一个特定领域 Sentry 辅助函数示例。如果你为自己的领域构建类似的辅助函数,调用方式如下:
import { WorkflowSentryHelper } from '../workflow/utils/sentryHelper';
WorkflowSentryHelper.captureWorkflowError(error, {
workflowCode: 'INVOICE_APPROVAL',
instanceId: 123,
stepId: 456,
userId: 'user-123',
operation: 'stepCompletion',
metadata: { additionalInfo: 'value' }
});
不使用辅助函数时,普通 Sentry 也适用于所有场景:
Sentry.captureException(error, {
tags: { operation: 'stepCompletion' },
extra: { workflowCode: 'INVOICE_APPROVAL', instanceId: 123, userId: 'user-123' }
});
4. Cron 作业(必需模式)
#!/usr/bin/env node
// FIRST LINE after shebang - CRITICAL!
import '../instrument';
import * as Sentry from '@sentry/node';
async function main() {
return await Sentry.startSpan({
name: 'cron.job-name',
op: 'cron',
attributes: {
'cron.job': 'job-name',
'cron.startTime': new Date().toISOString(),
}
}, async () => {
try {
// Your cron job logic
} catch (error) {
Sentry.captureException(error, {
tags: {
'cron.job': 'job-name',
'error.type': 'execution_error'
}
});
console.error('[Job] Error:', error);
process.exit(1);
}
});
}
main()
.then(() => {
console.log('[Job] Completed successfully');
process.exit(0);
})
.catch((error) => {
console.error('[Job] Fatal error:', error);
process.exit(1);
});
5. 数据库性能监控
这是原始生产项目中的示例——一个用 Sentry span 包装 DB 调用的小型辅助函数。请根据你的代码库进行调整:
import { DatabasePerformanceMonitor } from '../utils/databasePerformance';
const result = await DatabasePerformanceMonitor.withPerformanceTracking(
'findMany',
'UserProfile',
async () => {
return await PrismaService.main.userProfile.findMany({
take: 5,
});
}
);
通用等效方式是直接使用 Sentry span:
const result = await Sentry.startSpan({
name: 'db.userProfile.findMany',
op: 'db.query',
attributes: { 'db.model': 'UserProfile', 'db.operation': 'findMany' }
}, async () => {
return await prisma.userProfile.findMany({ take: 5 });
});
6. 使用 span 的异步操作
import * as Sentry from '@sentry/node';
const result = await Sentry.startSpan({
name: 'operation.name',
op: 'operation.type',
attributes: {
'custom.attribute': 'value'
}
}, async () => {
// Your async operation
return await someAsyncOperation();
});
错误级别
使用适当的严重性级别:
- fatal:系统无法使用(数据库宕机、关键服务故障)
- error:操作失败,需要立即处理
- warning:可恢复的问题、性能下降
- info:信息性消息、成功的操作
- debug:详细的调试信息(仅限开发环境)
必需上下文
import * as Sentry from '@sentry/node';
Sentry.withScope((scope) => {
// ALWAYS include these if available
scope.setUser({ id: userId });
scope.setTag('service', 'api'); // your service name
scope.setTag('environment', process.env.NODE_ENV);
// Add operation-specific context
scope.setContext('operation', {
type: 'workflow.start',
workflowCode: 'INVOICE_APPROVAL',
entityId: 123
});
Sentry.captureException(error);
});
服务集成示例
API 服务(示例)
位置:./api/src/instrument.ts
import * as Sentry from '@sentry/node';
import { nodeProfilingIntegration } from '@sentry/profiling-node';
Sentry.init({
dsn: process.env.SENTRY_DSN,
environment: process.env.NODE_ENV || 'development',
integrations: [
nodeProfilingIntegration(),
],
tracesSampleRate: 0.1,
profilesSampleRate: 0.1,
});
主要辅助工具:
- 用于特定领域错误的自定义 Sentry 辅助函数
DatabasePerformanceMonitor- DB 查询跟踪BaseController- 控制器错误处理
Notifications 服务(示例)
位置:./notifications/src/instrument.ts
import * as Sentry from '@sentry/node';
import { nodeProfilingIntegration } from '@sentry/profiling-node';
Sentry.init({
dsn: process.env.SENTRY_DSN,
environment: process.env.NODE_ENV || 'development',
integrations: [
nodeProfilingIntegration(),
],
tracesSampleRate: 0.1,
profilesSampleRate: 0.1,
});
主要辅助工具:
- 用于领域错误的服务专用 Sentry 辅助函数
BaseController- 控制器错误处理
配置(config.ini)
[sentry]
dsn = your-sentry-dsn
environment = development
tracesSampleRate = 0.1
profilesSampleRate = 0.1
[databaseMonitoring]
enableDbTracing = true
slowQueryThreshold = 100
logDbQueries = false
dbErrorCapture = true
enableN1Detection = true
测试 Sentry 集成
测试端点示例
# Test basic error capture
curl http://localhost:3000/api/sentry/test-error
# Test performance tracking
curl http://localhost:3000/api/sentry/test-performance
# Test database performance
curl http://localhost:3000/api/sentry/test-database-performance
在服务中创建测试端点,以验证 Sentry 集成是否端到端正常工作。
性能监控
要求
- 所有 API 端点都必须进行事务跟踪
- 超过 100 ms 的数据库查询会自动标记
- N+1 查询会被检测并报告
- Cron 作业必须跟踪执行时间
事务跟踪
import * as Sentry from '@sentry/node';
// Automatic transaction tracking for Express routes
app.use(Sentry.Handlers.requestHandler());
app.use(Sentry.Handlers.tracingHandler());
// Manual transaction for custom operations
const transaction = Sentry.startTransaction({
op: 'operation.type',
name: 'Operation Name',
});
try {
// Your operation
} finally {
transaction.finish();
}
应避免的常见错误
❌ 绝不在不使用 Sentry 的情况下使用 console.error ❌ 绝不悄无声息地吞掉错误 ❌ 绝不在错误上下文中暴露敏感数据 ❌ 绝不使用缺少上下文的通用错误消息 ❌ 绝不跳过异步操作中的错误处理 ❌ 绝不忘记在 cron 作业中将 instrument.ts 作为第一行导入
实施检查清单
向新代码中添加 Sentry 时:
- 已导入 Sentry 或适当的辅助函数
- 所有 try/catch 块都会将错误上报到 Sentry
- 已为错误添加有意义的上下文
- 使用了适当的错误级别
- 错误消息中不包含敏感数据
- 已为耗时操作添加性能跟踪
- 已测试错误处理路径
- 对于 cron 作业:instrument.ts 已作为第一项导入
关键文件(典型结构)
每个服务
src/instrument.ts- Sentry 初始化(首先导入)src/utils/sentryHelper.ts- 特定领域错误辅助函数src/utils/databasePerformance.ts- DB 监控src/controllers/BaseController.ts- 集成 Sentry 的控制器基类
配置
config.ini或.env- Sentry DSN 和设置sentry.ini- 共享 Sentry 配置(可选)
评论
支持 Markdown