React对接Application Insights入门资源及实操Demo问询
React 对接 Application Insights 实操实现指南
基础接入配置
首先安装依赖:npm install @microsoft/applicationinsights-react-js @microsoft/applicationinsights-web
新建遥测配置文件src/config/appInsights.ts,示例代码如下:
import { ApplicationInsights } from '@microsoft/applicationinsights-web'; import { ReactPlugin } from '@microsoft/applicationinsights-react-js'; import { createBrowserHistory } from 'history'; // 初始化React插件,用于路由、组件相关数据采集 const reactPlugin = new ReactPlugin(); const browserHistory = createBrowserHistory(); const appInsights = new ApplicationInsights({ config: { // 替换为你在Azure portal中拿到的Application Insights资源连接串 connectionString: "YOUR_CONNECTION_STRING", extensions: [reactPlugin], extensionConfig: { [reactPlugin.identifier]: { history: browserHistory } }, // 开启自动采集XHR/fetch请求数据 enableRequestTrackingTelemetryPlugin: true, // 开启异常自动捕获 enableAutoExceptionTracking: true } }); // 加载初始化 appInsights.loadAppInsights(); export { appInsights, reactPlugin };
在项目入口文件src/index.tsx中导入配置完成初始化:
import React from 'react'; import ReactDOM from 'react-dom/client'; import App from './App'; import { appInsights } from './config/appInsights'; // 全局挂载可方便手动调用,也可按需导入 window.appInsights = appInsights; const root = ReactDOM.createRoot( document.getElementById('root') as HTMLElement ); root.render(<App />);
1. React应用错误追踪
实现分自动全局捕获和手动自定义捕获两类:
- 全局组件错误捕获:搭配React ErrorBoundary实现所有组件渲染阶段错误的自动上报,示例代码如下:
import React, { Component, ErrorInfo, ReactNode } from 'react'; import { appInsights } from '../config/appInsights'; interface Props { children: ReactNode; } interface State { hasError: boolean; } class AppErrorBoundary extends Component<Props, State> { public state: State = { hasError: false }; public static getDerivedStateFromError(_: Error): State { return { hasError: true }; } public componentDidCatch(error: Error, errorInfo: ErrorInfo) { // 上报错误到Application Insights appInsights.trackException({ exception: error, properties: { componentStack: errorInfo.componentStack, errorType: 'ReactComponentRenderError' } }); } public render() { if (this.state.hasError) { return <h1>抱歉,页面出现异常</h1>; } return this.props.children; } } export default AppErrorBoundary;
然后在入口文件中将App组件包裹在ErrorBoundary内即可。
- 手动捕获异常:在异步逻辑、业务代码的try/catch块中可主动调用
trackException上报自定义错误,可附加业务属性方便排查。
2. React应用遥测数据采集
- 自动采集:开启基础配置中的对应开关后,会自动上报页面浏览量、用户会话标识、设备信息、所有接口请求的耗时/状态码/路径、前端加载性能指标等通用数据,无需额外编码。
- 自定义行为埋点:可在用户交互触发时上报自定义事件,示例:
// 上报用户点击登录按钮事件 appInsights.trackEvent({ name: 'UserClickLogin', properties: { loginChannel: 'password', page: 'LoginPage' } });
- 自定义性能指标:可上报业务自定义的性能数据,示例:
// 上报列表组件渲染耗时 appInsights.trackMetric({ name: 'ListComponentRenderTime', average: renderTimeMs, properties: { listType: 'goodsList', itemCount: 20 } });
- 路由切换追踪:配置history参数后会自动采集路由跳转的页面浏览数据,也可手动调用
trackPageView上报自定义页面访问事件。
3. Typescript符号反解
要实现上报的混淆堆栈自动对应到TS源码位置,按以下步骤配置即可:
- 调整TS配置:在
tsconfig.json中将sourceMap属性设置为true,打包时会生成对应的.map源映射文件。 - 上传源映射:将打包生成的所有.map文件上传到你的Application Insights资源对应的符号存储中,生产环境可删除构建产物中的.map文件,避免源文件暴露给终端用户,不影响反解功能。
- 开启反解开关:在Application Insights的配置中开启源映射解析功能,后续上报的错误堆栈会自动匹配源映射,还原出TS源码中的变量名、函数名、行号等信息。
额外建议
可在初始化配置时添加全局自定义属性,区分不同环境、版本的遥测数据:
appInsights.addTelemetryInitializer((envelope) => { envelope.baseData.properties = { ...envelope.baseData.properties, environment: process.env.NODE_ENV, appVersion: '1.0.0' }; });
方便后续在遥测后台筛选不同维度的数据,避免测试环境数据干扰生产统计。
内容的提问来源于stack exchange,提问作者mgru1
相关产品推荐
相关产品推荐

