Azure Service Fabric, Cloud Services 및 Virtual Machines에서 .NET 앱용 스냅샷 디버거 사용

ASP.NET 또는 ASP.NET Core 애플리케이션이 Azure App Service에서 실행되고 사용자 지정된 스냅샷 디버거 구성 또는 .NET Core의 미리 보기 버전이 필요한 경우 Azure App Service에서 .NET 앱용 스냅샷 디버거 사용을 시작합니다.

애플리케이션이 Azure Service Fabric, Azure Cloud Services, Azure Virtual Machines 또는 온-프레미스 머신에서 실행되는 경우 App Service에서 스냅샷 디버거를 사용하도록 설정하는 것을 건너뛰고 이 문서의 지침을 따를 수 있습니다.

시작하기 전에

ASP.NET 애플리케이션에 대한 스냅샷 컬렉션 구성

Microsoft.ApplicationInsights.SnapshotCollector NuGet 패키지를 애플리케이션에 추가하면 SnapshotCollectorTelemetryProcessor ApplicationInsights.configTelemetryProcessors 섹션에 자동으로 추가되어야 합니다.

ApplicationInsights.config에 SnapshotCollectorTelemetryProcessor가 표시되지 않거나 스냅샷 디버거 구성을 사용자 지정하려는 경우 직접 편집할 수 있습니다. 그러나 나중에 최신 버전의 Microsoft.ApplicationInsights.SnapshotCollector NuGet 패키지로 업그레이드하면 이러한 편집 내용을 덮어쓸 수 있습니다.

다음 예제에서는 기본 구성에 해당하는 구성을 보여 줍니다.

<TelemetryProcessors>
  <Add Type="Microsoft.ApplicationInsights.SnapshotCollector.SnapshotCollectorTelemetryProcessor, Microsoft.ApplicationInsights.SnapshotCollector">
    <!-- The default is true, but you can disable Snapshot Debugging by setting it to false -->
    <IsEnabled>true</IsEnabled>
    <!-- Snapshot Debugging is usually disabled in developer mode, but you can enable it by setting this to true. -->
    <!-- DeveloperMode is a property on the active TelemetryChannel. -->
    <IsEnabledInDeveloperMode>false</IsEnabledInDeveloperMode>
    <!-- How many times we need to see an exception before we ask for snapshots. -->
    <ThresholdForSnapshotting>1</ThresholdForSnapshotting>
    <!-- The maximum number of examples we create for a single problem. -->
    <MaximumSnapshotsRequired>3</MaximumSnapshotsRequired>
    <!-- The maximum number of problems that we can be tracking at any time. -->
    <MaximumCollectionPlanSize>50</MaximumCollectionPlanSize>
    <!-- How often we reconnect to the stamp. The default value is 15 minutes.-->
    <ReconnectInterval>00:15:00</ReconnectInterval>
    <!-- How often to reset problem counters. -->
    <ProblemCounterResetInterval>1.00:00:00</ProblemCounterResetInterval>
    <!-- The maximum number of snapshots allowed in ten minutes.The default value is 1. -->
    <SnapshotsPerTenMinutesLimit>3</SnapshotsPerTenMinutesLimit>
    <!-- The maximum number of snapshots allowed per day. -->
    <SnapshotsPerDayLimit>30</SnapshotsPerDayLimit>
    <!-- Whether or not to collect snapshot in low IO priority thread. The default value is true. -->
    <SnapshotInLowPriorityThread>true</SnapshotInLowPriorityThread>
    <!-- Agree to send anonymous data to Microsoft to make this product better. -->
    <ProvideAnonymousTelemetry>true</ProvideAnonymousTelemetry>
    <!-- The limit on the number of failed requests to request snapshots before the telemetry processor is disabled. -->
    <FailedRequestLimit>3</FailedRequestLimit>
  </Add>
</TelemetryProcessors>

스냅샷은 Application Insights에 보고되는 예외에 대해서만 수집됩니다. 경우에 따라(예: 이전 버전의 .NET 플랫폼) 포털에서 스냅샷 예외를 보려면 예외 컬렉션을 구성해야 할 수 있습니다.

ASP.NET Core 애플리케이션 또는 Worker Services에 대한 스냅샷 컬렉션 구성

필수 조건

애플리케이션은 이미 다음 Application Insights NuGet 패키지 중 하나를 참조해야 합니다.

NuGet 패키지 추가

Microsoft.ApplicationInsights.SnapshotCollector NuGet 패키지를 앱에 추가합니다.

서비스 컬렉션 업데이트

서비스가 구성된 애플리케이션의 시작 코드에서 AddSnapshotCollector 확장 메서드에 대한 호출을 추가합니다. AddApplicationInsightsTelemetry 호출 직후에 이 줄을 추가하는 것이 좋습니다. 예시:

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddApplicationInsightsTelemetry();
builder.Services.AddSnapshotCollector();

스냅샷 수집기 구성

대부분의 경우 기본 설정으로 충분합니다. 그렇지 않은 경우 AddSnapshotCollector() 호출 전에 다음 코드를 추가하여 설정을 사용자 지정합니다.

