봇에 원격 분석 추가

적용 대상: SDK v4

원격 분석 로깅을 사용하면 봇 애플리케이션이 Application Insights와 같은 원격 분석 서비스에 이벤트 데이터를 보낼 수 있습니다. 원격 분석은 가장 많이 사용되는 기능을 보여 줌으로써 봇에 대한 인사이트를 제공하고, 원치 않는 동작을 감지하며, 가용성, 성능 및 사용량에 대한 가시성을 제공합니다.

이 문서에서는 Application Insights를 사용하여 봇에서 원격 분석을 구현하는 방법을 설명합니다. 이 문서에서는 다음 내용을 설명합니다.

  • 봇에서 원격 분석을 연결하고 Application Insights에 연결하는 데 필요한 코드입니다.
  • 봇의 대화 상자에서 원격 분석을 사용하도록 설정하는 방법입니다.
  • 원격 분석을 사용하여 Azure AI 서비스와 같은 다른 서비스에서 사용량 현황 데이터를 캡처하는 방법입니다.
  • Application Insights에서 원격 분석 데이터를 시각화하는 방법입니다.

중요

원격 분석에서 PII(개인 식별 정보)를 수집할 수 있는 지역 봇의 경우 Application Insights 리소스와 Azure Bot 리소스는 봇과 동일한 지역에 있어야 합니다. 리소스가 다른 지역에 있는 경우 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 샘플 코드를 업데이트하여 팔로우하는 경우 에 대한 Microsoft.Bot.Builder.Integration.AspNet.Core using 문이 CoreBot 샘플에 이미 있다는 것을 알 수 있습니다.

  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() 메서드에 추가된 미들웨어 코드를 사용하도록 어댑터에 지시합니다. 생성자의 매개 변수 목록에서 TelemetryInitializerMiddleware telemetryInitializerMiddleware 매개 변수와 Use(telemetryInitializerMiddleware); 다음과 같이 생성자의 문을 사용하여 이 AdapterWithErrorHandler.cs 작업을 수행합니다.

        public AdapterWithErrorHandler(IConfiguration configuration, ILogger<BotFrameworkHttpAdapter> logger, TelemetryInitializerMiddleware telemetryInitializerMiddleware, ConversationState conversationState = null)
            : base(configuration, logger)
    {
        ...
        Use(telemetryInitializerMiddleware);
    }
    
  6. 또한 의 using 문 AdapterWithErrorHandler.cs목록에 를 추가 Microsoft.Bot.Builder.Integration.ApplicationInsights.Core 해야 합니다.

  7. Application Insights 계측 키를 appsettings.json 파일에 추가합니다. 파일에는 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 샘플 애플리케이션에서는 모든 대화 상자가 ComponentDialog인 MainDialog에 추가됩니다. TelemetryClient 속성을 MainDialog로 설정하면 추가된 모든 대화 상자가 원격 분석클라이언트를 자동으로 상속하므로 대화 상자를 추가할 때 명시적으로 설정할 필요가 없습니다.

아래 단계에 따라 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 해야 합니다.

활동 이벤트 및 개인 정보 로깅 사용 또는 사용 안 함

활동 로깅 사용 또는 사용 안 함

기본적으로 TelemetryInitializerMiddlewareTelemetryLoggerMiddleware를 사용하여 봇에서 활동을 보내거나 받을 때 원격 분석을 기록합니다. 활동 로깅은 사용자 지정 이벤트 로그를 Application Insights 리소스에 만듭니다. 원하는 경우 Startup.cs에 등록할 때 에서 을 false TelemetryInitializerMiddleware 로 설정 logActivityTelemetry 하여 활동 이벤트 로깅을 사용하지 않도록 설정할 수 있습니다.

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 Language의 기능인 사용자 지정 질문 답변은 QnA Maker 서비스의 업데이트된 버전입니다. Bot Framework SDK의 질문 및 답변 지원에 대한 자세한 내용은 자연어 이해를 참조하세요.

참고

LUIS(Language Understanding)는 2025년 10월 1일에 사용 중지됩니다. 2023년 4월 1일부터 새 LUIS 리소스를 만들 수 없습니다. 이제 최신 버전의 언어 이해가 Azure AI 언어의 일부로 제공됩니다.

