共用方式為


將遙測資料新增至 Bot

適用於: SDK v4

遙測記錄可讓 Bot 應用程式將事件數據傳送至 Application Insights遙測服務。 遙測會藉由顯示最常使用哪些功能、偵測垃圾行為,以及提供可用性、效能和使用方式的可見度,來提供 Bot 的深入解析。

本文說明如何使用Application Insights 在 Bot 中實作遙測。 此文章涵蓋:

  • 在 Bot 中連接遙測並連線到 Application Insights 所需的程式代碼。
  • 如何在 Bot 的 對話框中啟用遙測。
  • 如何讓遙測從其他服務擷取使用量數據,例如 Azure AI 服務。
  • 如何在 Application Insights 中將遙測數據可視化。

重要

對於可能收集遙測中個人標識資訊 (PII) 的區域 Bot,您的 Application Insights 資源和 Azure Bot 資源應該位於與 Bot 相同的區域中。 如果資源位於不同的區域,PII 可能會離開 Bot 的地理區域。

必要條件

注意

Application Insights 範例程式代碼建置在 CoreBot 範例程式代碼之上。 本文將逐步引導您修改 CoreBot 範例程式代碼以納入遙測。 如果您在 Visual Studio 中跟著進行,當您完成時,將會有 Application Insights 範例程式代碼。

在您的 Bot 中啟用遙測

本文從 CoreBot 範例應用程式 開始,並新增將遙測整合到任何 Bot 所需的程式代碼。 這可讓 Application Insights 開始追蹤要求。

重要

如果您尚未設定 Application Insights 帳戶並建立 Application Insights 密鑰,請先執行此動作,再繼續進行。

  1. Visual Studio 中開啟 CoreBot 範例應用程式

  2. 新增 Microsoft.Bot.Builder.Integration.ApplicationInsights.Core NuGet 套件。 如需使用 NuGet 的詳細資訊,請參閱 在 Visual Studio 中安裝和管理套件:

  3. 在中包含 Startup.cs下列 語句:

    using Microsoft.ApplicationInsights.Extensibility;
    using Microsoft.Bot.Builder.ApplicationInsights;
    using Microsoft.Bot.Builder.Integration.ApplicationInsights.Core;
    using Microsoft.Bot.Builder.Integration.AspNet.Core;
    

    提示

    如果您遵循更新 CoreBot 範例程式代碼,您會發現 CoreBot 範例中已經有 using 語句 Microsoft.Bot.Builder.Integration.AspNet.Core

  4. 在的方法Startup.cs中包含ConfigureServices()下列程序代碼。 這可讓遙測服務透過 相依性插入 (DI)提供給 Bot:

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        ...
            // Create the Bot Framework Adapter with error handling enabled.
            services.AddSingleton<IBotFrameworkHttpAdapter, AdapterWithErrorHandler>();
    
            // Add Application Insights services into service collection
            services.AddApplicationInsightsTelemetry();
    
            // Create the telemetry client.
            services.AddSingleton<IBotTelemetryClient, BotTelemetryClient>();
    
            // Add telemetry initializer that will set the correlation context for all telemetry items.
            services.AddSingleton<ITelemetryInitializer, OperationCorrelationTelemetryInitializer>();
    
            // Add telemetry initializer that sets the user ID and session ID (in addition to other bot-specific properties such as activity ID)
            services.AddSingleton<ITelemetryInitializer, TelemetryBotIdInitializer>();
    
            // Create the telemetry middleware to initialize telemetry gathering
            services.AddSingleton<TelemetryInitializerMiddleware>();
    
            // Create the telemetry middleware (used by the telemetry initializer) to track conversation events
            services.AddSingleton<TelemetryLoggerMiddleware>();
        ...
    }
    

    提示

    如果您遵循更新 CoreBot 範例程式代碼,您會發現 services.AddSingleton<IBotFrameworkHttpAdapter, AdapterWithErrorHandler>(); 已經存在。

  5. 指示配接器使用已新增至 方法的 ConfigureServices() 中間件程序代碼。 您可以在 中 AdapterWithErrorHandler.cs ,使用建構函式參數列表中的 TelemetryInitializerMiddleware telemetryInitializerMiddleware 和 Use(telemetryInitializerMiddleware); 建構函式中的 語句,如下所示:

        public AdapterWithErrorHandler(IConfiguration configuration, ILogger<BotFrameworkHttpAdapter> logger, TelemetryInitializerMiddleware telemetryInitializerMiddleware, ConversationState conversationState = null)
            : base(configuration, logger)
    {
        ...
        Use(telemetryInitializerMiddleware);
    }
    
  6. 您也必須將 新增 Microsoft.Bot.Builder.Integration.ApplicationInsights.Core 至 中的 AdapterWithErrorHandler.csusing語句清單。

  7. 在您的檔案中 appsettings.json 新增 Application Insights 檢測密鑰。 檔案 appsettings.json 包含 Bot 在執行時所使用之外部服務的元數據。 例如,Cosmos DB、Application Insights 和 Azure AI 服務連線和元數據會儲存在那裡。 檔案 appsettings.json 的新增必須以此格式:

    {
        "MicrosoftAppId": "",
        "MicrosoftAppPassword": "",
        "ApplicationInsights": {
            "InstrumentationKey": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
        }
    }
    

    注意

    如需取得 Application Insights 檢測金鑰的詳細數據,請參閱 Application Insights 密鑰一文

