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 パッケージをアプリケーションに追加すると、 SnapshotCollectorTelemetryProcessorApplicationInsights.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();

Snapshot Collector を構成する

ほとんどの組織で既定の設定をそのまま使うことができます。 そうでない場合は、AddSnapshotCollector() の呼び出しの前に次のコードを追加して設定をカスタマイズします

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

次に 、 appsettings.jsonSnapshotCollector セクションを追加します。ここで、既定値をオーバーライドできます。 次の例は、既定の構成と同じ構成を示しています。

{
  "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 を使用せずに Snapshot Collector の動作を手動でカスタマイズする必要がある場合は、デリゲートを受け取る 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.");
    }
  }
}

Note

既定では、Application Insights のログ (ApplicationInsightsLoggerProvider) は TelemetryClient.TrackException 経由でスナップショット デバッガーに例外を転送します。 この動作は、ApplicationInsightsLoggerOptions クラスの TrackExceptionsAsExceptionTelemetry プロパティを使用して制御されます。 Application Insights のログの構成時に TrackExceptionsAsExceptionTelemetryfalse に設定した場合、前述の例ではスナップショット デバッガーはトリガーされません。 この場合は、TrackException を手動で呼び出すようにコードを変更します。

Note

インストルメンテーション キーのインジェストのサポートは、2025 年 3 月 31 日に終了します。 インストルメンテーション キーのインジェストは引き続き機能しますが、この機能の更新プログラムやサポートは提供されなくなります。 接続文字列に移行することで、新機能をご利用いただけます。

次のステップ

  • 例外をトリガーできるアプリケーションへのトラフィックを生成します。 その後、Application Insights インスタンスにスナップショットが送信がされるまで 10 分から 15 分待ちます。
  • Azure portal でスナップショットを確認します。
  • スナップショット デバッガーの問題に対してトラブルシューティングを実施します。