Show / Hide Table of Contents ]

next 支持 sentry

Last updated: 2024-11-18 22:06:48

什么是 sentry

sentry 是一个开源的错误监控平台,可以监控和分析应用程序的错误。

使用

1. 安装依赖

1
pnpm add @sentry/nextjs

or

1
yarn add @sentry/nextjs

2. 初始化 Sentry

1
npx sentry-cli init

生成:

  • sentry.client.config.js
  • sentry.server.config.js
  • next.config.js (如果不存在的话)

3. 配置 Sentry

在项目根目录下修改 sentry.client.config.jssentry.server.config.js

1
2
3
4
5
6
7
8
9
import as Sentry from "@sentry/nextjs";

Sentry.init({
dsn: "你的-sentry-dsn", // 从 Sentry 控制台获取
tracesSampleRate: 1.0,
// 开发环境建议关闭
enabled: process.env.NODE_ENV === 'production',
});

4. 使用示例

1
2
3
4
5
6
7
8
import { ErrorBoundary } from "@sentry/nextjs";
export default function App() {
return (
<ErrorBoundary fallback={<p>出错了!</p>}>
<YourApp />
</ErrorBoundary>
);
}

5. 性能监控

1
2
3
4
5
Sentry.init({
dsn: "你的-sentry-dsn",
tracesSampleRate: 1.0,
integrations: [new Sentry.BrowserTracing()],
});

注意事项

  1. 确保在生产环境中正确配置 DSN
  2. 建议在开发环境中禁用 Sentry
  3. 合理配置采样率(tracesSampleRate)以控制成本

重拾纯粹的写作