为 Application Insights JavaScript SDK 启用框架扩展

除了核心 SDK 之外,还有适用于特定框架的插件,例如 React 插件React Native 插件Angular 插件

这些插件提供额外的功能并与特定框架集成。

先决条件

此插件能够实现什么?

使用 Application Insights JavaScript SDK 的 React 插件可以:

  • 跟踪路由器历史记录
  • 跟踪异常
  • 跟踪组件使用情况
  • 将 Application Insights 与 React Context 配合使用

添加插件

若要添加插件,请执行本部分中的步骤。

安装包


npm install @microsoft/applicationinsights-react-js

将扩展添加到代码

注意

对检测密钥引入的支持将于 2025 年 3 月 31 日结束。 检测密钥引入功能将会继续工作,但我们将不再为该功能提供更新或支持。 转换为连接字符串,以利用新功能

初始化与 Application Insights 的连接:

import React from 'react';
import { ApplicationInsights } from '@microsoft/applicationinsights-web';
import { ReactPlugin } from '@microsoft/applicationinsights-react-js';
import { createBrowserHistory } from "history";
const browserHistory = createBrowserHistory({ basename: '' });
var reactPlugin = new ReactPlugin();
// *** Add the Click Analytics plug-in. ***
/* var clickPluginInstance = new ClickAnalyticsPlugin();
   var clickPluginConfig = {
     autoCapture: true
}; */
var appInsights = new ApplicationInsights({
    config: {
        connectionString: 'YOUR_CONNECTION_STRING_GOES_HERE',
        // *** If you're adding the Click Analytics plug-in, delete the next line. ***
        extensions: [reactPlugin],
     // *** Add the Click Analytics plug-in. ***
     // extensions: [reactPlugin, clickPluginInstance],
        extensionConfig: {
          [reactPlugin.identifier]: { history: browserHistory }
       // *** Add the Click Analytics plug-in. ***
       // [clickPluginInstance.identifier]: clickPluginConfig
        }
    }
});
appInsights.loadAppInsights();

(可选)添加 Click Analytics 插件

如果要添加 Click Analytics 插件,请执行以下操作:

  1. 取消对 Click Analytics 的行的注释。

  2. 执行下列操作之一,具体取决于要添加的插件:

    • 对于 React,请删除 extensions: [reactPlugin],
    • 对于 React Native,请删除 extensions: [RNPlugin]
    • 对于 Angular,请删除 extensions: [angularPlugin],
  3. 请参阅使用 Click Analytics 插件以继续执行安装过程。

Configuration

本部分包含适用于 Application Insights JavaScript SDK 的框架扩展的配置设置。

跟踪路由器历史记录

名称 类型 必需? 默认 描述
history 对象 (object) 可选 Null 跟踪路由器历史记录。 有关详细信息,请参阅 React 路由器包文档

若要跟踪路由器历史记录,大多数用户可以使用 JavaScript SDK 配置中的 enableAutoRouteTracking 字段。 此字段收集与 history对象相同的页面视图数据。

使用不更新浏览器 URL 的路由器实现时,请使用 history 对象,这是配置侦听的内容。 不应同时启用 enableAutoRouteTracking 字段和 history 对象,因为会收到多个页面视图事件。

以下代码示例展示了如何启用 enableAutoRouteTracking 字段。

var reactPlugin = new ReactPlugin();
var appInsights = new ApplicationInsights({
    config: {
        connectionString: 'YOUR_CONNECTION_STRING_GOES_HERE',
        enableAutoRouteTracking: true,
        extensions: [reactPlugin]
    }
});
appInsights.loadAppInsights();

跟踪异常

React 错误边界提供了一种方法,可以在 React 应用程序中发生未捕获的异常时对其进行妥善处理。 当发生此类异常时,有可能需要记录该异常。 Application Insights 的 React 插件提供了一个错误边界组件,该组件将在发生异常时自动记录异常。

import React from "react";
import { reactPlugin } from "./AppInsights";
import { AppInsightsErrorBoundary } from "@microsoft/applicationinsights-react-js";

const App = () => {
    return (
        <AppInsightsErrorBoundary onError={() => <h1>I believe something went wrong</h1>} appInsights={reactPlugin}>
            /* app here */
        </AppInsightsErrorBoundary>
    );
};

需要向 AppInsightsErrorBoundary 传递两个属性。 这两个属性是为应用程序创建的 ReactPlugin 实例,以及发生异常时要呈现的组件。 发生未经处理的异常时,使用提供给错误边界的信息调用 trackException,并且 onError 组件将显示。

收集设备信息

设备信息(包括浏览器、OS、版本和语言)已由 Application Insights Web 程序包收集。

配置(其他)

跟踪组件使用情况

React 插件特有的一项功能是你可以检测特定组件并单独跟踪它们。

要检测 React 组件的使用情况跟踪功能,请应用 withAITracking 高阶组件函数。 要为组件启用 Application Insights,请用 withAITracking 包装组件:

import React from 'react';
import { withAITracking } from '@microsoft/applicationinsights-react-js';
import { reactPlugin, appInsights } from './AppInsights';

// To instrument various React components usage tracking, apply the `withAITracking` higher-order
// component function.

class MyComponent extends React.Component {
    ...
}

// withAITracking takes 4 parameters (reactPlugin, Component, ComponentName, className). 
// The first two are required and the other two are optional.

export default withAITracking(reactPlugin, MyComponent);

它测量从 ComponentDidMount 事件到 ComponentWillUnmount 事件的时间。 为使结果更准确,它会使用 React Component Engaged Time = ComponentWillUnmount timestamp - ComponentDidMount timestamp - idle time 减去用户空闲时间。

