啟用 Application Insights JavaScript SDK 的架構延伸模組

除了核心 SDK 之外,還有適用於特定架構的外掛程式,例如 React 外掛程式React Native 外掛程式Angular 外掛程式

這些外掛程式提供額外的功能以及與特定架構的整合。

必要條件

這個外掛程式有什麼作用?

適用於 Application Insights JavaScript SDK 的 React 外掛程式能夠:

  • 追蹤路由器歷程記錄
  • 追蹤例外狀況
  • 追蹤元件使用量
  • 搭配 React 內容使用 Application Insights

新增外掛程式

若要新增外掛程式,請遵循本節中的步驟。

Install the package


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 外掛流程繼續設定流程。

組態

本節涵蓋 Application Insights JavaScript SDK 架構延伸模組的組態設定。

追蹤路由器歷程記錄

名稱 類型​ 是必要的嗎? 預設 描述
歷程 object 選擇性 null 追蹤路由器歷程記錄。 如需詳細資訊,請參閱 React 路由器套件文件

若要追蹤路由器歷程記錄,大部分的使用者都可以在 enableAutoRouteTrackingJavaScript SDK 設定中使用 欄位。 此欄位會收集與 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 元件隨即顯示。

收集裝置資訊

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 監視器計量瀏覽器來繪製自訂計量名稱 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 入口網站中。

搭配 React 內容使用 Application Insights

我們提供一般勾點,可讓您自訂個別元件的變更追蹤。 或者,您可以使用 useTrackMetricuseTrackEvent,這是我們為了追蹤元件變更所提供的預先定義接點。

Application Insights 的 React 勾點其設計目的為使用 React Context 作為其所包含的層面。 若要使用 Context,請初始化 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>
    );
};

此 Context 提供者會讓 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 高階元件的功能,而不需將其他元件新增至元件結構。 勾點會採用兩個引數:

  • Application Insights 執行個體,您可從 useAppInsightsContext 勾點取得。
  • 進行追蹤的元件所用的識別碼,例如其名稱。
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;

其運作方式如同高階元件,但會回應勾點生命週期事件,而非元件的生命週期。 如果需要對於特定互動執行,則必須明確將勾點提供給使用者事件。

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 內嵌服務會使用 UA 剖析器來產生您在資料表和經驗中看到的欄位。 因此,Application Insights 使用者無法變更這些欄位。

如果使用者或企業停用瀏覽器設定中的傳送使用者代理程式,則偶爾會遺失或不正確的資料。 UA 剖析器 regex 可能不包含全部裝置資訊。 或者,Application Insights 可能尚未採用最新的更新。

下一步