Mengaktifkan Snapshot Debugger untuk aplikasi .NET di Azure Service Fabric, Cloud Services, dan Virtual Machines

Jika aplikasi ASP.NET atau ASP.NET Core Anda berjalan di Azure App Service dan memerlukan konfigurasi Snapshot Debugger yang disesuaikan, atau versi pratinjau .NET Core, mulailah dengan Mengaktifkan Snapshot Debugger untuk aplikasi .NET di Azure App Service.

Jika aplikasi Anda berjalan di Azure Service Fabric, Azure Cloud Services, Azure Virtual Machines, atau komputer lokal, Anda dapat melewati pengaktifan Snapshot Debugger di App Service dan mengikuti panduan dalam artikel ini.

Sebelum Anda mulai

Mengonfigurasi koleksi rekam jepret untuk aplikasi ASP.NET

Saat Anda menambahkan paket NuGet Microsoft.ApplicationInsights.SnapshotCollector ke aplikasi Anda, SnapshotCollectorTelemetryProcessor harus ditambahkan secara otomatis ke TelemetryProcessors bagian ApplicationInsights.config.

Jika Anda tidak melihat SnapshotCollectorTelemetryProcessor di ApplicationInsights.config, atau jika Anda ingin menyesuaikan konfigurasi Snapshot Debugger, Anda dapat mengeditnya dengan tangan. Namun, pengeditan ini mungkin ditimpa jika Nanti Anda meningkatkan ke versi paket NuGet Microsoft.ApplicationInsights.SnapshotCollector yang lebih baru.

Contoh berikut menunjukkan konfigurasi yang setara dengan konfigurasi default:

<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>

Rekam jepret dikumpulkan hanya pada pengecualian yang dilaporkan ke Application Insights. Dalam beberapa kasus (misalnya, versi lama platform .NET), Anda mungkin perlu mengonfigurasi koleksi pengecualian untuk melihat pengecualian dengan rekam jepret di portal.

Mengonfigurasi pengumpulan rekam jepret untuk aplikasi ASP.NET Core atau Layanan Pekerja

Prasyarat

Aplikasi Anda harus sudah mereferensikan salah satu paket Application Insights NuGet berikut:

Menambahkan paket NuGet

Tambahkan paket NuGet Microsoft.ApplicationInsights.SnapshotCollector ke aplikasi Anda.

Memperbarui kumpulan layanan

Dalam kode startup aplikasi Anda, tempat layanan dikonfigurasi, tambahkan panggilan ke AddSnapshotCollector metode ekstensi. Ada baiknya untuk menambahkan baris ini segera setelah panggilan ke AddApplicationInsightsTelemetry. Contohnya:

var builder = WebApplication.CreateBuilder(args);

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

Mengonfigurasi Snapshot Collector

Untuk sebagian besar situasi, pengaturan default sudah cukup. Jika tidak, kustomisasi pengaturan dengan menambahkan kode berikut sebelum panggilan ke AddSnapshotCollector()

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

Selanjutnya, tambahkan SnapshotCollector bagian ke appsettings.json tempat Anda dapat mengambil alih default. Contoh berikut menunjukkan konfigurasi yang setara dengan konfigurasi default:

{
  "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
  }
}

Jika Anda perlu menyesuaikan perilaku Snapshot Collector secara manual, tanpa menggunakan appsettings.json, gunakan kelebihan beban AddSnapshotCollector yang mengambil delegasi. Contohnya:

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

Mengonfigurasi koleksi rekam jepret untuk aplikasi .NET lainnya

Rekam jepret hanya dikumpulkan pada pengecualian yang dilaporkan ke Application Insights. Untuk aplikasi ASP.NET dan ASP.NET Core, Application Insights SDK secara otomatis melaporkan pengecualian yang tidak tertangani yang lolos dari metode pengontrol atau handler rute titik akhir. Untuk aplikasi lain, Anda mungkin perlu memodifikasi kode Anda untuk melaporkannya. Kode penanganan pengecualian tergantung pada struktur aplikasi Anda. Berikut contohnya:

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.
    }
  }
}

Contoh berikut menggunakan alih-alih ILoggerTelemetryClient. Contoh ini mengasumsikan Anda menggunakan Penyedia Pencatat Application Insights. Seperti yang ditunjukkan contoh, saat menangani pengecualian, pastikan untuk meneruskan pengecualian sebagai parameter pertama ke 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.");
    }
  }
}

Catatan

Secara default, Application Insights Logger (ApplicationInsightsLoggerProvider) meneruskan pengecualian ke Snapshot Debugger melalui TelemetryClient.TrackException. Perilaku ini dikontrol melalui TrackExceptionsAsExceptionTelemetry properti di ApplicationInsightsLoggerOptions kelas . Jika Anda mengatur TrackExceptionsAsExceptionTelemetry ke false saat mengonfigurasi Application Insights Logger, maka contoh sebelumnya tidak akan memicu Snapshot Debugger. Dalam hal ini, ubah kode Anda untuk memanggil TrackException secara manual.

Catatan

Pada tanggal 31 Maret 2025, dukungan untuk penyerapan kunci instrumentasi akan berakhir. Penyerapan kunci instrumentasi akan berjalan terus, namun kami tidak akan lagi menyediakan pembaruan atau dukungan terhadap fitur tersebut. Transisi ke string koneksi untuk memanfaatkan kemampuan baru.

Langkah berikutnya

  • Hasilkan lalu lintas ke aplikasi Anda yang dapat memicu pengecualian. Kemudian tunggu 10 hingga 15 menit agar rekam jepret dikirim ke instans Application Insights.
  • Lihat rekam jepret di portal Microsoft Azure.
  • Memecahkan masalah Snapshot Debugger.