Laravel中如何通过before_send等配置过滤Sentry上报事件
Laravel Sentry 客户端侧限流与重复事件过滤方案
方案1:基于before_send回调实现精确频次控制
你可以直接借助Laravel自带的缓存系统存储上报计数,在before_send回调中完成单事件上报次数校验、全局日上报上限校验,符合规则的事件才会被上报。
配置示例如下:
// config/sentry.php return [ // 保留其他原有Sentry配置不变 'before_send' => function (Sentry\Event $event, ?Sentry\EventHint $hint): ?Sentry\Event { // 自定义配置:单异常事件24小时内最多上报次数 $perEventMaxCount = 5; // 自定义配置:全局所有事件24小时内最多上报总次数 $globalDailyMaxCount = 500; // 第一步:校验全局日上报是否已达上限 $globalCountKey = 'sentry:global:daily:count'; $currentGlobalCount = \Illuminate\Support\Facades\Cache::get($globalCountKey, 0); if ($currentGlobalCount >= $globalDailyMaxCount) { return null; // 达上限直接丢弃事件 } // 第二步:生成当前事件的唯一标识指纹 $eventFingerprint = null; // 优先读取事件自定义指纹 if (!empty($event->getFingerprint())) { $eventFingerprint = implode('_', $event->getFingerprint()); } // 异常类事件用类名+报错信息+首行行号生成指纹 else if ($hint?->exception instanceof \Throwable) { $exception = $hint->exception; $firstTraceLine = $exception->getTrace()[0]['line'] ?? '0'; $eventFingerprint = md5(get_class($exception) . $exception->getMessage() . $firstTraceLine); } // 普通消息类事件用事件标题生成指纹 else { $eventFingerprint = md5($event->getTitle() ?? 'unknown_event_type'); } // 第三步:校验当前事件24小时内上报次数是否达上限 $perEventCountKey = "sentry:event:count:{$eventFingerprint}"; $currentEventCount = \Illuminate\Support\Facades\Cache::get($perEventCountKey, 0); if ($currentEventCount >= $perEventMaxCount) { return null; // 达上限直接丢弃事件 } // 第四步:计数累加,缓存有效期设为24小时 \Illuminate\Support\Facades\Cache::put($perEventCountKey, $currentEventCount + 1, now()->addDay()); \Illuminate\Support\Facades\Cache::put($globalCountKey, $currentGlobalCount + 1, now()->addDay()); return $event; }, ];
方案2:基于采样率的简易全局限流
如果不需要精确控制单事件上报次数,只需要整体降低上报量,可以直接配置Sentry自带的采样率参数,数值为0到1之间的浮点数,对应上报的比例:
// config/sentry.php return [ // 错误事件采样率:0.3代表只上报30%的错误事件 'error_sample_rate' => 0.3, // 性能链路事件采样率,不需要上报链路的话可以设为0 'traces_sample_rate' => 0, ];
注意事项
- 多实例部署的项目建议使用Redis作为缓存驱动,避免不同实例计数不同步导致限流规则失效
- 可以根据自身Sentry配额调整配置项中的单事件上限、全局日上限数值,核心业务异常也可以单独加判断跳过限流规则
- 若临时遇到突发大量报错,可以直接调低采样率快速降低配额消耗
内容的提问来源于stack exchange,提问作者Ian MacLean
相关产品推荐
相关产品推荐