此時,已完成使用Application Insights啟用遙測的初步工作。 您可以使用模擬器在本機執行 Bot,然後進入 Application Insights 以查看記錄的內容,例如響應時間、整體應用程式健康情況,以及一般執行資訊。

在 Bot 對話框中啟用遙測

將新對話框新增至任何 ComponentDialog 時,它會繼承其父對話方塊的 Microsoft.Bot.Builder.IBotTelemetryClient。 例如,在 CoreBot 範例應用程式中,所有對話框都會新增至 MainDialog,也就是 ComponentDialog。 一旦您將 TelemetryClient 屬性設定為 MainDialog,新增至該屬性的所有對話框都會自動從中繼承 telemetryClient,因此在新增對話框時不需要明確設定。

請遵循下列步驟來更新 CoreBot 範例:

  1. 在 中 MainDialog.cs,更新建構函式的參數清單以包含 IBotTelemetryClient 參數,然後將MainDialog的 TelemetryClient 屬性設定為該值,如下列代碼段所示:

    public MainDialog(IConfiguration configuration, ILogger<MainDialog> logger, IBotTelemetryClient telemetryClient)
        : base(nameof(MainDialog))
    {
        // Set the telemetry client for this and all child dialogs.
        this.TelemetryClient = telemetryClient;
        ...
    }
    

提示

如果您遵循並更新 CoreBot 範例程式代碼,如果您遇到任何問題,可以參考 Application Insights 範例程式代碼

遙測現在已新增至 Bot 對話框。 如果您現在執行 Bot,您應該會看到在 Application Insights 中記錄的專案;不過,如果您有任何整合技術,例如 Azure AI 服務,您也必須將 新增 TelemetryClient 至該程序代碼。

啟用或停用活動事件和個人信息記錄

啟用或停用活動記錄

根據預設,當您 TelemetryInitializerMiddleware 的 Bot 傳送/接收活動時,會使用 TelemetryLoggerMiddleware 來記錄遙測。 活動記錄會在 Application Insights 資源中建立自定義事件記錄。 如果您想要的話,您可以在 Startup.cs 中註冊活動事件時,將 設定logActivityTelemetry為 false TelemetryInitializerMiddleware 來停用活動事件記錄。

public void ConfigureServices(IServiceCollection services)
{
    ...
    // Add the telemetry initializer middleware
    services.AddSingleton<TelemetryInitializerMiddleware>(sp =>
            {
                var loggerMiddleware = sp.GetService<TelemetryLoggerMiddleware>();
                return new TelemetryInitializerMiddleware(loggerMiddleware, logActivityTelemetry: false);
            });
    ...
}

啟用或停用個人信息記錄

根據預設,如果啟用活動記錄,傳入/傳出活動的某些屬性會從記錄中排除,因為它們可能會包含個人資訊,例如使用者名稱和活動文字。 註冊 時TelemetryLoggerMiddleware,您可以選擇在記錄中包含這些屬性,方法是對 Startup.cs 進行下列變更

public void ConfigureServices(IServiceCollection services)
{
    ...
    // Add the telemetry initializer middleware
    services.AddSingleton<TelemetryLoggerMiddleware>(sp =>
            {
                var telemetryClient = sp.GetService<IBotTelemetryClient>();
                return new TelemetryLoggerMiddleware(telemetryClient, logPersonalInformation: true);
            });
    ...
}

接下來,我們將瞭解需要包含哪些專案,才能將遙測功能新增至對話。 這可讓您取得其他資訊,例如執行哪些對話框,以及每個對話框的相關統計數據。

啟用遙測以從 LUIS 和 QnA Maker 等其他服務擷取使用量數據

注意

Azure AI QnA Maker 將於 2025 年 3 月 31 日淘汰。 從 2022 年 10 月起,您將無法建立新的 QnA Maker 資源或知識庫。 較新版的問題和解答功能現在隨附於 Azure AI 語言。

自定義問題解答是 Azure AI 語言的一項功能,是 QnA Maker 服務的更新版本。 如需 Bot Framework SDK 中問答支援的詳細資訊,請參閱 自然語言理解

注意

Language Understanding (LUIS) 將於 2025 年 10 月 1 日淘汰。 從 2023 年 4 月 1 日起,您將無法建立新的 LUIS 資源。 新版的語言理解現在已提供作為 Azure AI 語言的一部分。

