前端监控体系:错误、性能与用户行为
MrSmy Lv5

“用户说页面白屏了,我们查了半天没发现问题”——这是没有前端监控的典型状态。服务端有日志和 APM,前端却常常是”薛定谔的 bug”。

这篇讲我们搭一套最小可用前端监控的过程:错误怎么抓、性能怎么采、sourcemap 怎么处理。

错误采集:四种入口

1. 运行时错误

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
window.addEventListener('error', (event) => {
// 资源加载错误(img/script/link)也走这里,但 event.message 为空
if (event.target && event.target !== window && !event.message) {
report({
type: 'resource',
tagName: event.target.tagName,
src: event.target.src || event.target.href,
})
return
}

report({
type: 'error',
message: event.message,
filename: event.filename,
lineno: event.lineno,
colno: event.colno,
stack: event.error?.stack,
})
}, true) // 必须 capture=true,否则拿不到资源错误

capture: true 是关键——资源错误不冒泡,用默认的 false 捕获不到。

2. Promise rejection

1
2
3
4
5
6
7
8
window.addEventListener('unhandledrejection', (event) => {
const reason = event.reason
report({
type: 'unhandledrejection',
message: reason?.message ?? String(reason),
stack: reason?.stack,
})
})

**这一类占我们线上错误的 62%**——因为大部分业务代码是 async,而 await 的异常容易漏掉 catch。

3. 框架层错误

React:

1
2
3
4
5
6
7
8
9
10
11
12
13
class ErrorBoundary extends React.Component {
componentDidCatch(error, info) {
report({
type: 'react',
message: error.message,
stack: error.stack,
componentStack: info.componentStack,
})
}
render() {
return this.state.hasError ? <Fallback /> : this.props.children
}
}

Vue 3:

1
2
3
4
5
6
7
8
9
app.config.errorHandler = (err, instance, info) => {
report({
type: 'vue',
message: err.message,
stack: err.stack,
componentName: instance?.$options.name,
info, // 比如 "render function"、"setup function"
})
}

框架错误的价值在于 **componentStack**——它告诉你错误发生在哪个组件树路径上,比单纯的 JS 堆栈有用得多。

4. 接口错误

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
async function request(url, options) {
const start = performance.now()
try {
const res = await fetch(url, options)
if (!res.ok) {
report({
type: 'http',
url,
status: res.status,
duration: performance.now() - start,
})
}
return res
} catch (e) {
report({ type: 'network', url, message: e.message })
throw e
}
}

上下文:没有上下文就没有用

一条错误堆栈信息 Cannot read property 'name' of undefined,单独看毫无价值。要能定位,必须带上:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
const context = {
// 用户与环境
userId: getUserId(),
sessionId: getSessionId(),
url: location.href,
referrer: document.referrer,

// 版本
appVersion: __APP_VERSION__,
buildTime: __BUILD_TIME__,

// 设备
ua: navigator.userAgent,
screen: `${screen.width}x${screen.height}`,
dpr: devicePixelRatio,

// 网络
connection: navigator.connection?.effectiveType,

// 自定义
route: router.currentRoute.value.fullPath,
featureFlags: getActiveFlags(),
}

**关键是 appVersion + route**——能立刻回答”是不是新版本引入的”和”哪个页面出问题”。

面包屑:还原用户操作路径

只靠错误堆栈,你只能知道”代码崩了”,不知道”用户做了什么”。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
const breadcrumbs = []
const MAX = 30

function addBreadcrumb(item) {
breadcrumbs.push({
...item,
timestamp: Date.now(),
})
if (breadcrumbs.length > MAX) breadcrumbs.shift()
}

// 自动采集
addEventListener('click', (e) => {
const el = e.target.closest('[data-track]') || e.target
addBreadcrumb({
type: 'click',
text: el.textContent?.slice(0, 40),
tag: el.tagName,
})
}, true)

addEventListener('popstate', () => {
addBreadcrumb({ type: 'navigation', to: location.pathname })
})

// 接口请求
addBreadcrumb({ type: 'xhr', method, url, status })

上报错误时带上面包屑:

1
report({ ...error, breadcrumbs: [...breadcrumbs] })

这样在后台看到的是一条完整的”用户操作时间线”:

1
2
3
4
5
6
14:23:01  navigation  /orders
14:23:02 xhr GET /api/orders 200
14:23:05 click "导出"
14:23:05 xhr POST /api/export 500
14:23:05 error Cannot read property 'name' of undefined
at exportOrder (ExportDialog.vue:42)

这比堆栈有用 10 倍。

性能采集:Core Web Vitals

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import { onCLS, onFCP, onINP, onLCP, onTTFB } from 'web-vitals'

const report = (metric) => {
send('/api/rum', {
name: metric.name, // LCP / INP / CLS ...
value: metric.value,
rating: metric.rating, // good / needs-improvement / poor
id: metric.id,
route: location.pathname,
appVersion: __APP_VERSION__,
})
}

onLCP(report)
onINP(report) // 2024 年起 INP 替代 FID
onCLS(report)
onFCP(report)
onTTFB(report)

