使用 Sentry 进行监控
为您的 Supabase 边缘函数添加 Sentry Deno SDK,以追踪异常并获取错误或性能问题的通知。
先决条件
- 创建 Sentry 账户
- 确保已安装最新版本的 Supabase CLI
1. 创建 Supabase 函数
在本地创建新函数:
1supabase functions new sentryfied
2. 添加 Sentry Deno SDK
在函数中处理异常并将其发送至 Sentry:
123456789101112131415161718192021222324252627282930313233import * as Sentry from 'https://deno.land/x/sentry/index.mjs'Sentry.init({ // https://docs.sentry.io/product/sentry-basics/concepts/dsn-explainer/#where-to-find-your-dsn dsn: SENTRY_DSN, defaultIntegrations: false, // 性能监控 tracesSampleRate: 1.0, // 设置性能分析采样率 - 相对于 tracesSampleRate profilesSampleRate: 1.0,})// 将 region 和 execution_id 设为自定义标签Sentry.setTag('region', Deno.env.get('SB_REGION'))Sentry.setTag('execution_id', Deno.env.get('SB_EXECUTION_ID'))Deno.serve(async (req) => { try { const { name } = await req.json() // 此处会抛出异常,因为在我们的示例调用中 `name` 是 `undefined` const data = { message: `你好 ${name}!`, } return new Response(JSON.stringify(data), { headers: { 'Content-Type': 'application/json' } }) } catch (e) { Sentry.captureException(e) return new Response(JSON.stringify({ msg: 'error' }), { status: 500, headers: { 'Content-Type': 'application/json' }, }) }})
3. 部署与测试
本地运行函数:
12supabase startsupabase functions serve --no-verify-jwt
测试地址:http://localhost:54321/functions/v1/sentryfied
将函数部署至 Supabase:
1supabase functions deploy sentryfied --no-verify-jwt
4. 亲自尝试
完整示例可在 GitHub 上找到。
作用域处理
Sentry Deno SDK 目前不支持 Deno.serve
插装,这意味着请求之间没有作用域隔离。
因此,当边缘函数运行时在多个请求之间复用时,所有全局捕获的面包屑和上下文数据
将被共享,这不是期望的行为。为了解决这个问题,上述示例代码中禁用了所有默认集成,
您应该依赖 withScope
来封装
所有 Sentry SDK API 调用,或者直接传递上下文
给 captureException
或 captureMessage
调用。