前端监控实践:错误、性能与用户行为追踪
常见误区
前端监控?这不是后端的事吗?
"我的代码没问题,不需要监控"——结果用户反馈网站崩溃,自己却一无所知; "我有日志,还需要什么监控"——结果日志太多,根本找不到问题; "监控太复杂了,我没时间做"——结果问题频发,用户流失。
醒醒吧,前端监控是前端开发的重要组成部分,不是可有可无的!
实施前端监控的价值
- 问题发现:及时发现和定位前端问题
- 性能优化:了解网站性能瓶颈
- 用户体验:了解用户真实使用情况
- 数据驱动:基于数据做出决策
缺乏监控的代码示例
// 反面教材:没有任何监控
function App() {
return (
<div>
<h1>我的网站</h1>
{/* 没有任何错误处理和监控 */}
<button onClick={() => {
// 可能会出错的代码
const data = fetchData();
processData(data);
}}>
点击我
</button>
</div>
);
}
// 反面教材:简单的 console.log
function fetchData() {
try {
const data = /* 从 API 获取数据 */;
return data;
} catch (error) {
console.log('Error:', error); // 只在控制台打印,没有持久化
return null;
}
}
集成 Sentry 监控方案
// 正确的做法:使用专业的监控工具
// 安装依赖:npm install @sentry/react @sentry/tracing
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import * as Sentry from '@sentry/react';
import { BrowserTracing } from '@sentry/tracing';
// 初始化 Sentry
Sentry.init({
dsn: 'YOUR_SENTRY_DSN',
integrations: [new BrowserTracing()],
tracesSampleRate: 1.0,
// 环境信息
environment: process.env.NODE_ENV,
// 发布版本
release: '[email protected]'
});
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<App />
</React.StrictMode>
);
// 正确的做法:错误边界
import React from 'react';
import * as Sentry from '@sentry/react';
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
// 更新状态,下次渲染时显示降级 UI
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
// 捕获错误并发送到 Sentry
Sentry.captureException(error, { extra: errorInfo });
}
render() {
if (this.state.hasError) {
// 降级 UI
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
// 正确的做法:性能监控
import { usePerformanceObserver } from 'web-vitals';
function PerformanceMonitor() {
usePerformanceObserver(({ entries }) => {
entries.forEach((entry) => {
// 发送性能数据到监控服务
if (entry.name === 'first-contentful-paint') {
Sentry.captureMessage('FCP', { level: 'info', extra: { value: entry.startTime } });
}
if (entry.name === 'largest-contentful-paint') {
Sentry.captureMessage('LCP', { level: 'info', extra: { value: entry.startTime } });
}
});
});
return null;
}
// 正确的做法:用户行为监控
function trackUserAction(action, data) {
// 发送用户行为数据到监控服务
Sentry.captureMessage(action, { level: 'info', extra: data });
}
// 正确的做法:网络请求监控
function fetchWithMonitoring(url, options = {}) {
const start = performance.now();
return fetch(url, options)
.then(response => {
const end = performance.now();
const duration = end - start;
// 发送网络请求数据到监控服务
Sentry.captureMessage('Network Request', { level: 'info', extra: { url, status: response.status, duration } });
return response;
})
.catch(error => {
// 捕获网络请求错误
Sentry.captureException(error, { extra: { url } });
throw error;
});
}
// 正确的做法:在组件中使用
function App() {
return (
<ErrorBoundary>
<PerformanceMonitor />
<div>
<h1>我的网站</h1>
<button onClick={() => {
trackUserAction('Button Click', { button: 'submit' });
fetchWithMonitoring('https://api.example.com/data')
.then(res => res.json())
.then(data => processData(data))
.catch(error => {
console.error('Error:', error);
});
}}>
点击我
</button>
</div>
</ErrorBoundary>
);
}
总结与建议
看看,这才叫前端监控!不是简单地 console.log,而是使用专业的监控工具,从错误监控、性能监控、用户行为监控等多个方面入手。
记住,前端监控不是为了发现错误,而是为了预防错误。通过监控数据,你可以了解用户的真实使用情况,发现潜在的问题,从而不断优化你的网站。
所以,别再觉得监控不重要了,它是你网站质量的保障!
核心要点
- 错误监控:使用 Sentry 等工具捕获和分析错误
- 性能监控:监控 Core Web Vitals 等性能指标
- 用户行为:跟踪用户点击、页面浏览等行为
- 网络监控:监控 API 请求的响应时间和成功率
- 错误边界:使用 React 错误边界捕获组件错误
- 日志聚合:集中管理和分析日志
- 告警机制:设置阈值,当出现问题时及时告警
- 数据可视化:通过图表直观展示监控数据
