当前位置: 首页 > news >正文

WebTracing:一站式前端埋点监控解决方案

WebTracing 埋点SDK学习指南

📊 SDK简介

WebTracing 是一个基于 JavaScript 的前端埋点SDK,为前端项目提供全面的监控解决方案。

🌟 核心功能

WebTracing 努力为你的前端项目提供8大监控手段

  • 📈 行为监控 - 用户交互行为追踪
  • ⚡ 性能监控 - 页面加载和运行性能
  • 🚨 异常监控 - JavaScript错误和异常捕获
  • 🌐 请求监控 - HTTP请求状态和性能
  • 📦 资源监控 - 静态资源加载情况
  • 🔄 路由监控 - SPA路由切换追踪
  • 👁️ 曝光监控 - 元素可见性监控
  • 🎬 录屏功能 - 用户操作录制回放

✨ SDK特点

  • 纯JavaScript编写 - 支持所有现代浏览器环境
  • 框架支持 - 提供Vue2、Vue3专用版本
  • 轻量级 - 最小化性能影响
  • 灵活配置 - 丰富的配置选项
  • 数据处理 - 内置数据缓存和批量发送机制

📦 安装部署

包总览

# 核心实现包 - 原生JavaScript
pnpm install @web-tracing/core# Vue2专用版本
pnpm install @web-tracing/vue2# Vue3专用版本  
pnpm install @web-tracing/vue3

