# Sentry 错误监控快速接入指南(免费版) > **适用场景**: Novalon Website 项目 > **Sentry 版本**: 免费版 (5,000 errors/month) > **预计耗时**: 15-30 分钟 ## 📋 前置条件 - ✅ Sentry 账号 (如果没有,见下方注册步骤) - ✅ 项目已安装 `@sentry/nextjs` 依赖 - ✅ 已创建 `sentry.*.config.ts` 配置文件 ## 🚀 步骤 1:注册 Sentry 免费账号(如果还没有) ### 1.1 访问 Sentry 官网 打开浏览器访问: **https://sentry.io/signup** ### 1.2 注册账号 **推荐方式(最快)**: - 点击 "Sign up with GitHub" 或 "Sign up with Google" - 使用你的 Gitea/GitHub 账号直接登录 **或者使用邮箱注册**: 1. 输入工作邮箱(建议用 `dev-team@novalon.cn`) 2. 设置密码 3. 验证邮箱(检查收件箱,点击验证链接) ### 1.3 创建组织(Organization) 注册成功后: 1. 进入 Dashboard 2. 点击 "Create Organization" 3. 组织名称填写: `Novalon` 或 `Novalon-Tech` 4. 选择团队类型: **Developer Team**(免费) 5. 点击 "Create Organization" ### 1.4 创建项目(Project) 在组织内创建新项目: 1. 点击 "Create Project" 2. 搜索并选择框架: **Next.js** 3. 项目名称填写: `novalon-website` 4. 团队选择: 默认团队即可 5. 点击 "Create Project" ### 1.5 获取 DSN(Data Source Name) 项目创建完成后: 1. 进入项目 → **Settings** → **Client Keys (DSN)** 2. 复制 **DSN** 值,格式如下: ``` https://examplePublicKey@o0.ingest.sentry.io/123456 ``` 3. **保存这个 DSN 值**,下一步会用到! --- ## ⚙️ 步骤 2:配置环境变量 ### 2.1 编辑 `.env.local` 文件 在项目根目录下创建或编辑 `.env.local`: ```bash # 复制示例配置 cp .env.example .env.local ``` 编辑 `.env.local`: ```bash # Google Analytics (如果有真实值,请替换) NEXT_PUBLIC_GA_MEASUREMENT_ID=G-XXXXXXXXXX # Sentry DSN (替换为你在步骤 1.5 中获取的真实 DSN) NEXT_PUBLIC_SENTRY_DSN=https://your-real-dsn@o0.ingest.sentry.io/your-project-id SENTRY_DSN=https://your-real-dsn@o0.ingest.sentry.io/your-project-id # CDN 配置(可选) CDN_DOMAIN= ``` **⚠️ 重要提醒:** - ❌ 不要将 `.env.local` 提交到 Git!它已经在 `.gitignore` 中 - ✅ 只在本地开发环境和生产服务器上配置此文件 - 🔒 DSN 是公开的,不包含敏感信息(可以安全地用在客户端) --- ## 📦 步骤 3:安装 Sentry SDK ```bash # 安装 @sentry/nextjs 及其依赖 npm install @sentry/nextjs @sentry/tracing # 或者使用 pnpm(如果你用 pnpm) pnpm add @sentry/nextjs @sentry/tracing ``` --- ## 🔄 步骤 4:修改 next.config.ts 以集成 Sentry 当前你的 [next.config.ts](./next.config.ts) 需要添加 Sentry wrapper: ```typescript import type { NextConfig } from "next"; import { withSentryConfig } from "@sentry/nextjs"; const cdnDomain = process.env.CDN_DOMAIN || ''; const nextConfig: NextConfig = { distDir: 'dist', output: 'export', assetPrefix: cdnDomain || undefined, images: { unoptimized: true, }, compress: true, poweredByHeader: false, reactStrictMode: true, experimental: { optimizePackageImports: ['lucide-react'], }, compiler: { removeConsole: process.env.NODE_ENV === 'production', }, }; export default withSentryConfig( nextConfig, { silent: true, disableLogger: true, hideSourceMaps: true, // 自动上传 source maps 到 Sentry(推荐生产环境开启) disableClientWebpackPlugin: process.env.NODE_ENV !== 'production', disableServerWebpackPlugin: process.env.NODE_ENV !== 'production', }, ); ``` **注意**:我已经为你创建了修改后的版本,可以直接替换原文件。 --- ## ✅ 步骤 5:验证 Sentry 是否正常工作 ### 5.1 启动开发服务器 ```bash npm run dev ``` ### 5.2 触发测试错误 浏览器访问以下地址之一: ```bash # 方法 A:访问 Sentry 内置的错误页面 http://localhost:3000/sentry-example-error # 方法 B:在浏览器控制台手动触发(更灵活) # 打开 http://localhost:3000,然后在控制台执行: throw new TestError('Sentry 测试错误 - 如果你能看到这条错误,说明 Sentry 工作正常!'); ``` ### 5.3 在 Sentry Dashboard 验证 1. 登录 https://sentry.io 2. 进入你的组织 → `novalon-website` 项目 3. 点击左侧菜单 **Issues** 4. 应该能看到刚刚触发的测试错误! **预期结果**: ``` ✅ Issues 列表中显示: - Error Type: Error (或 TestError) - Message: "Sentry 测试错误..." - First Seen: 几秒钟前 - Events: 1 ``` --- ## 🎯 步骤 6:配置告警规则(可选但强烈推荐) ### 6.1 创建错误数量告警 1. 在 Sentry Dashboard 中,点击 **Alerts** → **Create Alert** 2. 选择 alert 类型: **"When an issue is created"** 或 **"Number of errors is high"** 3. 配置阈值: ``` Alert Type: Number of Errors Threshold: > 10 errors in 5 minutes Environment: production ``` 4. 配置通知方式: - **Email**: 发送到 dev-team@novalon.cn - **Slack/DingTalk**: 如果集成了的话 5. 保存告警规则 ### 6.2 创建性能退化告警(进阶) 如果你想监控 Core Web Vitals: 1. 进入 **Settings** → **Performance** 2. 开启 **Web Vitals** 监控 3. 设置阈值: - LCP (Largest Contentful Paint): > 2.5 秒 - FID (First Input Delay): > 100 ms - CLS (Cumulative Layout Shift): > 0.1 --- ## 🛠️ 步骤 7:在生产环境中启用 Sentry 当你准备部署到生产环境时: ### 7.1 在生产服务器上配置环境变量 SSH 到你的生产服务器 (139.155.109.62): ```bash ssh root@139.155.109.62 # 编辑 Docker 环境变量或 .env 文件 nano /home/novalon/docker-app/.env.production ``` 添加以下内容: ```bash NODE_ENV=production NEXT_PUBLIC_GA_MEASUREMENT_ID=你的真实GA_ID NEXT_PUBLIC_SENTRY_DSN=你的真实SENTRY_DSN SENTRY_DSN=你的真实SENTRY_DSN ``` ### 7.2 重新构建和部署 ```bash # 回到本地开发机 ./deploy-dist.sh ``` Jenkins Pipeline 会自动: 1. 运行测试 2. 构建生产版本 3. 部署到服务器 4. Sentry 开始收集生产环境的错误数据 --- ## 📊 步骤 8:查看和分析错误报告 ### 8.1 Issues 页面(问题列表) 进入 **Issues** 标签页,你可以看到: | 列 | 说明 | 示例 | |---|------|------| | **Issue Title** | 错误标题 | TypeError: Cannot read property 'x' of undefined | | **First Seen** | 首次发生时间 | 2 hours ago | | **Events** | 发生次数 | 23 users, 45 events | | **Users Affected** | 影响用户数 | 23 users | | **Level** | 严重程度 | error / warning / info | ### 8.2 Performance 页面(性能监控) 如果你的应用开启了性能监控: - **Transaction**(事务):每个页面加载的详细耗时 - **Span**(时间跨度):具体操作的时间分解 - **Web Vitals**:LCP、FID、CLS 的趋势图 ### 8.3 Releases 页面(版本追踪) 每次部署后,Sentry 会自动关联到 Git commit: ``` Release: v1.0.0-stable Commit: abc1234 (feat: downgrade to stable stack) Deploy Time: 2026-05-12 14:30:00 Errors: 0 (or X if any) ``` --- ## 💡 高级用法(按需启用) ### #1:标记用户身份(提升错误排查效率) 在你的业务代码中(如用户登录后): ```typescript import * as Sentry from '@sentry/nextjs'; // 当用户登录后 Sentry.setUser({ id: user.id, email: user.email, segment: 'premium', // or 'free' }); ``` **收益**:当某个用户报错时,你可以直接看到是哪个用户遇到的问题。 ### #2:附加自定义上下文(业务相关信息) ```typescript // 在关键操作中添加上下文 Sentry.setContext('order', { orderId: 'ORD-20260512-001', amount: 999, product: 'Enterprise License', }); // 如果这里出错,Sentry 会自动附带这些信息 ``` ### #3:手动捕获特定错误 ```typescript try { const response = await fetch('/api/contact'); if (!response.ok) { throw new Error(`Contact form submission failed: ${response.status}`); } } catch (error) { // 手动发送到 Sentry,并附加额外信息 Sentry.captureException(error, { tags: { feature: 'contact-form' }, extra: { formData: { name, email, subject } }, }); } ``` ### #4:设置面包屑导航(Breadcrumbs)—— 记录用户操作路径 Sentry 会自动记录: - UI 交互(click、input、keypress) - 导航变化(URL 变化) - Console 日志 - HTTP 请求(XHR/Fetch) - DOM 变化 你还可以手动添加: ```typescript Sentry.addBreadcrumb({ category: 'ui', message: 'User clicked "Submit" on contact form', level: 'info', }); ``` --- ## 🔧 故障排除 ### 问题 1:Sentry Dashboard 看不到任何错误 **可能原因及解决方案**: | 原因 | 解决方案 | |------|---------| | DSN 未正确配置 | 检查 `.env.local` 中的 `NEXT_PUBLIC_SENTRY_DSN` 是否有值 | | 环境变量未生效 | 重启开发服务器 (`npm run dev`) | | `enabled: false` 在开发环境 | 检查 `sentry.client.config.ts` 中的 `enabled` 条件 | | 网络问题 | 检查是否能访问 `o0.ingest.sentry.io` | **调试方法**: ```typescript // 在 sentry.client.config.ts 中临时添加 console.log('[Sentry] DSN:', SENTRY_DSN); console.log('[Sentry] Enabled:', process.env.NODE_ENV !== 'development'); ``` ### 问题 2:Source Maps 未上传 **现象**:Sentry 显示的错误堆栈是压缩后的代码,难以阅读。 **解决方案**: 1. 安装 `@sentry/webpack-plugin`: ```bash npm install --save-dev @sentry/webpack-plugin ``` 2. 在 `next.config.ts` 中配置: ```typescript export default withSentryConfig( nextConfig, { silent: true, hideSourceMaps: false, // 改为 false // 其他配置... }, { include: './dist/**', ignore: ['node_modules'], urlPrefix: '~/_next', } ); ``` ### 问题 3:免费额度超限 **Sentry 免费版限制**: - 每月 5,000 个错误事件 - 保留 30 天的数据 - 5 个团队成员 **如果超限**: 1. 升级到 Developer 版本 ($26/月,50,000 errors/month) 2. 或者优化错误过滤(减少噪音) 3. 或者在 `ignoreErrors` 中添加更多模式 --- ## 📚 相关文档链接 - **Sentry 官方文档**: https://docs.sentry.io/platforms/javascript/guides/nextjs/ - **Next.js 集成指南**: https://docs.sentry.io/platforms/javascript/guides/nextjs/ - **最佳实践**: https://docs.sentry.io/product/best-practices/event-grouping/ --- ## ✅ 接入完成清单 请逐项确认: - [ ] 已注册 Sentry 账号并创建项目 - [ ] 已获取 DSN 并配置到 `.env.local` - [ ] 已安装 `@sentry/nextjs` 和 `@sentry/tracing` - [ ] 已修改 `next.config.ts` 添加 `withSentryConfig` - [ ] 已运行 `npm run dev` 并访问 `/sentry-example-error` - [ ] 已在 Sentry Dashboard 看到测试错误 - [ ] (可选)已配置告警规则 - [ ] (可选)已部署到生产环境并验证 全部完成后,你的 Novalon Website 就拥有了**企业级的错误监控能力**!🎉