停止为 Slack 警报付费:免费将 Sentry 错误发送到 Slack
Source: Dev.to
厌倦了为 Sentry 的 Slack 集成付费吗?好消息是,你根本不需要付费。
只需使用 Sentry webhook、Vercel Edge Functions 和 Slack 免费的 chat.postMessage API 进行简单设置,就能在 Slack 中实时收到错误通知——无需高级套餐。
为什么要为你可以自己构建的东西付费?
Sentry 内置的 Slack 集成需要付费。对于独立开发者和小型项目来说,这笔费用往往不划算。
相反,你可以:
- 使用 Sentry 的 webhook 集成
- 使用 Vercel Edge Function 捕获事件
- 使用 Slack 免费 API 发送格式化消息
同样的结果。零额外费用。
第一步:设置 Sentry Webhook
- 打开你的 Sentry 项目设置。
- 前往 Legacy Integrations → Webhooks。
- 添加一个新的 webhook(部署后你将在此粘贴你的 Vercel 函数 URL)。
Sentry 现在会将错误事件发送到你的自定义端点。
步骤 2:创建 Vercel Edge 函数
如果你是 Vercel 的新手,它是一个无服务器平台,能够在边缘运行代码,并提供慷慨的免费额度。
我们将创建一个 Edge 函数,实现以下功能:
- 接收 Sentry 事件
- 使用 Slack Block Kit 对其进行格式化
- 通过 API 将消息发送到 Slack
export const config = {
runtime: 'edge',
};
const sendMessage = async (
channel,
{ level, formatted, environment, email, title, culprit, project }
) => {
const isError = level === "error";
const blocks = [
{
type: "section",
text: {
type: "mrkdwn",
text: `${isError ? ":red_circle:" : ""} *${title}*`,
},
},
{
type: "section",
fields: [
{ type: "mrkdwn", text: `*Environment:*\n${environment}` },
{ type: "mrkdwn", text: `*Level:*\n${level}` },
{ type: "mrkdwn", text: `*Project:*\n${project}` },
],
},
{
type: "section",
fields: [{ type: "mrkdwn", text: `*User:*\n${email}` }],
},
{ type: "divider" },
{
type: "section",
text: { type: "mrkdwn", text: `*Message:*\n${formatted}` },
},
{
type: "section",
text: { type: "mrkdwn", text: `*Culprit:*\n${culprit}` },
},
{ type: "divider" },
];
await fetch("https://slack.com/api/chat.postMessage", {
method: "POST",
headers: {
"Content-Type": "application/json; charset=utf-8",
Authorization: `Bearer ${process.env.SLACK_ACCESS_TOKEN}`,
},
body: JSON.stringify({ channel, blocks }),
});
};
export default async (req) => {
const body = await req.json();
const {
project,
culprit,
event: {
level,
logentry: { formatted },
user: { email },
environment,
metadata: { title },
},
} = body;
await sendMessage(process.env.CHANNEL_ID, {
level,
formatted,
environment,
email,
title,
culprit,
project,
});
return new Response("Event received");
};
这段代码的作用
- 接收来自 Sentry 的错误事件。
- 使用 Block Kit 将其格式化为结构化的 Slack 消息。
- 使用 OAuth 令牌直接向 Slack 发送消息。
第三步:创建并配置你的 Slack 应用
- 前往 .
- 在你的工作区创建一个新应用。
- 在 OAuth & Permissions 中,添加作用域
chat:write。 - 将应用安装到你的工作区并复制 OAuth Bot Token。
在 Vercel 中添加以下环境变量:
SLACK_ACCESS_TOKEN– 刚才复制的机器人令牌。CHANNEL_ID– 应接收警报的 Slack 频道的 ID。
Step 4: Deploy to Vercel
- 将代码推送到 GitHub。
- 将仓库导入 Vercel。
- 添加环境变量(
SLACK_ACCESS_TOKEN、CHANNEL_ID)。 - 部署。
部署完成后,复制 Edge Function URL 并将其粘贴到 Sentry webhook 设置中。
第5步:测试
在 Sentry 中触发一个测试错误。如果一切配置正确,干净且结构化的错误通知将在几秒钟内出现在 Slack 中。
为什么这种设置会赢
- 完全免费。
- 实时通知。
- 完全可自定义的 Slack 格式。
- 无服务器且低维护。
- 在 Sentry 的免费计划上可用。
获取代码并自定义
随意将此设置适配到您的工作流中:
- 添加严重性过滤。
- 将不同项目路由到不同频道。
- 为预发布和生产环境更改格式。
如果这帮助您节省了成本或改进了监控,请考虑给仓库加星并与其他开发者分享。
祝构建愉快 🚀