你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

将遥测功能添加到机器人

适用于:SDK v4

遥测日志记录使机器人应用程序能够将事件数据发送到 Application Insights 等遥测服务。 遥测通过显示最常使用的功能、检测不需要的行为以及提供可用性、性能和使用情况的可见性,提供对机器人的见解。

本文介绍如何使用 Application Insights 在机器人中实现遥测。 本文介绍:

  • 将遥测连接到机器人中以及连接到 Application Insights 所需的代码。
  • 如何在 机器人的对话中启用遥测。
  • 如何启用遥测来捕获其他服务(如 Azure AI 服务)的使用情况数据。
  • 如何在 Application Insights 中可视化遥测数据。

重要

对于可能在遥测中收集个人身份信息 (PII) 的区域机器人,Application Insights 资源和 Azure 机器人资源应与机器人位于同一区域。 如果资源位于不同的区域,则 PII 可能会离开机器人的地理区域。

先决条件

注意

Application Insights 示例代码基于 CoreBot 示例代码。 本文详细介绍如何通过修改 CoreBot 示例代码来纳入遥测功能。 如果在 Visual Studio 中继续执行操作,则完成后,你将拥有 Application Insights 示例代码。

在机器人中启用遥测

本文将从 CoreBot 示例应用着手,添加将遥测集成到任何机器人中所需的代码。 这样 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.csConfigureServices() 方法中。 这样就可以通过依赖项注入 (DI) 让机器人使用遥测服务:

    // 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 文件包含有关机器人在运行时要使用的外部服务的元数据。 例如,Cosmos DB、Application Insights 和 Azure AI 服务连接和元数据存储在其中。 添加到 appsettings.json 文件的内容必须采用以下格式:

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

    注意

    若要详细了解如何获取 Application Insights 检测密钥,可参阅 Application Insights 密钥一文。

此时,已完成使用 Application Insights 启用遥测的初步工作。 可以使用模拟器在本地运行机器人,然后进入 Application Insights 查看记录的内容,例如响应时间、应用总体运行状况和常规运行信息。

在机器人的对话框中启用遥测

将新对话添加到任何 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 示例代码

遥测现已添加到机器人对话。 如果现在运行机器人,应会看到在 Application Insights 中记录内容;但是,如果你有任何集成技术(例如 Azure AI 服务),则还需要将 添加到 TelemetryClient 该代码。

启用或禁用活动事件和个人信息日志记录

启用或禁用活动日志记录

默认情况下,当机器人发送/接收活动时,TelemetryInitializerMiddleware 将使用 TelemetryLoggerMiddleware 来记录遥测数据。 活动日志记录在 Application Insights 资源中创建自定义事件日志。 如果需要,可以禁用活动事件日志记录,方法是在 Startup.cs 中注册 TelemetryInitializerMiddleware 时,将其上的 logActivityTelemetry 设置为 false。

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 月 1 日开始,将无法创建新的 QnA Maker 资源或知识库。 问答功能的较新版本现已作为 Azure AI 语言的一部分提供。

自定义问答是 Azure AI 语言的一项功能,是 QnA Maker 服务的更新版本。 有关 Bot Framework SDK 中的问答支持的详细信息,请参阅 自然语言理解

注意

语言理解 (LUIS) 将于 2025 年 10 月 1 日停用。 从 2023 年 4 月 1 日开始,将无法创建新的 LUIS 资源。 新版本的语言理解现已作为 Azure AI 语言的一部分提供。

对话语言理解 (CLU) (Azure AI 语言的一项功能)是 LUIS 的更新版本。 有关 Bot Framework SDK 中的语言理解支持的详细信息,请参阅 自然语言理解

接下来,我们将在 LUIS 服务中实现遥测功能。 LUIS 服务提供内置的遥测日志记录功能,因此无需执行任何操作即可开始从 LUIS 获取遥测数据。 如果有兴趣在已启用 QnA Maker 的机器人中启用遥测,请参阅 将遥测添加到 QnA Maker 机器人

  1. FlightBookingRecognizer.csFlightBookingRecognizer 构造函数中, IBotTelemetryClient telemetryClient 参数是必需的:

    public FlightBookingRecognizer(IConfiguration configuration, IBotTelemetryClient telemetryClient)
    
  2. 接下来,在 telemetryClient 构造函数中创建 LuisRecognizerFlightBookingRecognizer 时启用 。 为此,将 telemetryClient 添加为新的 LuisRecognizerOption

    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);
    }
    

操作完毕。你现在应该有一个正常运行的机器人,可以将遥测数据记录到 Application Insights 中。 可以使用 Bot Framework Emulator 在本地运行机器人。 你应该看不到机器人的行为有任何变化,只会看到它将信息记录到 Application Insights 中。 通过发送多个消息与机器人交互,我们将在下一部分中查看 Application Insights 中的遥测结果。

若要了解如何测试和调试机器人,可参阅以下文章:

在 Application Insights 中可视化遥测数据

无论机器人应用程序托管在云中还是本地,Application Insights 都可以监视其可用性、性能和使用情况。 它使用 Azure Monitor 中功能强大的数据分析平台,提供对应用程序操作的深入见解,并诊断错误,而无需等待用户报告错误。 可以通过许多方式查看 Application Insights 收集的遥测数据,其中的两种主要方式是使用查询和仪表板。

使用 Kusto 查询在 Application Insights 中查询遥测数据

从此部分着手,了解如何在 Application Insights 中使用日志查询。 此部分演示了两个有用的查询,并提供了其他文档的链接和其他信息。

查询数据的步骤

  1. 转到 Azure 门户

  2. 若要转到 Application Insights 页,请选择“ 监视”,然后选择 “应用程序”,并在其中找到它。

  3. 进入 Application Insights 后,选择“ 日志” (Analytics)

    机器人 Application Insights 页上的“日志 (Analytics) ”按钮的屏幕截图。

  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 边栏选项卡顶部的按钮即可看到标记为“应用程序仪表板”的该仪表板。

机器人的 Application Insights 页上的“应用程序仪表板”按钮的屏幕截图。

另外,若要查看数据,可转到 Azure 门户。 选择左侧的“仪表板”,然后从下拉列表中选择所需的仪表板。

在其中可以看到一些有关机器人性能的默认信息,以及已固定到仪表板的任何其他查询。

其他信息