如何在TypeScript中使用Azure Application Insights?现有方案无效求助
在纯TypeScript项目中使用Azure Application Insights
1. 安装官方SDK
直接安装微软官方的Web SDK,无需依赖Angular等框架:
npm install @microsoft/applicationinsights-web # 或使用yarn yarn add @microsoft/applicationinsights-web
2. 初始化SDK
在项目入口文件(比如index.ts)中完成初始化,配置你的Application Insights仪表密钥:
import { ApplicationInsights } from '@microsoft/applicationinsights-web'; // 初始化实例 const appInsights = new ApplicationInsights({ config: { instrumentationKey: '你的仪表密钥', // 替换为实际的密钥 enableAutoTrackPageVisitTime: true, // 自动跟踪页面访问时长 enableAutoRouteTracking: true, // 单页应用自动路由跟踪(如果适用) disableFetchTracking: false, // 启用Fetch请求跟踪 disableAjaxTracking: false // 启用AJAX请求跟踪 } }); // 启动SDK appInsights.loadAppInsights();
3. 手动跟踪核心数据
除了自动跟踪的内容,你可以手动触发以下常用跟踪操作:
跟踪自定义事件
// 跟踪用户操作事件,比如按钮点击 appInsights.trackEvent({ name: 'button_click', properties: { buttonId: 'submit_form', page: 'checkout' }, // 自定义属性 measurements: { clickDuration: 120 } // 自定义度量值 });
跟踪异常
try { // 可能抛出错误的代码 throw new Error('自定义错误信息'); } catch (error) { appInsights.trackException({ exception: error as Error, properties: { context: '表单提交' } }); }
跟踪页面视图
如果是手动路由切换的场景,可手动上报页面视图:
appInsights.trackPageView({ name: '用户详情页', uri: '/user/123', properties: { userId: '123' } });
4. 设置自定义上下文
设置用户标识
// 当用户登录后,设置唯一用户ID appInsights.setAuthenticatedUserContext('user_12345', undefined, true); // 登出时清除 appInsights.clearAuthenticatedUserContext();
添加全局自定义属性
// 所有后续跟踪事件都会带上这些属性 appInsights.addTelemetryInitializer((envelope) => { envelope.data.properties = { ...envelope.data.properties, appVersion: '1.0.0', environment: 'production' }; });
5. 常见问题排查
- 确认
instrumentationKey是否正确,可在Azure Portal的Application Insights资源中查看 - 检查浏览器控制台是否有SDK相关报错,比如网络请求被拦截
- 若使用打包工具(如Webpack),确保SDK被正确打包,未被tree-shaking移除
- 查看Azure Portal的实时指标流,验证数据是否正常上报
内容的提问来源于stack exchange,提问作者Akhil pramod
相关产品推荐
相关产品推荐

