Skip to content

前端可观测性 ​

上线后才是真实世界。用户不会把控制台截图发给你,你必须自己看见问题。

一句话先记住:前端可观测性 = 错误 + 性能 + 用户行为 + 发布版本 + 上下文。


一、前端要观测什么 ​

text
错误:
  JS exception
  Promise rejection
  React error boundary
  API error
  resource load error

性能:
  Web Vitals
  route timing
  API latency
  long task
  bundle size

行为:
  page view
  click
  form submit
  conversion
  feature usage

上下文:
  user id
  session id
  release version
  route
  browser
  request id

只接一个 console.error 不叫可观测。


二、错误监控 ​

最小接入:

ts
import * as Sentry from '@sentry/react';

Sentry.init({
  dsn: import.meta.env.VITE_SENTRY_DSN,
  environment: import.meta.env.MODE,
  release: import.meta.env.VITE_APP_VERSION,
});

React Error Boundary:

tsx
export function AppErrorBoundary({ children }: { children: React.ReactNode }) {
  return (
    <Sentry.ErrorBoundary fallback={<ErrorPage />}>
      {children}
    </Sentry.ErrorBoundary>
  );
}

手动上报:

ts
try {
  await saveUser(input);
} catch (error) {
  Sentry.captureException(error, {
    tags: { feature: 'user-create' },
    extra: { input },
  });
  throw error;
}

三、全局错误 ​

ts
window.addEventListener('error', (event) => {
  reportError(event.error, {
    type: 'window.error',
    filename: event.filename,
    lineno: event.lineno,
  });
});

window.addEventListener('unhandledrejection', (event) => {
  reportError(event.reason, {
    type: 'unhandledrejection',
  });
});

注意:

  • error 抓同步错误和资源错误
  • unhandledrejection 抓未处理 Promise
  • React 渲染错误还要 Error Boundary

四、Source Map ​

没有 source map,线上报错只能看到:

text
TypeError: Cannot read properties of undefined
at app.8af31.js:1:23891

构建要上传 source map 到监控平台:

bash
sentry-cli releases new "$VERSION"
sentry-cli releases files "$VERSION" upload-sourcemaps dist/assets
sentry-cli releases finalize "$VERSION"

生产环境不要公开 source map:

text
上传到 Sentry / Datadog
不要让 CDN 暴露 .map 文件

否则源码会被直接下载。


五、Web Vitals ​

核心指标:

text
LCP  最大内容绘制       首屏主体出来多快
INP  交互到下一帧       用户点了以后卡不卡
CLS  累积布局偏移       页面是否乱跳

采集:

ts
import { onCLS, onINP, onLCP } from 'web-vitals';

function sendMetric(metric: unknown) {
  navigator.sendBeacon('/api/metrics', JSON.stringify(metric));
}

onCLS(sendMetric);
onINP(sendMetric);
onLCP(sendMetric);

sendBeacon 适合页面卸载时发送,不会阻塞跳转。


六、API 观测 ​

request 层统一记录:

ts
export async function request<T>(url: string, init?: RequestInit): Promise<T> {
  const startedAt = performance.now();
  const requestId = crypto.randomUUID();

  try {
    const res = await fetch(url, {
      ...init,
      headers: {
        ...init?.headers,
        'x-client-request-id': requestId,
      },
    });

    reportApiMetric({
      url,
      method: init?.method ?? 'GET',
      status: res.status,
      duration: performance.now() - startedAt,
      requestId,
    });

    return await res.json();
  } catch (error) {
    reportError(error, { url, requestId });
    throw error;
  }
}

至少记录:

  • URL 模板,不要带敏感 query
  • method
  • status
  • duration
  • requestId
  • release

七、用户行为埋点 ​

事件命名要稳定:

ts
track('user_create_submit', {
  source: 'users_page',
  role: input.role,
});

不要这样:

ts
track('点击了创建用户按钮');
track('click');
track('button_click_123');

推荐格式:

text
domain_action_result

user_create_submit
user_create_success
user_create_failed
order_export_started
order_export_downloaded

埋点是数据契约,不是随手打日志。


八、隐私边界 ​

不要上报:

  • 密码
  • token
  • 身份证 / 银行卡
  • 完整手机号 / 邮箱
  • 用户输入的富文本正文
  • 私密文件 URL

上报前做脱敏:

ts
function maskEmail(email: string) {
  const [name, domain] = email.split('@');
  return `${name.slice(0, 2)}***@${domain}`;
}

可观测性不能变成数据泄漏。


九、发布版本 ​

每次构建注入版本:

ts
// vite.config.ts
export default defineConfig({
  define: {
    __APP_VERSION__: JSON.stringify(process.env.GITHUB_SHA),
  },
});

声明:

ts
declare const __APP_VERSION__: string;

上报时带上:

ts
Sentry.setTag('release', __APP_VERSION__);

没有 release,你无法判断错误来自哪个版本。


十、前端日志分级 ​

text
debug  本地调试,生产默认不上报
info   用户关键路径
warn   可恢复异常
error  功能失败
fatal  页面不可用

示例:

ts
logger.warn('upload_retry', {
  fileSize: file.size,
  retryCount,
});

logger.error('checkout_failed', {
  orderId,
  requestId,
});

日志要结构化。不要只写一句字符串。


十一、仪表盘 ​

至少看这些图:

text
错误:
  error count by release
  error rate by route
  top error issues

性能:
  LCP p75
  INP p75
  CLS p75
  API latency p95

业务:
  conversion rate
  submit success rate
  upload failure rate

只看平均值没用。性能和延迟看 p75 / p95。


十二、检查清单 ​

  • [ ] JS error 是否自动上报
  • [ ] unhandled rejection 是否上报
  • [ ] React / Vue 是否有错误边界
  • [ ] source map 是否上传且不公开
  • [ ] Web Vitals 是否采集
  • [ ] API latency / status 是否采集
  • [ ] requestId 是否贯穿前后端
  • [ ] release 是否注入
  • [ ] 埋点命名是否规范
  • [ ] 是否过滤敏感数据
  • [ ] 是否有错误率 / 性能 / 业务转化仪表盘

十三、心智模型 ​

text
错误监控告诉你哪里坏了
性能监控告诉你哪里慢了
行为埋点告诉你用户怎么用
release 告诉你哪个版本引入问题
requestId 告诉你怎么和后端日志对上

前端上线后没有可观测性,就是闭着眼开车。

下一篇 50 做一个实战项目闭环。