从零搭建前端监控系统:错误捕获、性能采集和告警
Building a Frontend Monitoring System from Scratch: Error Capture, Performance Collection and Alerting
| Lisa | 2026-08-27T21:39:29
之前用的第三方监控太贵了,我们自己搭了一套前端监控系统。核心功能包括 JS 错误捕获、性能指标采集和钉钉告警。
Built our own frontend monitoring system to replace expensive third-party solutions. Core features include JS error capture, performance metrics collection, and DingTalk alerting.
之前用 Sentry 做前端错误监控,一个月要好几百刀,对于我们这种小团队来说实在肉疼。花了两周时间自己搭了一套,功能虽然没 Sentry 全,但是完全够用了。 整体架构 分三部分: SDK:嵌入前端页面,负责数据采集和上报 收集服务:接收数据,写入 ClickHouse 看板和告警:Grafana 展示 + 钉钉机器人告警 SDK 核心实现 JS 错误捕获 // 全局错误 window.addEventListener('error', (event) => { report({ type: 'js_error', message: event.message, filename: event.filename, lineno: event.lineno, colno: event.colno, stack: event.error?.stack }); }); // Promise 未捕获异常 window.addEventListener('unhandledrejection', (event) => { report({ type: 'promise_error', message: event.reason?.message || String(event.reason), stack: event.reason?.stack }); }); 性能指标采集 用 PerformanceObserver 采集 Web Vitals: new PerformanceObserver((list) => { for (const entry of list.getEntries()) { report({ type: 'performance', name: entry.name, value: entry.value || entry.duration, rating: getRating(entry.name, entry.value) }); } }).observe({ type: 'largest-contentful-paint', buffered: true }); 数据上报策略 不是每条数据都立即上报,做了一些优化: 批量上报:每 10 条或每 5 秒上报一次 页面关闭时用 navigator.sendBeacon 兜底 采样率:非关键数据只采 10% 相同错误 1 分钟内只上报一次 效果 上线一个月,捕获了 47 个之前不知道的前端错误,其中有 3 个影响了核心流程。性能监控也帮我们发现了一个特定安卓机型上的渲染问题。总花费就是一台 2C4G 的服务器,每月 30 块钱。
Replaced expensive Sentry subscription with a custom frontend monitoring system built in two weeks. Architecture SDK (data collection) → Collection service (ClickHouse storage) → Grafana dashboard + DingTalk alerts. Key Features JS error capture via window error/unhandledrejection listeners, Web Vitals collection via PerformanceObserver, batch reporting with sendBeacon fallback, sampling, and deduplication. Results Caught 47 previously unknown frontend errors in the first month, 3 affecting core flows. Total cost: one 2C4G server at $5/month.