别让前端监控变成“数据坟场”:从错误采集到行为回放的架构级拆解
引言
先讲个真实场景。某电商大促前夜,运营反馈“支付页偶发白屏”,但研发本地复现不了。查日志——后端接口一切正常;查监控——只有一条 ChunkLoadError 孤零零躺着,没有用户 ID、没有路由、没有网络状态。三天后靠用户录屏才定位到:某个 lazily load 的 chunk 在 CDN 边缘节点 404,只在弱网 + 特定运营商下触发。
这就是大多数团队前端监控的真实处境:数据在收,但收到的是“尸检报告”而不是“现场录像”。错误上报只报了 message,性能指标只采了 loadTime,用户行为只记了 PV/UV。三张皮各自为战,出事时拼不出完整链路。
本文不聊“怎么接入 Sentry”这种装配工内容。我们要从采集原理 → 传输协议 → 关联建模 → 存储查询整条链路做架构级拆解,重点回答三个问题:
- 错误上报如何做到不丢、不重、可还原现场?
- 性能指标如何从“一堆数字”变成“可归因的瓶颈”?
- 用户行为如何与错误/性能在同一个 traceId 下对齐?
核心概念:把监控想象成“医院急诊系统”
前端监控的本质,和急诊科看病是一个道理:
| 医院急诊 | 前端监控 | 技术映射 |
|---|---|---|
| 分诊台 | 错误分级 | error.type + severity |
| 病历本 | 上下文快照 | breadcrumb + context |
| 生命体征仪 | 性能指标 | PerformanceObserver |
| 监控录像 | 行为回放 | rrweb 类 DOM 快照 |
| 病历归档 | 存储与检索 | 列式存储 + 倒排索引 |
关键洞察:分诊台(采集)决定生死,病历本(上下文)决定能否确诊。大多数团队把 80% 精力花在“归档”(接个 SDK),却忽略了“病历本”的完整性——这才是定位问题的命门。
从技术定义上说,一个生产级前端监控系统必须同时具备四个能力:
- 采集(Collect):无侵入、低开销地捕获错误/性能/行为
- 关联(Correlate):用统一
traceId把三类数据串成一条时间线
- 传输(Transport):可靠、批量、可降级地上报
- 消费(Consume):可聚合、可下钻、可告警
下面逐个拆到源码级。
源码/原理深度分析
1. 错误采集:window.onerror 的“三不管”地带
很多人以为 window.onerror 能兜住一切,实际上它有明确的盲区。看浏览器规范里 reportError 的触发路径,错误分为三类,捕获方式完全不同:
坑点一:资源错误不冒泡。 error 事件在资源加载失败时不冒泡,必须用捕获阶段监听:
// 资源错误必须在捕获阶段监听,且 target 不是 window 才是资源错误
window.addEventListener(
'error',
(event: Event) => {
const target = event.target as HTMLElement;
// 区分:资源错误 target 是具体元素,运行时错误 target 是 window
if (target && (target.tagName === 'IMG' || target.tagName === 'SCRIPT')) {
report({
type: 'resource',
url: (target as HTMLImageElement).src,
tag: target.tagName,
});
}
},
true // 关键:捕获阶段
);坑点二:Script error. 的成因。 当脚本来自不同源且未声明 crossorigin 时,浏览器出于安全考虑把错误信息脱敏成 Script error.,message、filename、lineno 全部为空。这不是 bug,是 CORS 策略。解法是 CDN 响应头加 Access-Control-Allow-Origin, 加载。这条如果没做,你的错误监控等于对第三方脚本瞎了。
坑点三:React 的 Error Boundary 捕获不到异步错误。 componentDidCatch 只处理 render/lifecycle 阶段同步抛出的错误,setTimeout 里的、事件处理器里的、Promise 里的它一概不管。所以 React 项目必须“Error Boundary + 全局监听”双保险:
class ErrorBoundary extends React.Component<Props, { hasError: boolean }> {
static getDerivedStateFromError() {
return { hasError: true };
}
componentDidCatch(error: Error, info: React.ErrorInfo) {
// error 是错误对象,info.componentStack 是组件栈——这是全局监听拿不到的宝贵信息
report({
type: 'react',
error: serializeError(error),
componentStack: info.componentStack,
// 关键:主动关联当前 traceId
traceId: getCurrentTraceId(),
});
}
render() {
return this.state.hasError ? <Fallback /> : this.props.children;
}
}注意
componentStack是 React 独有的“组件调用栈”,比 JS 调用栈更能定位“是哪个组件炸的”。这就是“病历本”里最值钱的一页。
2. 性能指标:PerformanceObserver 与“真实用户”的鸿沟
performance.timing 那套已经过时(navigationStart 是 2012 年的产物)。现代方案是 PerformanceObserver + Web Vitals。但源码级的坑在于:LCP/CLS/INP 都是“分布”而非“单值”。
看 web-vitals 库的核心逻辑(简化版):
// web-vitals 对 LCP 的处理:它监听的是"候选值",最终值是页面隐藏时的最后一个候选
let lcpValue = 0;
const po = new PerformanceObserver((list) => {
const entries = list.getEntries();
const last = entries[entries.length - 1] as LargestContentfulPaint;
// 关键:不立即上报,持续覆盖
lcpValue = last.startTime;
// 用户可能还在滚动,LCP 会变
});
po.observe({ type: 'largest-contentful-paint', buffered: true });
// 页面隐藏(visibilitychange -> hidden)时才"定稿"上报
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'hidden') {
report({ metric: 'LCP', value: lcpValue });
}
});为什么不能立即上报? 因为 SPA 里用户可能 3 秒后才滚动到主图,LCP 会从 1.2s 变成 3.5s。如果首屏就上报,你拿到的是“假指标”。这也是为什么 web-vitals 强调在 visibilitychange 时 flush——指标是“会话级”的,不是“页面级”的。
CLS 的坑更深。 CLS 只在“用户可见期间”的布局偏移才计入。用户切到后台标签页时的偏移不计入。所以 PerformanceObserver 的 layout-shift 回调里必须判断 entry.hadRecentInput:
let clsValue = 0;
new PerformanceObserver((list) => {
for (const entry of list.getEntries() as LayoutShift[]) {
// 用户输入后 500ms 内的偏移不算(那是用户自己搞的)
if (!entry.hadRecentInput) {
clsValue += entry.value;
}
}
}).observe({ type: 'layout-shift', buffered: true });INP(Interaction to Next Paint) 是 2024 年后取代 FID 的核心指标,它测量的是所有交互中最差的那次延迟。实现上要监听 event 的 duration,且要区分“输入延迟 + 处理时间 + 呈现延迟”三段。这块细节极多,建议直接用 web-vitals 的 onINP,不要自己造。
3. 行为分析:rrweb 的“增量快照”为什么省流量
行为回放听起来很重(录屏?),但 rrweb 用了一个极其聪明的设计:全量快照 + 增量变更。
- 全量快照:初始化时把整个 DOM 序列化成一棵 JSON 树(含 CSS)
- 增量快照:之后用
MutationObserver监听 DOM 变更,只记录 diff(节点增删、属性变化、文本变化)
- 事件流:鼠标移动、点击、输入、滚动,全部打上时间戳
这就像快递分拣:全量快照是“第一次寄件时的完整地址”,增量是“后续每次改地址的变更单”。存储层只需按 traceId 拼接,回放时重放即可。
但 rrweb 有两个生产级大坑:
- 隐私:输入框内容、
data-*敏感字段必须脱敏。用maskAllInputs: true加maskTextSelector: '.sensitive'。 - 体积:一个 10 分钟的会话可能产生 1-2MB 事件流。必须采样(如 5% 会话录制)+ 压缩(
pakogzip)+ 分片上传。
实战代码
示例 1:一个“不丢数据”的上报器(含批量、重试、降级)
这是整个监控 SDK 的心脏。核心设计:内存队列 + 定时 flush + sendBeacon 兜底 + 失败重试。
interface ReportPayload {
type: 'error' | 'perf' | 'behavior';
traceId: string;
timestamp: number;
data: Record<string, unknown>;
}
class Reporter {
private queue: ReportPayload[] = [];
private readonly maxBatch = 20;
private readonly flushInterval = 5000;
private readonly endpoint = '/api/monitor/collect';
private timer: number | null = null;
constructor() {
this.timer = window.setInterval(() => this.flush(), this.flushInterval);
// 关键:页面隐藏/卸载时,用 sendBeacon 保证最后一发不丢
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'hidden') this.flush(true);
});
window.addEventListener('pagehide', () => this.flush(true));
}
push(payload: ReportPayload) {
this.queue.push(payload);
// 队列超阈值立即发,防止内存泄漏
if (this.queue.length >= this.maxBatch) this.flush();
}
private flush(isUnload = false) {
if (this.queue.length === 0) return;
const batch = this.queue.splice(0, this.maxBatch);
const body = JSON.stringify(batch);
// 卸载场景:sendBeacon 是唯一可靠的手段(fetch 会被浏览器干掉)
if (isUnload && navigator.sendBeacon) {
// Blob 类型必须是 application/json 才能被服务端正确解析
navigator.sendBeacon(this.endpoint, new Blob([body], { type: 'application/json' }));
return;
}
// 常规场景:fetch + keepalive,失败重试 2 次
this.sendWithRetry(body, 2);
}
private async sendWithRetry(body: string, retries: number) {
try {
const res = await fetch(this.endpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body,
keepalive: true, // 允许请求在页面卸载后继续
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
} catch (e) {
if (retries > 0) {
// 指数退避,避免雪崩
setTimeout(() => this.sendWithRetry(body, retries - 1), 1000 * (3 - retries));
} else {
// 最终失败:降级写 localStorage,下次启动补发
const failed = JSON.parse(localStorage.getItem('__monitor_failed__') || '[]');
failed.push(...JSON.parse(body));
localStorage.setItem('__monitor_failed__', JSON.stringify(failed.slice(-100)));
}
}
}
}为什么 sendBeacon 是卸载场景的唯一解? 因为 fetch 在 pagehide 后会被浏览器取消(即使 keepalive 也有 64KB 限制和时序问题)。sendBeacon 由浏览器网络层接管,页面死了请求还在飞。这就像寄挂号信——你人走了,邮局照送。
示例 2:用 traceId 把错误、性能、行为串成一条时间线
这是本文最核心的“关联建模”。思路:每次路由切换生成一个 traceId,三类采集器共享它。
// trace.ts —— 全局 trace 上下文
let currentTraceId = generateId();
export function getCurrentTraceId() {
return currentTraceId;
}
export function rotateTrace() {
currentTraceId = generateId();
// 路由切换时轮换,并记录切换点作为"会话分片"
}
// router 集成(Vue Router / React Router 通用思路)
export function setupTraceOnRoute(router: { afterEach: (cb: () => void) => void }) {
router.afterEach(() => {
rotateTrace();
reporter.push({
type: 'behavior',
traceId: getCurrentTraceId(),
timestamp: Date.now(),
data: { event: 'route_change', path: location.pathname },
});
});
}
// 错误采集器自动带上 traceId
window.addEventListener('error', (e) => {
reporter.push({
type: 'error',
traceId: getCurrentTraceId(), // ← 关键关联点
timestamp: Date.now(),
data: { message: e.message, filename: e.filename, lineno: e.lineno },
});
});
// 性能采集器也带上
new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
reporter.push({
type: 'perf',
traceId: getCurrentTraceId(), // ← 同一个 traceId
timestamp: Date.now(),
data: { name: entry.name, duration: entry.duration, type: entry.entryType },
});
}
}).observe({ entryTypes: ['resource', 'measure', 'longtask'] });服务端按 traceId 聚合后,你在控制台看到的就是一条完整时间线:
[10:00:01] route_change -> /checkout
[10:00:01.2] resource /api/cart 耗时 3200ms ← 慢
[10:00:04.5] error ChunkLoadError: checkout-v2.js ← 炸
[10:00:04.6] behavior click #pay-btn没有 traceId,这三条数据就是三个孤岛;有了它,就是一部纪录片。
示例 3:基于 PerformanceObserver 的“可归因”慢资源采集
普通做法只记录“哪个资源慢”,但定位需要知道“为什么慢”——是 DNS、TCP、还是 TTFB?PerformanceResourceTiming 提供了完整的分段:
const SLOW_THRESHOLD = 1000;
new PerformanceObserver((list) => {
for (const entry of list.getEntries() as PerformanceResourceTiming[]) {
if (entry.duration < SLOW_THRESHOLD) continue;
// 把耗时拆成 5 段,直接告诉研发瓶颈在哪
const breakdown = {
dns: entry.domainLookupEnd - entry.domainLookupStart, // DNS 解析
tcp: entry.connectEnd - entry.connectStart, // TCP 握手
tls: entry.secureConnectionStart > 0
? entry.connectEnd - entry.secureConnectionStart : 0, // TLS 握手
ttfb: entry.responseStart - entry.requestStart, // 首字节
download: entry.responseEnd - entry.responseStart, // 传输
};
// 归因:最大耗时项就是"罪魁"
const bottleneck = Object.entries(breakdown)
.sort(([, a], [, b]) => b - a)[0][0];
reporter.push({
type: 'perf',
traceId: getCurrentTraceId(),
timestamp: Date.now(),
data: {
url: entry.name,
duration: entry.duration,
breakdown,
bottleneck, // 直接告诉研发:这次慢在 TTFB
initiatorType: entry.initiatorType, // script / img / fetch
},
});
}
}).observe({ type: 'resource', buffered: true });这段代码的价值在于:把“慢”从形容词变成了可执行的归因。看到 bottleneck: 'ttfb',研发就知道该去查后端而不是 CDN;看到 bottleneck: 'dns',就该查 DNS 预解析。
方案对比:自建 vs Sentry vs 云厂商
| 维度 | 自建 SDK + 自建后端 | Sentry(自托管/云) | 云厂商(ARMS/APM) |
|---|---|---|---|
| 数据主权 | 完全可控 | 云版数据出境 | 依赖厂商 |
| 行为回放 | 需集成 rrweb | 内置(付费功能) | 部分支持 |
| 定制采集 | 无限制 | 受 SDK 约束 | 受 API 约束 |
| 成本 | 人力成本高,存储便宜 | 按事件量计费,量大贵 | 按量计费,中等 |
| 上手速度 | 慢(2-4 周) | 快(半天) | 快(半天) |
| 适用场景 | 大厂、强合规、深度定制 | 中小团队、快速起步 | 已用该云生态 |
我的观点:90% 的团队应该用 Sentry 起步,但一定要自建一条“关键链路”的旁路采集——因为 Sentry 的采样率、脱敏规则、聚合维度未必匹配你的业务。当 Sentry 报警“错误率上升”时,你得有能力下钻到“是哪个 traceId、哪段用户行为、哪个性能瓶颈触发的”。自建的不是监控系统,是“下钻能力”。
最佳实践与避坑指南
- 采样率要分层:错误 100% 采集(量小),性能 10-20%,行为回放 1-5%。全量采集行为流,存储成本会吃掉你的预算。
- 脱敏在客户端做,不在服务端做:密码、身份证、token 一旦传出就不可控,客户端
beforeSend钩子里正则替换。 traceId要有生命周期:路由切换轮换,但同一会话的 traceId 要有父子关系(parentTraceId),否则多页应用拼不出完整漏斗。- 别用
console.error当上报:它不携带堆栈上下文,且会被用户控制台吞掉。用专用report()。 - 源映射(sourcemap)必须私密上传:错误堆栈是压缩后的,没有 sourcemap 等于看天书。但 sourcemap 不能公开(会泄露源码),应在上报时由服务端用私有 sourcemap 还原。
- 性能指标看 P75/P95,不看均值:均值会被长尾掩盖。LCP 均值 2s 可能意味着 30% 用户超过 4s。
- 告警要有“基线”:错误率突增 50% 才告警,而不是“有错误就告警”——后者会让你被噪音淹没。
总结
前端监控的本质不是“采集技术”,而是关联建模。错误、性能、行为三类数据,单独看都是碎片;用 traceId 串起来,才是一部能定位问题的纪录片。
回顾三个关键点:
- 采集要懂源码:
window.onerror的盲区、Script error.的 CORS 成因、PerformanceObserver的“候选值”机制,决定了你的数据是“真”还是“假”。 - 传输要抗死:
sendBeacon+ 批量 + 重试 + 降级,是“不丢数据”的四道防线。 - 关联是灵魂:
traceId贯穿错误/性能/行为,才能从“报警”走向“归因”。
延伸思考:当 AI 辅助排障普及后,监控系统的价值会从“给人看”转向“给模型喂”——数据结构化程度(而非可视化美观度)将成为核心竞争点。你现在的上报 schema,是否已经为“机器可读”做好了准备?
*本文代码示例基于 TypeScript 5.x + 现代浏览器 API,可在 Vite/Webpack 项目直接集成。生产环境请补充采样、脱敏与 sourcemap 还原链路。*