前端监控与错误上报实战:Sentry接入与sourcemap线上问题定位

前端错误不能只依赖用户反馈,线上异常需要第一时间可感知、可定位。Sentry作为主流错误监控平台,能自动捕获前端异常、性能指标与告警,配合sourcemap把压缩代码还原为源码位置。本文按接入、采样、源码还原、告警四步给出可落地的配置。

Vue3项目接入Sentry

npm install @sentry/vue @sentry/browser

import * as Sentry from "@sentry/vue";
import { createApp } from "vue";

const app = createApp(App);
Sentry.init({
  app,
  dsn: "https://xxxxxxxx@o123.ingest.sentry.io/1234567",
  environment: import.meta.env.PROD ? "production" : "development",
  tracesSampleRate: 0.1,
  release: "frontend@" + __APP_VERSION__
});

dsn在Sentry控制台获取,environment区分预发与生产,release对应git tag,是sourcemap关联的关键。

sourcemap上传与源码定位

压缩产物无法直接读源码,构建后需上传sourcemap:

npx vite build --sourcemap

npx @sentry/cli releases -o your-org -p your-project new frontend@1.0.0
npx @sentry/cli releases files frontend@1.0.0 upload-sourcemaps ./dist/assets

上传后错误堆栈会显示源码路径与行号。生产环境不要公开分发sourcemap文件,避免源码泄露。

误报过滤与错误分组优化

跨域Script error、浏览器插件注入等噪音会干扰告警,需要主动过滤:

Sentry.init({
  ignoreErrors: ["Script error.", "Non-Error promise rejection"],
  denyUrls: [/extensions\//i, /chrome-extension:\/\//i],
  beforeSend(event) {
    if (event.request && event.request.url) {
      delete event.request.headers;
    }
    return event;
  }
});

同名错误Sentry会按堆栈自动聚合,配合指纹设置可把误报归入ignore组。

性能监控与业务指标采集

开启性能监控后可获取LCP、FID、CLS与fetch耗时,同时通过Sentry的Custom Instrumentation上报关键业务点(如登录、下单耗时),用release维度对比版本性能差异。

告警规则与异常响应

配置告警规则:错误率超阈值、新增错误量突增、核心接口耗时超线时,通过企业微信/钉钉/邮件推送。设置每日汇总邮件,覆盖凌晨无人值守时段。

监控与隐私保护的平衡

采集避免过度收集:通过beforeSend去掉Cookie与授权头,用户手机号等敏感字段做脱敏。前端监控的作用是量化问题,错误信息带到堆栈即可,不需要也不应该采集完整请求体。

原创文章,作者:小编,如若转载,请注明出处:https://www.yunthe.com/qian-duan-jian-kong-yu-cuo-wu-shang-bao-shi-zhan-sentry-jie/

(0)
小编小编
上一篇 10小时前
下一篇 10小时前

相关推荐