1. HTML & JavaScript 集成

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>WebTracing Demo</title>
</head>
<body><!-- CDN方式引入 --><script src="https://cdn.jsdelivr.net/npm/@web-tracing/core"></script><script>webtracing.init({appName: 'my-app',debug: true,pv: true,performance: true,error: true,event: true,cacheMaxLength: 10,cacheWatingTime: 1000,userUuid: 'init_userUuid',scopeError: true,tracesSampleRate: 0.5,ignoreErrors: ['111', /^promise/, /.*split is not .* function/],ignoreRequest: ['111', /normal/],beforePushEventList(data) {return data},beforeSendData(data) {// 返回false代表sdk不再发送return data},afterSendData(data) {console.log('数据发送完成', data)}})</script>
</body>
</html>

2. Vue2 项目集成

import WebTracing from '@web-tracing/vue2'Vue.use(WebTracing, {dsn: '/trackweb',appName: 'vue2-app',debug: true,pv: true,performance: true,error: true,event: true,cacheMaxLength: 10,cacheWatingTime: 1000,userUuid: 'init_userUuid',scopeError: true,tracesSampleRate: 0.5,ignoreErrors: ['111', /^promise/, /.*split is not .* function/],ignoreRequest: [/getAllTracingList/, /cleanTracingList/],beforePushEventList(data) {const arr = ['intersection', 'click']data.forEach(item => {if (arr.includes(item.eventType)) {// 触发自定义逻辑window.vm.sendMessage()}})return data},beforeSendData(data) {// 数据发送前处理return data},afterSendData(data) {// 数据发送后处理console.log('Vue2数据发送完成', data)}
})

3. Vue3 项目集成

import { createApp } from 'vue'
import WebTracing from '@web-tracing/vue3'
import App from './App.vue'const app = createApp(App)app.use(WebTracing, {dsn: '/trackweb',appName: 'vue3-app',debug: true,pv: true,performance: true,error: true,event: true,cacheMaxLength: 10,cacheWatingTime: 1000,ignoreRequest: [/getAllTracingList/,/cleanTracingList/,/getBaseInfo/,/getSourceMap/],afterSendData(data) {console.log('Vue3数据发送完成', data)}
})app.mount('#app')

⚙️ 配置选项详解

基础配置

配置项类型默认值说明
dsnstring-数据上报接口地址
appNamestring-应用名称,用于区分不同项目
debugbooleanfalse开启调试模式,控制台输出详细日志
userUuidstring-用户唯一标识符

功能开关

配置项类型说明
pvboolean页面访问统计 (Page View)
performanceboolean性能监控开关
errorboolean错误监控开关
eventboolean事件监控开关
scopeErrorboolean作用域错误捕获

数据缓存配置

配置项类型默认值说明
cacheMaxLengthnumber10缓存队列最大长度
cacheWatingTimenumber1000缓存等待时间(ms)
tracesSampleRatenumber1.0数据采样率 (0-1)

过滤配置

{// 忽略的错误ignoreErrors: ['111',                              // 字符串匹配/^promise/,                         // 正则匹配/.*split is not .* function/       // 正则匹配],// 忽略的请求ignoreRequest: [/getAllTracingList/,/cleanTracingList/,/getBaseInfo/]
}

生命周期钩子

{// 事件入队前处理beforePushEventList(data) {// 可对数据进行预处理console.log('事件入队:', data)return data},// 数据发送前处理beforeSendData(data) {// 返回false阻止发送console.log('即将发送:', data)return data},// 数据发送后处理afterSendData(data) {console.log('发送完成:', data)}
}

🔧 功能模块详解

1. 📈 行为监控 (Event Tracking)

自动捕获用户交互行为:

// 自动监控的事件类型
const eventTypes = ['click',        // 点击事件'input',        // 输入事件  'change',       // 表单变化'submit',       // 表单提交'scroll',       // 滚动事件'resize'        // 窗口调整
]// 手动触发事件
webtracing.track('custom_event', {category: 'user_action',action: 'button_click',label: 'header_login_btn',value: 1
})

2. ⚡ 性能监控 (Performance)

监控页面加载和运行性能:

// 监控指标
const performanceMetrics = {FCP: 'First Contentful Paint',      // 首次内容绘制LCP: 'Largest Contentful Paint',    // 最大内容绘制FID: 'First Input Delay',           // 首次输入延迟CLS: 'Cumulative Layout Shift',     // 累积布局偏移TTFB: 'Time to First Byte',         // 首字节时间FP: 'First Paint'                   // 首次绘制
}// 自定义性能标记
webtracing.markStart('api_call')
// ... 执行API调用
webtracing.markEnd('api_call')

3. 🚨 错误监控 (Error Tracking)

自动捕获和上报错误:

// 自动捕获的错误类型
const errorTypes = ['JavaScript运行时错误','Promise未捕获错误',  '资源加载错误','网络请求错误','Vue组件错误' // Vue版本
]// 手动上报错误
webtracing.captureException(new Error('自定义错误'), {tags: {component: 'UserProfile',action: 'save_data'},extra: {userId: '12345',timestamp: Date.now()}
})

4. 🌐 请求监控 (Request Tracking)

监控HTTP请求状态和性能:

// 自动监控
const requestMetrics = {url: 'string',          // 请求URLmethod: 'string',       // 请求方法status: 'number',       // 响应状态码duration: 'number',     // 请求耗时size: 'number',         // 响应大小timestamp: 'number'     // 请求时间戳
}// 手动上报请求信息
webtracing.trackRequest({url: '/api/user/profile',method: 'GET',status: 200,duration: 350,success: true
})

5. 📦 资源监控 (Resource Tracking)

监控静态资源加载情况:

// 监控的资源类型
const resourceTypes = ['script',       // JS文件'stylesheet',   // CSS文件'img',          // 图片'font',         // 字体'fetch',        // Fetch请求'xmlhttprequest' // XHR请求
]// 资源性能指标
const resourceMetrics = {name: 'string',             // 资源名称type: 'string',             // 资源类型duration: 'number',         // 加载时长size: 'number',            // 资源大小transferSize: 'number',     // 传输大小encodedBodySize: 'number'   // 编码后大小
}

6. 🔄 路由监控 (Route Tracking)

SPA路由切换追踪:

// Vue Router 集成示例
router.beforeEach((to, from, next) => {webtracing.trackPageView({path: to.path,name: to.name,params: to.params,query: to.query,referrer: from.path})next()
})// 手动路由追踪
webtracing.trackRoute({from: '/home',to: '/profile',duration: 150,trigger: 'navigation'
})

7. 👁️ 曝光监控 (Intersection Tracking)

元素可见性监控:

// 自动曝光监控 (需要添加data属性)
<div data-track-exposure="banner_ad" data-exposure-ratio="0.5">广告内容
</div>// 手动曝光监控
webtracing.trackExposure({element: 'product_card_123',ratio: 0.8,duration: 2000,position: { x: 100, y: 200 }
})// 配置曝光参数
{intersectionRatio: 0.5,     // 可见比例阈值intersectionTime: 1000      // 持续时间阈值
}

🎯 最佳实践

1. 初始化配置建议

// 生产环境配置
const productionConfig = {dsn: 'https://api.your-domain.com/tracking',appName: 'your-app-name',debug: false,// 开启核心功能pv: true,performance: true,error: true,event: true,// 优化缓存策略cacheMaxLength: 20,cacheWatingTime: 5000,// 设置采样率 (生产环境建议降低)tracesSampleRate: 0.1,// 过滤无关错误ignoreErrors: [/Script error/,/ResizeObserver loop limit exceeded/,/Non-Error promise rejection captured/],// 过滤内部请求ignoreRequest: [/\/tracking/,/\/health-check/,/\/metrics/]
}// 开发环境配置
const developmentConfig = {...productionConfig,debug: true,tracesSampleRate: 1.0
}

2. 用户标识管理

// 用户登录后更新标识
function onUserLogin(user) {webtracing.setUser({id: user.id,email: user.email,name: user.name,role: user.role})
}// 用户登出时清理
function onUserLogout() {webtracing.clearUser()
}// 设置用户属性
webtracing.setUserProperty('vip_level', 'gold')

3. 自定义事件追踪

// 业务关键指标追踪
const trackBusinessMetrics = {// 购买转化trackPurchase(orderId, amount, currency) {webtracing.track('purchase', {order_id: orderId,amount: amount,currency: currency,timestamp: Date.now()})},// 搜索行为trackSearch(query, resultCount) {webtracing.track('search', {query: query,result_count: resultCount,search_type: 'product'})},// 功能使用trackFeatureUsage(feature, action) {webtracing.track('feature_usage', {feature: feature,action: action,user_type: 'premium'})}
}

4. 错误处理优化

// 全局错误处理
window.addEventListener('error', (event) => {// 添加更多上下文信息webtracing.captureException(event.error, {tags: {source: 'global_handler',filename: event.filename,lineno: event.lineno,colno: event.colno},extra: {userAgent: navigator.userAgent,url: window.location.href,timestamp: Date.now()}})
})// Promise错误处理
window.addEventListener('unhandledrejection', (event) => {webtracing.captureException(event.reason, {tags: {source: 'unhandled_promise'}})
})

5. 性能监控优化

// 关键渲染路径监控
function trackCriticalRendering() {// 监控首屏渲染const observer = new PerformanceObserver((list) => {list.getEntries().forEach((entry) => {if (entry.entryType === 'paint') {webtracing.track('paint_timing', {name: entry.name,startTime: entry.startTime,duration: entry.duration})}})})observer.observe({ entryTypes: ['paint'] })
}// 自定义性能指标
function trackCustomMetrics() {// 页面加载完成时间window.addEventListener('load', () => {const loadTime = performance.now()webtracing.track('page_load_complete', {load_time: loadTime,page_url: window.location.href})})
}

📊 数据格式说明

事件数据结构

const eventData = {eventType: 'click',           // 事件类型eventId: 'unique_id',         // 事件唯一IDtimestamp: 1640995200000,     // 时间戳userId: 'user_123',           // 用户IDsessionId: 'session_456',     // 会话IDpageUrl: '/home',             // 页面URLelement: {                    // 元素信息tagName: 'button',className: 'btn-primary',textContent: '登录',attributes: {}},position: {                   // 位置信息x: 100,y: 200},extra: {}                     // 额外数据
}

性能数据结构

const performanceData = {type: 'performance',timestamp: 1640995200000,metrics: {FCP: 1200,               // 首次内容绘制LCP: 2500,               // 最大内容绘制  FID: 50,                 // 首次输入延迟CLS: 0.1,                // 累积布局偏移TTFB: 300,               // 首字节时间domContentLoaded: 1500,   // DOM解析完成loadComplete: 3000        // 页面加载完成},navigation: {type: 'navigate',         // 导航类型redirectCount: 0          // 重定向次数}
}

错误数据结构

const errorData = {type: 'error',timestamp: 1640995200000,message: 'TypeError: Cannot read property...',stack: 'Error stack trace...',filename: 'app.js',lineno: 100,colno: 25,source: 'javascript',level: 'error',tags: {component: 'UserProfile',environment: 'production'},extra: {userId: 'user_123',action: 'button_click'}
}

🔍 调试和监控

开发调试

// 开启调试模式
webtracing.init({debug: true,  // 控制台输出详细日志// ... 其他配置
})// 手动检查SDK状态
console.log(webtracing.getState())// 查看缓存队列
console.log(webtracing.getEventQueue())// 强制发送缓存数据
webtracing.flush()

生产监控

// 监控SDK自身状态
webtracing.onError((error) => {console.error('WebTracing SDK Error:', error)// 可以上报到其他监控系统
})// 监控数据发送状态
webtracing.onSendSuccess((data) => {console.log('数据发送成功:', data)
})webtracing.onSendFailure((error, data) => {console.error('数据发送失败:', error, data)// 可以实现重试机制
})

🎯 总结

WebTracing SDK 提供了完整的前端监控解决方案:

功能全面 - 涵盖行为、性能、错误、请求等8大监控领域
易于集成 - 支持原生JS、Vue2、Vue3多种使用方式
配置灵活 - 丰富的配置选项满足不同场景需求
性能优化 - 内置缓存机制和采样策略
数据可控 - 提供完整的生命周期钩子和过滤机制

💡 使用建议

  1. 根据项目需求选择合适的功能模块,避免过度监控影响性能
  2. 合理设置采样率和缓存策略,平衡数据完整性和性能开销
  3. 善用过滤配置,避免无关错误和请求干扰分析
  4. 建立完善的用户标识体系,提升数据分析价值
  5. 结合业务场景定制事件追踪,获得更有价值的业务洞察

通过 WebTracing SDK,您可以构建完整的前端监控体系,及时发现和解决问题,持续优化用户体验。


开始您的前端监控之旅! 📊

💡 提示:合理的监控策略不仅能帮助发现问题,更能为产品优化提供数据支撑。建议从核心功能开始,逐步完善监控体系。

http://www.xdnf.cn/news/792199.html

相关文章:

  • 多线程编程中的重要概念
  • CSP模式下如何保证不抖动
  • 查询去重使用 DISTINCT 的性能分析
  • Ubuntu安装Docker命令清单(以20.04为例)
  • 文件批量重命名
  • Tiktok App 登录账号、密码、验证码 XOR 加密算法
  • C++指针加减法详解:深入理解指针运算的本质
  • ES6 Promise 状态机
  • 外贸建站平台推荐
  • shell脚本的常用命令
  • 2024年认证杯SPSSPRO杯数学建模D题(第二阶段)AI绘画带来的挑战解题全过程文档及程序
  • Linux 命令全讲解:从基础操作到高级运维的实战指南
  • 人脸识别技术应用备案系统已开启!
  • Python趣学篇:Pygame重现《黑客帝国》数字雨
  • ArcGIS Pro 3.4 二次开发 - 地图创作 2
  • 车规级BMS芯片国产化!精准电量监测延长电池寿命
  • JS语法笔记
  • PyTorch——非线性激活(5)
  • Linux系统下Google浏览器无法使用中文输入的临时解决方案
  • AIGC学习笔记(9)——AI大模型开发工程师
  • OD 算法题 B卷【代码编辑器】
  • 第十一章 注解
  • AI数据集构建:从爬虫到标注的全流程指南
  • 使用ArcPy生成地图系列
  • 0518蚂蚁暑期实习上机考试题3:小红的字符串构造
  • 如何爬取google应用商店的应用分类呢?
  • Java-redis实现限时在线秒杀功能
  • 【RAG最新总结】检索增强生成最新进展2024-2025
  • 解决FreePBX 17初始配置时网页无响应
  • CCF CSP 第37次(2025.03)(3_模板展开_C++)(哈希表+stringstream)