Azure AI Language의 기능인 CLU(대화형 언어 이해)는 업데이트된 LUIS 버전입니다. Bot Framework SDK의 언어 이해 지원에 대한 자세한 내용은 자연어 이해를 참조하세요.

다음으로 LUIS 서비스에서 원격 분석 기능을 구현합니다. LUIS 서비스에는 기본 제공 원격 분석 로깅을 사용할 수 있으므로 LUIS에서 원격 분석 데이터 가져오기를 시작하기 위해 수행할 작업이 거의 없습니다. QnA Maker 지원 봇에서 원격 분석을 사용하도록 설정하는 데 관심이 있는 경우 QnA Maker 봇에 원격 분석 추가를 참조하세요.

  1. IBotTelemetryClient telemetryClient 매개 변수는 FlightBookingRecognizer.csFlightBookingRecognizer 생성자에 필요합니다.

    public FlightBookingRecognizer(IConfiguration configuration, IBotTelemetryClient telemetryClient)
    
  2. 다음으로 생성자에서 를 LuisRecognizer 만들 때 를 FlightBookingRecognizer 사용하도록 설정합니다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);
    }
    

다 됐습니다. 이제 Application insights에 원격 분석 데이터를 기록하는 봇이 정상적으로 작동할 것입니다. Bot Framework Emulator를 사용하여 봇을 로컬로 실행할 수 있습니다. 봇의 동작이 어떻게 달라졌는지 눈에 보이지는 않지만, 봇이 Application Insights에 정보를 기록할 것입니다. 여러 메시지를 전송하여 봇과 상호 작용하고 다음 섹션에서 Application Insights의 원격 분석 결과를 검토합니다.

봇의 테스트 및 디버깅에 대한 내용은 다음 문서를 참조하세요.

Application Insights에서 원격 분석 데이터 시각화

Application Insights는 클라우드 또는 온-프레미스에 호스트되는 봇 애플리케이션의 가용성, 성능 및 사용량을 모니터링합니다. Azure Monitor의 강력한 데이터 분석 플랫폼을 사용하여 애플리케이션 작업에 대한 심층 인사이트를 제공하고 사용자가 보고할 때까지 기다리지 않고 오류를 진단합니다. Application Insights가 수집한 원격 분석 데이터를 살펴보는 몇 가지 방법이 있는데, 가장 많이 사용되는 두 가지 방법은 쿼리와 대시보드입니다.

Kusto 쿼리를 사용하여 Application Insights에서 원격 분석 데이터 쿼리

이 섹션을 시작점으로 사용하여 Application Insights에서 로그 쿼리를 사용하는 방법을 알아보세요. 이 섹션에서는 두 가지 유용한 쿼리를 보여주고 추가 정보가 포함된 다른 설명서의 링크를 제공합니다.

데이터를 쿼리하는 방법

  1. Azure Portal로 이동

  2. Application Insights 페이지로 이동하려면 모니터, 애플리케이션을 차례로 선택하고 해당 페이지에서 찾습니다.

  3. Application Insights에서 로그(분석)를 선택합니다.

    봇의 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 dashboard 쿼리를 고정할 수 있습니다. 쿼리를 고정하려는 대시보드를 선택하기만 하면 됩니다. 그러면 다음에 해당 대시보드를 방문할 때 쿼리를 사용할 수 있습니다.

Application Insights 대시보드

Azure에서 Application Insights 리소스를 만들 때마다 새 대시보드가 자동으로 만들어지고 리소스와 연결됩니다. Application Insights 블레이드의 맨 위에 있는 애플리케이션 대시보드라는 단추를 선택하면 대시보드를 볼 수 있습니다.

봇의 Application Insights 페이지에 애플리케이션 대시보드 단추가 있는 스크린샷

또는 데이터를 보려면 Azure Portal로 이동합니다. 왼쪽에서 대시보드를 선택한 다음 드롭다운에서 원하는 dashboard 선택합니다.

해당 대시보드에는 봇 성능에 대한 기본 정보와 해당 대시보드에 고정한 추가 쿼리가 표시됩니다.

추가 정보