你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

在 Azure Service Fabric、云服务和虚拟机中为 .NET 应用启用快照调试器

如果 ASP.NET 或 ASP.NET Core 应用程序在 Azure 应用服务中运行并且需要自定义的 Snapshot Debugger 配置或 .NET Core 预览版,请从在 Azure 应用服务中为 .NET 应用启用快照调试器开始。

如果应用程序在 Azure Service Fabric、Azure 云服务、Azure 虚拟机或本地计算机中运行,则可以跳过在应用服务上启用 Snapshot Debugger 并按照本文中的指南进行操作。

准备阶段

为 ASP.NET 应用程序配置快照集合

Microsoft.ApplicationInsights.SnapshotCollector NuGet 包添加到应用程序时,SnapshotCollectorTelemetryProcessor 应自动添加到 TelemetryProcessorsApplicationInsights.config部分。

如果在 ApplicationInsights.config 中看不到 SnapshotCollectorTelemetryProcessor,或者想要自定义 Snapshot Debugger 配置,可以手动编辑它。 但是,如果以后升级到较新版本的 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();

配置 Snapshot Collector

在大多数情况下,默认设置已经足够。 如果没有,请在调用 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
  }
}

如果需要手动自定义 Snapshot Collector 的行为,而不使用 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.
    }
  }
}

以下示例使用 ILogger 而不是 TelemetryClient。 此示例假设使用的是 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 将异常转发到 Snapshot Debugger。 可以通过 ApplicationInsightsLoggerOptions 类的 TrackExceptionsAsExceptionTelemetry 属性控制此行为。 如果在配置 Application Insights 记录器时将 TrackExceptionsAsExceptionTelemetry 设置为 false,则以上示例将不会触发 Snapshot Debugger。 在这种情况下,请修改代码以手动调用 TrackException

注意

对检测密钥引入的支持将于 2025 年 3 月 31 日结束。 检测密钥引入功能将会继续工作,但我们将不再为该功能提供更新或支持。 转换为连接字符串,以利用新功能

后续步骤

  • 为应用程序生成可触发异常的流量。 然后等待 10 到 15 分钟,这样快照就会发送到 Application Insights 实例。
  • 请参见 Azure 门户中的快照
  • 排查 Snapshot Debugger 问题。