對話式語言理解(CLU)是 Azure AI 語言的一項功能,是 LUIS 的更新版本。 如需 Bot Framework SDK 中語言理解支援的詳細資訊,請參閱 自然語言理解

接下來,我們將在 LUIS 服務中實作遙測功能。 LUIS 服務有內建的遙測記錄可供使用,因此您不需要這麼做,即可開始從 LUIS 取得遙測數據。 如果您有興趣在已啟用 QnA Maker 的 Bot 中啟用遙測,請參閱 將遙測新增至 QnA Maker Bot

  1. 在 中的FlightBookingRecognizerFlightBookingRecognizer.csIBotTelemetryClient telemetryClient構函式中,需要 參數:

    public FlightBookingRecognizer(IConfiguration configuration, IBotTelemetryClient telemetryClient)
    
  2. 接下來,當您在建構函式中FlightBookingRecognizer建立 LuisRecognizer 時,請啟用 telemetryClient 。 新增 為新的 LuisRecognizerOption 來執行此動作telemetryClient

    if (luisIsConfigured)
    {
        var luisApplication = new LuisApplication(
            configuration["LuisAppId"],
            configuration["LuisAPIKey"],
            "https://" + configuration["LuisAPIHostName"]);
    
        // Set the recognizer options depending on which endpoint version you want to use.
        var recognizerOptions = new LuisRecognizerOptionsV3(luisApplication)
        {
            TelemetryClient = telemetryClient,
        };
        _recognizer = new LuisRecognizer(recognizerOptions);
    }
    

也就是說,您應該有一個功能 Bot,將遙測數據記錄到 Application Insights 中。 您可以使用 Bot Framework 模擬器 在本機執行 Bot。 您不應該在 Bot 的行為中看到任何變更,但它會將資訊記錄到 Application Insights。 藉由傳送多個訊息與 Bot 互動,在下一節中,我們將檢閱 Application Insights 中的遙測結果。

如需測試和偵錯 Bot 的相關信息,請參閱下列文章:

在 Application Insights 中可視化遙測數據

Application Insights 會監視 Bot 應用程式的可用性、效能和使用方式,無論是裝載於雲端還是內部部署。 它會使用 Azure 監視器中強大的資料分析平臺,讓您深入瞭解應用程式的作業,並診斷錯誤,而不需要等待使用者回報錯誤。 有幾種方式可查看ApplicationInsights所收集的遙測數據,其中兩種主要方式是透過查詢和儀錶板。

使用 Kusto 查詢在 Application Insights 中查詢遙測數據

使用本節作為起點,瞭解如何在 Application Insights 中使用記錄查詢。 它會示範兩個有用的查詢,並提供其他文件的連結,並提供其他資訊。

查詢您的數據

  1. 移至 Azure 入口網站

  2. 若要移至 Application Insights 頁面,請選取 [監視],然後選取 [應用程式],並在該處找到它。

  3. 一旦進入Application Insights,請選取 [記錄] [分析]。

    Bot [Application Insights] 頁面上 [記錄][分析] 按鈕的螢幕快照。

  4. 這會顯示 [查詢] 視窗。 輸入下列查詢,然後選取 [ 執行]:

    customEvents
    | where name=="WaterfallStart"
    | extend DialogId = customDimensions['DialogId']
    | extend InstanceId = tostring(customDimensions['InstanceId'])
    | join kind=leftouter (customEvents | where name=="WaterfallComplete" | extend InstanceId = tostring(customDimensions['InstanceId'])) on InstanceId
    | summarize starts=countif(name=='WaterfallStart'), completes=countif(name1=='WaterfallComplete') by bin(timestamp, 1d), tostring(DialogId)
    | project Percentage=max_of(0.0, completes * 1.0 / starts), timestamp, tostring(DialogId)
    | render timechart
    
  5. 這會傳回執行至完成之瀑布式對話的百分比。

    App Insights 查詢的範例輸出。

提示

您可以選取 [記錄] 刀鋒視窗右上方的按鈕,將任何查詢釘選到 Application Insights 儀錶板。 只要選取您想要釘選的儀錶板,下一次瀏覽該儀錶板時即可使用。

Application Insights 儀錶板

當您在 Azure 中建立 Application Insights 資源時,系統會自動建立新的儀錶板並與其建立關聯。 您可以選取 [Application Insights] 刀鋒視窗頂端的按鈕,標示 為 [應用程式儀錶板],以查看該儀錶板

Bot [Application Insights] 頁面上 [應用程式儀錶板] 按鈕的螢幕快照。

或者,若要檢視數據,請移至 Azure 入口網站。 選取 左側的 [儀錶板 ],然後從下拉式清單中選取您想要的儀錶板。

在那裡,您會看到 Bot 效能的一些預設資訊,以及您已釘選到儀錶板的任何其他查詢。

其他資訊