using Microsoft.ApplicationInsights.SnapshotCollector;
...
builder.Services.Configure<SnapshotCollectorConfiguration>(builder.Configuration.GetSection("SnapshotCollector"));

다음으로, 기본값을 재정의할 수 있는 SnapshotCollector 섹션을 appsettings.json에 추가합니다. 다음 예제에서는 기본 구성에 해당하는 구성을 보여 줍니다.

{
  "SnapshotCollector": {
    "IsEnabledInDeveloperMode": false,
    "ThresholdForSnapshotting": 1,
    "MaximumSnapshotsRequired": 3,
    "MaximumCollectionPlanSize": 50,
    "ReconnectInterval": "00:15:00",
    "ProblemCounterResetInterval":"1.00:00:00",
    "SnapshotsPerTenMinutesLimit": 1,
    "SnapshotsPerDayLimit": 30,
    "SnapshotInLowPriorityThread": true,
    "ProvideAnonymousTelemetry": true,
    "FailedRequestLimit": 3
  }
}

appsettings.json을 사용하지 않고 스냅샷 수집기의 동작을 수동으로 사용자 지정해야 하는 경우 대리자를 사용하는 AddSnapshotCollector의 오버로드를 사용합니다. 예시:

builder.Services.AddSnapshotCollector(config => config.IsEnabledInDeveloperMode = true);

다른 .NET 애플리케이션에 대한 스냅샷 컬렉션 구성

스냅샷은 Application Insights에 보고되는 예외에 대해서만 수집됩니다. ASP.NET 및 ASP.NET Core 애플리케이션의 경우 Application Insights SDK는 컨트롤러 메서드 또는 엔드포인트 경로 처리기를 이스케이프하는 처리되지 않은 예외를 자동으로 보고합니다. 다른 애플리케이션의 경우 코드를 수정하여 보고해야 할 수도 있습니다. 예외 처리 코드는 애플리케이션의 구조에 따라 달라집니다. 예를 들면 다음과 같습니다.

using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.ApplicationInsights.Extensibility;

internal class ExampleService
{
  private readonly TelemetryClient _telemetryClient;

  public ExampleService(TelemetryClient telemetryClient)
  {
    // Obtain the TelemetryClient via dependency injection.
    _telemetryClient = telemetryClient;
  }

  public void HandleExampleRequest()
  {
    using IOperationHolder<RequestTelemetry> operation = 
        _telemetryClient.StartOperation<RequestTelemetry>("Example");
    try
    {
      // TODO: Handle the request.
      operation.Telemetry.Success = true;
    }
    catch (Exception ex)
    {
      // Report the exception to Application Insights.
      operation.Telemetry.Success = false;
      _telemetryClient.TrackException(ex);
      // TODO: Rethrow the exception if desired.
    }
  }
}

다음 예제에서는 TelemetryClient 대신 ILogger을(를) 사용합니다. 이 예제에서는 Application Insights 로거 공급자를 사용 중이라고 가정합니다. 예제에서 알 수 있듯이 예외를 처리할 때 예외를 첫 번째 매개 변수로 LogError에 전달해야 합니다.

using Microsoft.Extensions.Logging;

internal class LoggerExample
{
  private readonly ILogger _logger;

  public LoggerExample(ILogger<LoggerExample> logger)
  {
    _logger = logger;
  }

  public void HandleExampleRequest()
  {
    using IDisposable scope = _logger.BeginScope("Example");
    try
    {
      // TODO: Handle the request
    }
    catch (Exception ex)
    {
      // Use the LogError overload with an Exception as the first parameter.
      _logger.LogError(ex, "An error occurred.");
    }
  }
}

참고 항목

기본적으로 Application Insights 로거(ApplicationInsightsLoggerProvider)는 TelemetryClient.TrackException통해 스냅샷 디버거에 예외를 전달합니다. 이 동작은 ApplicationInsightsLoggerOptions 클래스의 TrackExceptionsAsExceptionTelemetry 속성을 통해 제어됩니다. Application Insights 로거를 구성할 때 TrackExceptionsAsExceptionTelemetry을(를) false(으)로 설정하면 앞의 예제에서 스냅샷 디버거를 트리거하지 않습니다. 이 경우 수동으로 TrackException을(를) 호출하도록 코드를 수정합니다.

참고 항목

2025년 3월 31일에 계측 키 수집에 대한 지원이 종료됩니다. 계측 키 수집은 계속 작동하지만 더 이상 기능에 대한 업데이트 또는 지원을 제공하지 않습니다. 연결 문자열로 전환하여 새로운 기능을 활용합니다.

다음 단계

  • 예외를 트리거할 수 있는 애플리케이션에 대한 트래픽을 생성합니다. 그런 다음, 스냅샷이 Application Insights 인스턴스로 전송될 때까지 10~15분 정도 기다립니다.
  • Azure Portal에서 스냅샷을 참조하세요.
  • 스냅샷 디버거 문제 해결.