如何为applicationinsights-clickanalytics-js添加全局自定义属性?
为@microsoft/applicationinsights-clickanalytics-js添加全局自定义属性的解决方案
针对你需要给所有自动捕获和手动触发的点击事件添加租户ID这类自定义属性的需求,这里提供三种可行方案:
方案1:通过ClickAnalyticsPlugin初始化配置注入
初始化插件时,可通过配置项直接添加全局属性,同时利用onBeforeSend钩子统一处理所有事件:
import { ApplicationInsights } from '@microsoft/applicationinsights-web'; import { ClickAnalyticsPlugin } from '@microsoft/applicationinsights-clickanalytics-js'; const appInsights = new ApplicationInsights({ config: { instrumentationKey: '你的仪表板密钥', // 其他基础配置 } }); const clickPlugin = new ClickAnalyticsPlugin(); appInsights.loadAppInsights(); // 添加插件并配置全局属性 appInsights.addPlugin(clickPlugin, { autoCapture: { // 给自动捕获的点击事件预设全局属性 customAttributes: { tenantId: '你的租户ID' } }, // 拦截所有待发送的点击事件,补充属性(覆盖自动捕获的属性,也支持手动事件) onBeforeSend: (item) => { item.properties = { ...item.properties, tenantId: '你的租户ID' }; return true; // 返回true允许事件发送,返回false则丢弃事件 } }); appInsights.trackPageView();
方案2:使用TelemetryProcessor统一拦截所有遥测事件
和标准Application Insights用法一致,给默认客户端添加遥测处理器,可针对性给点击事件(或所有事件)添加属性:
appInsights.loadAppInsights(); appInsights.addPlugin(clickPlugin); // 添加全局遥测处理器 appInsights.defaultClient.addTelemetryProcessor((envelope) => { // 筛选事件类型(点击事件属于EventData类型) if (envelope.data.baseType === 'EventData') { envelope.data.baseData.properties = { ...envelope.data.baseData.properties, tenantId: '你的租户ID' }; } return true; });
方案3:直接设置commonProperties
如果ClickAnalytics插件使用的是默认客户端,直接设置commonProperties即可让所有通过该客户端发送的事件(包括点击事件)带上全局属性:
appInsights.loadAppInsights(); appInsights.addPlugin(clickPlugin); // 全局通用属性,所有默认客户端发送的事件都会包含这些属性 appInsights.defaultClient.commonProperties = { tenantId: '你的租户ID', environment: process.env.SOME_ENV_VARIABLE };
优先级说明
如果同时使用多种方案,属性合并优先级为:TelemetryProcessor > onBeforeSend钩子 > commonProperties > autoCapture.customAttributes
内容的提问来源于stack exchange,提问作者Stefan Starke
相关产品推荐
相关产品推荐

