在 Azure Service Fabric、雲端服務 和 虛擬機器 中啟用 .NET 應用程式的快照調試程式

如果您的 ASP.NET 或 ASP.NET Core 應用程式在 Azure App 服務 中執行,而且需要自定義的快照調試程式組態,或 .NET Core 的預覽版本,請從在 Azure App 服務 中啟用 .NET 應用程式的快照調試程序開始

如果您的應用程式在 Azure Service Fabric、Azure 雲端服務、Azure 虛擬機器 或內部部署機器中執行,您可以略過在 App Service 上啟用快照調試程式,並遵循本文中的指引。

開始之前

設定 ASP.NET 應用程式的快照集集合

當您將 Microsoft.ApplicationInsights.SnapshotCollector NuGet 套件新增至應用程式時,SnapshotCollectorTelemetryProcessor應該會自動將 新增至 TelemetryProcessors ApplicationInsights.config區段。

如果您在 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 應用程式或背景工作服務的快照集集合

必要條件

您的應用程式應該已經參考下列其中一個 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.
    }
  }
}

下列範例會使用 ILoggerTelemetryClient而不是 。 此範例假設您使用 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 Logger (ApplicationInsightsLoggerProvider) 會透過 TelemetryClient.TrackException將例外狀況轉送至快照調試程式。 此行為是透過 TrackExceptionsAsExceptionTelemetry 類別上的 ApplicationInsightsLoggerOptions 屬性來控制。 如果您在設定 Application Insights 記錄器時將 設定 TrackExceptionsAsExceptionTelemetryfalse ,則上述範例將不會觸發快照調試程式。 在此情況下,請修改您的程式代碼以手動呼叫 TrackException

注意

針對檢測金鑰擷取的支援將在 2025 年 3 月 31 日結束。 檢測金鑰擷取將會繼續運作,但我們不再提供該功能的更新或支援。 轉換至連接字串以利用新功能

下一步