首页 > 解决方案 > Application Insights React 插件

问题描述

我一直在玩 React 和 Azure App Insights。

const appInsights = useAppInsightsContext();

仅对于事件和指标,似乎有两种做事方式。为什么是这样?为什么它只针对这 2 件事,即对于 PageViews 或异常,您只能使用第二种方式(appInsights.trackPageView,appInsights.trackException)

//第一种方式

    const trackEventHook = useTrackEvent(
    appInsights,
    "AppInsightsPage Track Event Hook",
    { extraData: "some extra data important to this" },
    false
  );

trackEventHook({ extraData: "function call extra data" });

//第二种方式

appInsights.trackEvent({ name: "AppInsightsPage Custom Event" }, undefined);

标签: reactjsazure-application-insightsapplicationinsights-react-js

解决方案


在使用 Application Insight 时,我们在代码中使用 TrackEvent 来计算各种事件。用户选择特定功能的频率,或者他们做出特定选择的频率。

例如,我们想了解网站上的用户行为,并且我们想了解特定操作,例如单击“添加到购物车”按钮。

这可以通过两种方式完成:

使用 trackEvent 方法

appInsights.trackEvent({ name: 'EventName', properties: { anyProperty } })

我们使用我们正在导出的 appInsights 对象,并将一些数据传递给 trackEvent、我们正在跟踪的事件的名称以及我们想要包含在事件中的任何自定义属性。

使用 React 插件 useTrackEvent Hook

const trackEventName = useTrackEvent(appInsights, "Event Name", condition);

useTrackEventHook 用于跟踪应用程序可能需要跟踪的任何自定义事件,例如按钮单击或其他 API 调用。它需要四个参数:

  1. Application Insights 实例(可以从 useAppInsightsContext Hook 中获取)。
  2. 事件的名称。
  3. 封装必须跟踪的更改的事件数据对象。
  4. skipFirstRun(可选)标志跳过 trackEvent 初始化调用。默认值设置为 true

trackExpection用于记录与 API 相关的异常,我们不知道它们何时会发生,对于trackPageView,默认情况下会在每个屏幕或页面加载时发送页面视图遥测。因此,在trackExpectiontrackPageView中,我们没有任何数据对象来跟踪任何更改。这就是为什么我们不对这两个使用useTrackEvent钩子的原因。

有关详细信息,请查看以下 Microsoft 文档:


推荐阅读