INP(Interaction to Next Paint) 是 2024 年 3 月正式取代 FID 的指标。它测量”页面上每次交互的响应延迟”,取较差的那个。

我们踩的坑:INP 在开发环境测不出来——开发服务器的构建产物没压缩、没分包,本地机器太快。必须在生产环境采集真实用户数据(RUM)。

性能采集的补充:长任务与资源

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// 长任务(> 50ms)
new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
send('/api/rum/longtask', {
duration: entry.duration,
startTime: entry.startTime,
attribution: entry.attribution?.[0]?.containerSrc, // 哪个脚本
})
}
}).observe({ entryTypes: ['longtask'] })

// 慢资源
new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
if (entry.duration > 1000) {
send('/api/rum/slow-resource', {
name: entry.name,
type: entry.initiatorType,
duration: entry.duration,
size: entry.transferSize,
})
}
}
}).observe({ entryTypes: ['resource'] })

长任务的归因很关键——attribution.containerSrc 能告诉你是哪个 JS 文件里的任务阻塞了主线程。

上报策略

1. 批量 + 延迟

每条错误都发一个请求,会拖慢页面且制造大量请求。用队列:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
let queue = []
let timer = null

function enqueue(item) {
queue.push(item)
if (queue.length >= 10) {
flush()
} else if (!timer) {
timer = setTimeout(flush, 5000)
}
}

async function flush() {
clearTimeout(timer)
timer = null
if (!queue.length) return

const batch = queue
queue = []

try {
navigator.sendBeacon('/api/errors', JSON.stringify(batch))
} catch {
// 兜底:普通请求
fetch('/api/errors', { method: 'POST', body: JSON.stringify(batch), keepalive: true })
}
}

sendBeacon 是页面关闭时唯一可靠的上报方式——普通 fetch 在 unload 时会被取消。

1
2
3
4
addEventListener('pagehide', flush)      // 用 pagehide 而不是 unload(后者在移动端不可靠)
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'hidden') flush()
})

2. 采样

错误可以全量(量不大),性能指标要采样(量大):

1
2
3
4
5
6
7
const SAMPLING_RATE = 0.1      // 10%

function shouldSample() {
// 用 sessionId 哈希,保证同一会话的采样决策一致
const hash = hashString(getSessionId())
return hash % 1000 < SAMPLING_RATE * 1000
}

“同一会话一致采样”很重要——否则一个用户的 LCP 采到了、INP 没采到,无法关联分析。

3. 去重与限流

1
2
3
4
5
6
7
8
9
10
11
const seen = new Map()

function shouldReport(key) {
const count = seen.get(key) ?? 0
if (count >= 5) return false // 同一个错误最多报 5 次

seen.set(key, count + 1)
return true
}

// key 用 message + 文件 + 行号

错误风暴是真实威胁:一个渲染循环里的错误可能每秒触发几百次,把上报接口打挂。

sourcemap:最重要的一环

生产代码是压缩过的:

1
2
TypeError: Cannot read property 'name' of undefined
at e.t (app.4f3c.js:1:28471)

没有 sourcemap 的话,这条错误无法定位。

三种方案:

1. 方案 A:sourcemap 部署到服务器,但只对内部开放

1
2
3
4
5
6
7
# 不暴露 .map 文件给公网
location ~* \.map$ {
deny all;
# 只允许内网 IP
allow 10.0.0.0/8;
deny all;
}

后端解析 sourcemap,把堆栈还原后再存数据库。

2. 方案 B:不部署 sourcemap,上传到监控平台

构建后把 .map 上传到 Sentry(或自建服务),然后删掉。生产环境完全不含 sourcemap。

3. 方案 C:隐藏 sourcemap

1
2
3
4
5
6
// vite.config.js
export default {
build: {
sourcemap: 'hidden', // 生成 map 但不加 //# sourceMappingURL
},
}

生成 .map 文件,但 JS 里不引用。只有你自己能拿到并上传给监控平台。这是最推荐的方案。

千万不要公开 sourcemap:

1
build: { sourcemap: true }      // ❌ 任何人打开 DevTools 就能看到你的源码

我们的一个客户就因为这个泄露了内部 API 地址和注释里的账号密码。

一个错误还原的例子

原始上报:

1
2
3
4
5
6
7
{
"message": "Cannot read properties of undefined (reading 'name')",
"stack": "TypeError: Cannot read properties of undefined (reading 'name')\n at t.value (app.4f3c.js:1:28471)\n at VueComponent.e (vendor.9a2b.js:1:120334)",
"appVersion": "2.14.3",
"route": "/orders/12345",
"breadcrumbs": [...]
}

用 source-map 库还原:

1
2
3
4
5
6
7
8
const { SourceMapConsumer } = require('source-map')

async function resolve(rawStack, maps) {
const consumer = await new SourceMapConsumer(maps['app.4f3c.js'])
// 解析 "at t.value (app.4f3c.js:1:28471)" 里的 line/column
const pos = consumer.originalPositionFor({ line: 1, column: 28471 })
return pos // { source: 'src/views/OrderDetail.vue', line: 87, column: 12 }
}

