You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何统计用户仪表盘停留时长?Sentry startTransaction替代方案咨询

解决Sentry统计仪表盘停留时长的替代方案

针对你遇到的Sentry startTransaction 废弃后无法统计页面停留时长的问题,可以用以下两种方案实现需求:

方案一:手动创建自定义事务并控制生命周期

Sentry新版本仍支持手动创建事务,只需调整API用法,通过手动控制事务的启动和结束时机来统计停留时长:

// 用户进入仪表盘时启动事务
const dashboardTransaction = Sentry.startTransaction({
  name: 'Dashboard Stay Duration',
  op: 'page.view',
});

// 监听页面卸载事件,结束事务
window.addEventListener('beforeunload', () => {
  dashboardTransaction.finish();
});

// 单页应用场景下,监听路由离开仪表盘的事件
router.beforeEach((to, from) => {
  if (from.name === 'Dashboard') {
    dashboardTransaction.finish();
  }
});

方案二:结合现有事务添加自定义时长指标

利用Sentry自动捕获的页面事务,通过添加自定义测量值记录停留时长:

// 记录用户进入仪表盘的时间
const enterTime = Date.now();

// 离开时计算时长并关联到当前事务
window.addEventListener('beforeunload', () => {
  const stayDuration = Date.now() - enterTime;
  const activeTransaction = Sentry.getCurrentHub().getScope().getTransaction();
  if (activeTransaction) {
    activeTransaction.setMeasurement('dashboard.stay_duration', stayDuration, 'millisecond');
    activeTransaction.finish();
  }
});

注意事项

  • 确保使用v7及以上版本的Sentry SDK,上述API均兼容
  • 单页应用需做好路由切换的监听,避免事务未正确结束
  • 可给事务添加自定义标签(如user_id),方便后续筛选分析

内容的提问来源于stack exchange,提问作者David Ly

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 18:34:51