如何使用 Sentry 或 Datadog 进行错误监控?
解读
该问题考察候选人对 Next.js 应用错误监控体系的理解,以及对 Sentry 和 Datadog 这两类主流监控工具的集成能力。在企业级项目中,错误监控是保障系统稳定性的重要环节,需结合 Next.js 的特性(如 SSR、SSG、API 路由)实现全链路错误捕获与分析。
知识点
- Next.js 错误处理机制
- 全局错误边界(
_error.js) - API 路由中的错误捕获
- 自定义错误日志记录
- 全局错误边界(
- Sentry 集成要点
- 客户端错误捕获(React 组件、异步代码)
- 服务端错误捕获(API 路由、Node.js 服务)
- 项目配置与 SDK 初始化
- Datadog 集成要点
- 日志收集与分析
- 性能监控(如请求延迟、错误率)
- 自定义指标与事件追踪
- 国内开发环境适配
- 网络代理配置(如使用
https-proxy-agent) - 数据隐私合规(GDPR/《个人信息保护法》)
- 网络代理配置(如使用
答案
Sentry 集成
- 安装 SDK
在package.json中添加依赖:npm install @sentry/react @sentry/node - 初始化配置
在next.config.js中配置 Sentry:
在客户端页面中使用module.exports = { sentry: { org: 'your-org', project: 'your-project', authToken: 'your-auth-token', }, };@sentry/react:import * as Sentry from '@sentry/react'; import { Integrations } from '@sentry/tracing'; Sentry.init({ dsn: 'https://examplePublicKey@o0.ingest.sentry.io/123456', integrations: [new Integrations.BrowserTracing()], tracesSampleRate: 1.0, }); // 捕获全局错误 window.addEventListener('error', Sentry.captureException); window.addEventListener('unhandledrejection', Sentry.captureException); - 服务端错误捕获
在 API 路由中添加错误处理逻辑:export default async function handler(req, res) { try { // 业务逻辑 } catch (error) { Sentry.captureException(error); res.status(500).json({ error: 'Internal Server Error' }); } } - 国内适配
若需通过代理访问 Sentry 服务,可在next.config.js中配置:module.exports = { webpack(config, { isServer }) { if (!isServer) { config.resolve.fallback = { ...config.resolve.fallback, 'https-proxy-agent': require.resolve('https-proxy-agent'), }; } return config; }, };
Datadog 集成
- 安装 SDK
安装 Datadog 的 Node.js 和浏览器 SDK:npm install datadog-browser-sdk datadog-node - 初始化配置
在next.config.js中配置 Datadog:
在客户端页面中初始化浏览器 SDK:module.exports = { datadog: { apiKey: 'your-api-key', service: 'nextjs-app', env: 'production', }, };import { init, info } from 'datadog-browser-sdk'; import { datadogRum } from '@datadog/browser-rum'; init({ applicationId: 'your-app-id', clientToken: 'your-client-token', env: 'production', service: 'nextjs-app', }); // 捕获错误 datadogRum.startSessionReplayRecording(); datadogRum.addAction('page-load', { page: 'home' }); - 服务端日志与性能监控
在 API 路由中记录日志并发送到 Datadog:import { logger } from 'datadog-node'; export default async function handler(req, res) { try { // 业务逻辑 } catch (error) { logger.error('API Error', { error: error.message, url: req.url }); res.status(500).json({ error: 'Internal Server Error' }); } } - 国内适配
若需满足数据合规要求,可配置日志脱敏规则:logger.setGlobalContext({ user: { id: 'user123', email: 'user@example.com', }, });
拓展思考
- 多环境配置
需区分开发、测试、生产环境的监控级别,例如在开发环境关闭错误上报,生产环境启用全量采集。if (process.env.NODE_ENV === 'production') { Sentry.init({ ... }); } - 错误分类与优先级
通过Sentry.setTag或DatadogRum.addAction标记错误类型(如前端 UI 错误、后端 API 错误),便于后续分析。Sentry.setTag('source', 'frontend'); - 性能监控指标
在 Datadog 中可设置关键性能指标(KPI),如页面加载时间(performance.timing)或 API 响应延迟(request.duration)。datadogRum.addRumGlobalContext('performance', { loadTime: performance.timing.loadEventEnd - performance.timing.navigationStart, }); - 错误监控与告警联动
配合监控平台的告警规则(如错误率超过 1% 触发通知),需在配置中定义阈值:// 示例:Sentry 错误率告警 Sentry.configureScope(scope => { scope.setTag('error_rate', '1%'); }); - 数据安全与合规
在国内部署时需确保敏感信息(如用户数据、API 密钥)不被明文传输,可通过 SDK 的excludeKeys参数过滤日志内容。logger.excludeKeys(['password', 'token']);