还原后:

1
2
TypeError: Cannot read properties of undefined (reading 'name')
at OrderDetail.vue:87:12 (computed: order.customer.name)

这条信息才能指导修复。

隐私与合规

监控数据会包含用户信息,必须脱敏:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const SENSITIVE = /(password|token|secret|authorization|phone|idcard)/i

function sanitize(obj) {
if (!obj || typeof obj !== 'object') return obj
const out = Array.isArray(obj) ? [] : {}
for (const [k, v] of Object.entries(obj)) {
if (SENSITIVE.test(k)) {
out[k] = '[REDACTED]'
} else if (typeof v === 'object') {
out[k] = sanitize(v)
} else {
out[k] = v
}
}
return out
}

要脱敏的地方:

  • 接口请求/响应体(含手机号、地址、token)
  • URL 里的查询参数(?token=xxx)
  • 表单输入的 value
  • 错误消息(某些库会把参数拼进 message)

后台怎么看

采集只是第一步,能”用起来”才是目的。我们的监控后台有四个视图:

1. 错误概览

1
2
3
4
5
近 24 小时
总错误数 1,284
影响用户数 342
新增错误类型 3 ← 重点关注
未处理 12

2. 错误详情

按 message + 文件 + 行号聚类,每组显示:

  • 发生次数 / 影响用户数
  • 首次出现 / 最后出现(判断是不是新版本引入)
  • 版本分布(哪些版本有问题)
  • 浏览器 / 系统分布
  • 面包屑(用户操作路径)
  • 还原后的堆栈

3. 性能面板

1
2
3
LCP  p75: 2.4s   p90: 4.1s
INP p75: 180ms p90: 420ms
CLS p75: 0.08

按 route 分组,找出最慢的页面。

4. 版本对比

1
2
2.14.2  LCP p75 2.1s  错误率 0.3%
2.14.3 LCP p75 2.9s 错误率 1.8% ← 这个版本有问题

版本对比是最有用的功能——它把”上线后变差了”变成可量化的事实。

踩过的坑

1. window.onerror 的 event.error 可能为 null

跨域脚本(CDN 上的)默认不暴露错误详情,只给 "Script error."。解决方法:

1
2
3
4
5
<script
src="https://cdn.example.com/app.js"
crossorigin="anonymous"
integrity="sha384-xxxxxxxx">
</script>
1
Access-Control-Allow-Origin: *

两边都要配,否则错误信息就是空的。

integrity(SRI)顺便值得一起加上——crossorigin 解决的是”能拿到错误详情”,**SRI 解决的是”CDN 被篡改时不会执行恶意代码”**。两者配合才是完整的第三方脚本加载策略:

1
2
# 生成 hash
openssl dgst -sha384 -binary app.js | openssl base64 -A

注意 SRI 会让”换版本”变成”改 HTML”(hash 变了),所以它只适合”版本相对固定”的第三方脚本;你的业务 bundle 用”文件名带 hash + 自托管”更合适。

2. 压缩后的变量名影响错误消息

t.name vs order.name——不管有没有 sourcemap,message 里的变量名都是压缩后的。

所以要靠堆栈 + sourcemap,不能靠 message 匹配。

3. unhandledrejection 在某些库内部被吞掉

有些库自己加了 unhandledrejection 处理(比如 core-js 的 polyfill),可能阻止你的监听器执行。要检查加载顺序。

4. 上报接口自己出问题

监控系统和业务系统应该物理隔离(不同域名、不同服务)。否则业务挂了监控也挂了,什么都看不到。

5. 移动端的采样失真

navigator.sendBeacon 在移动端后台标签页会被丢弃。要接受”数据不完整”,用采样率推算总量。

6. 本地开发时的错误上报

开发环境不该上报(会污染数据)。但要能在开发环境看到上报内容:

1
2
3
4
5
if (import.meta.env.DEV) {
report = (data) => console.log('[telemetry]', data)
} else {
report = realReport
}

小结

一套最小可用的前端监控需要四块:

模块 关键点
错误采集 四种入口 + capture:true + Promise rejection
上下文 版本 + 路由 + 面包屑(比堆栈有用)
性能采集 Core Web Vitals + 长任务 + sendBeacon
sourcemap hidden 模式 + 上传平台 + 不公开

优先级建议:

  1. 先做错误采集 + sourcemap(能回答”哪里崩了”)
  2. 再做面包屑(能回答”用户怎么走到这一步”)
  3. 最后做性能采集(能回答”为什么慢”)

一个反直觉的经验:我们 80% 的排查时间花在”复现问题”上。有了面包屑 + 版本 + 路由,复现时间从平均 40 分钟降到 5 分钟。这比任何”智能分析”都有用。

  • 本文标题:前端监控体系:错误、性能与用户行为
  • 本文作者:MrSmy
  • 创建时间:2023-10-29 20:47:00
  • 本文链接:https://fengyang.live/2023/10/29/前端监控体系:错误、性能与用户行为/
  • 版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!