浏览数据

使用 Azure Monitor 指标资源管理器绘制自定义指标名称 React Component Engaged Time (seconds) 的图表,并按 Component Name 对此自定义指标进行拆分

Screenshot that shows a chart that displays the custom metric React Component Engaged Time (seconds) split by Component Name

还可运行自定义查询来划分 Application Insights 数据,从而根据需求生成报表和可视化效果。 下面是自定义查询的示例。 继续操作并将其直接粘贴到查询编辑器中以进行测试。

customMetrics
| where name contains "React Component Engaged Time (seconds)"
| summarize avg(value), count() by tostring(customDimensions["Component Name"])

新的自定义指标最多可能需要 10 分钟才能显示在 Azure 门户中。

将 Application Insights 与 React Context 配合使用

我们提供常规挂钩,使你能够自定义各个组件的变更跟踪。 或者,可以使用 useTrackMetricuseTrackEvent,它们是我们提供的预定义联系方式,用于跟踪组件变更。

Application Insights React 挂钩旨在使用 React 上下文作为它的一个包含方面。 若要使用上下文,请初始化 Application Insights,然后导入上下文对象:

import React from "react";
import { AppInsightsContext } from "@microsoft/applicationinsights-react-js";
import { reactPlugin } from "./AppInsights";

const App = () => {
    return (
        <AppInsightsContext.Provider value={reactPlugin}>
            /* your application here */
        </AppInsightsContext.Provider>
    );
};

此上下文提供程序使 Application Insights 在它的所有子组件内可作为 useContext 挂钩使用:

import React from "react";
import { useAppInsightsContext } from "@microsoft/applicationinsights-react-js";

const MyComponent = () => {
    const appInsights = useAppInsightsContext();
    const metricData = {
        average: engagementTime,
        name: "React Component Engaged Time (seconds)",
        sampleCount: 1
      };
    const additionalProperties = { "Component Name": 'MyComponent' };
    appInsights.trackMetric(metricData, additionalProperties);
    
    return (
        <h1>My Component</h1>
    );
}
export default MyComponent;
useTrackMetric

useTrackMetric 挂钩复制 withAITracking 高阶组件的功能,而不会向组件结构中添加其他组件。 Hook 接受两个参数:

  • Application Insights 实例,可以从 useAppInsightsContext Hook 获取。
  • 用于跟踪的组件的标识符,例如其名称。
import React from "react";
import { useAppInsightsContext, useTrackMetric } from "@microsoft/applicationinsights-react-js";

const MyComponent = () => {
    const appInsights = useAppInsightsContext();
    const trackComponent = useTrackMetric(appInsights, "MyComponent");
    
    return (
        <h1 onHover={trackComponent} onClick={trackComponent}>My Component</h1>
    );
}
export default MyComponent;

该组件像高阶组件一样运行,但它响应挂钩生命周期事件而不是组件生命周期。 如果需要在特定交互上运行,则需要向用户事件显式提供 Hook。

useTrackEvent

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

  • Application Insights 实例,可以从 useAppInsightsContext 挂钩获取。
  • 事件的名称。
  • 事件数据对象,该对象封装了必须跟踪的更改。
  • skipFirstRun(可选)标志,用于在初始化时跳过 trackEvent 调用。 默认值设置为 true 以更接近非挂钩版本的工作方式模拟。 使用 useEffect 挂钩,每次值更新时都会触发该效果,包括值的初始设置。 因此,跟踪会过早启动,导致可能跟踪不需要的事件。
import React, { useState, useEffect } from "react";
import { useAppInsightsContext, useTrackEvent } from "@microsoft/applicationinsights-react-js";

const MyComponent = () => {
    const appInsights = useAppInsightsContext();
    const [cart, setCart] = useState([]);
    const trackCheckout = useTrackEvent(appInsights, "Checkout", cart);
    const trackCartUpdate = useTrackEvent(appInsights, "Cart Updated", cart);
    useEffect(() => {
        trackCartUpdate({ cartCount: cart.length });
    }, [cart]);
    
    const performCheckout = () => {
        trackCheckout();
        // submit data
    };
    
    return (
        <div>
            <ul>
                <li>Product 1 <button onClick={() => setCart([...cart, "Product 1"])}>Add to Cart</button></li>
                <li>Product 2 <button onClick={() => setCart([...cart, "Product 2"])}>Add to Cart</button></li>
                <li>Product 3 <button onClick={() => setCart([...cart, "Product 3"])}>Add to Cart</button></li>
                <li>Product 4 <button onClick={() => setCart([...cart, "Product 4"])}>Add to Cart</button></li>
            </ul>
            <button onClick={performCheckout}>Checkout</button>
        </div>
    );
}

export default MyComponent;

使用该挂钩时,可以向其提供数据有效负载,以便在将事件存储到 Application Insights 时向该事件添加其他数据。

示例应用

常见问题

本部分提供常见问题的解答。

Application Insights 如何生成设备信息(例如浏览器、操作系统、语言和型号)?

浏览器在请求的 HTTP 标头中传递用户代理字符串。 Application Insights 引入服务使用用户代理分析程序生成你在数据表和体验中看到的字段。 因此,Application Insights 用户无法更改这些字段。

如果用户或企业禁止在浏览器设置中发送用户代理,则此数据偶尔可能会缺失或不准确。 用户代理分析程序正则表达式可能未包含所有设备信息。 或者 Application Insights 可能未采用最新更新。

后续步骤