使用 Application Insights 诊断 Web 应用中的异常Diagnose exceptions in your web apps with Application Insights

Application Insights 可报告实时 Web 应用中的异常。Exceptions in your live web app are reported by Application Insights. 可以将失败的请求与异常关联到客户端和服务器上的其他事件,从而快速诊断原因。You can correlate failed requests with exceptions and other events at both the client and server, so that you can quickly diagnose the causes.

设置异常报告Set up exception reporting

使用 Visual Studio 诊断异常Diagnosing exceptions using Visual Studio

在 Visual Studio 中打开应用解决方案,帮助进行调试。Open the app solution in Visual Studio to help with debugging.

使用 F5 在服务器或开发计算机上运行应用。Run the app, either on your server or on your development machine by using F5.

在 Visual Studio 中打开“Application Insights 搜索”窗口,然后将它设置为显示应用中的事件。Open the Application Insights Search window in Visual Studio, and set it to display events from your app. 进行调试时,只需单击 Application Insights 按钮即可执行此操作。While you're debugging, you can do this just by clicking the Application Insights button.

右键单击项目,并依次选择“Application Insights”、“打开”。

请注意,可以筛选报告,以便仅显示异常。Notice that you can filter the report to show just exceptions.

没有显示异常?请参阅捕获异常No exceptions showing? See Capture exceptions.

单击异常报告,显示器堆栈跟踪。Click an exception report to show its stack trace. 单击堆栈跟踪中的行引用,打开相关代码文件。Click a line reference in the stack trace, to open the relevant code file.

请注意,CodeLens 会在代码中显示有关异常的数据:In the code, notice that CodeLens shows data about the exceptions:

有关异常的 CodeLens 通知。

使用 Azure 门户诊断故障Diagnosing failures using the Azure portal

Application Insights 附带了精选的 APM 体验,帮助你诊断所监视应用程序中的失败。Application Insights comes with a curated APM experience to help you diagnose failures in your monitored applications. 若要开始,请单击位于“调查”部分中的 Application Insights 资源菜单中的“失败”选项。To start, click on the Failures option in the Application Insights resource menu located in the Investigate section. 此时应看到一个显示请求的失败率趋势的全屏视图,其中包括多少个请求将要失败以及多少个用户受到影响。You should see a full-screen view that shows you the failure rate trends for your requests, how many of them are failing, and how many users are impacted. 在右侧将看到一些最有用的特定于所选失败操作的分发,包括前三个响应代码、前三个异常类型以及前三种失败依赖项类型。On the right, you'll see some of the most useful distributions specific to the selected failing operation, including top three response codes, top three exception types, and top three failing dependency types.

失败会审视图(“操作”选项卡)

只需单击一下,即可查看其中每个子集的操作具有代表性的示例。In a single click, you can then review representative samples for each of these subsets of operations. 具体而言,若要诊断异常,可以单击要在“端到端事务详细信息”选项卡中显示的特定异常的计数,如下所示:In particular, to diagnose exceptions, you can click on the count of a particular exception to be presented with the End-to-end transaction details tab, such as this one:

“端到端事务详细信息”选项卡

或者, 可以切换到顶部的“异常”选项卡,从异常的总体视图开始,而不是查看特定失败操作的异常:Alternatively, instead of looking at exceptions of a specific failing operation, you can start from the overall view of exceptions, by switching to the Exceptions tab at the top. 这里可以看到为所监视的应用收集的所有异常。Here you can see all the exceptions collected for your monitored app.

没有显示异常?请参阅捕获异常No exceptions showing? See Capture exceptions.

自定义跟踪和日志数据Custom tracing and log data

要获取特定于应用的诊断数据,可在插入代码后发送自己的遥测数据。To get diagnostic data specific to your app, you can insert code to send your own telemetry data. 该数据与请求、页面视图和其他自动收集的数据一起显示在诊断搜索中。This displayed in diagnostic search alongside the request, page view, and other automatically collected data.

有几种选项:You have several options:

若要查看这些事件,请在左侧菜单中打开 搜索、选择“事件类型”下拉菜单,然后选择“自定义事件”、“跟踪”或“异常”。To see these events, open Search from the left menu, select the drop-down menu Event types, and then choose Custom Event, Trace, or Exception.

深入了解

备注

如果应用生成大量遥测,自适应采样模块将通过仅发送具有代表性的事件部分自动减少发送到门户的量。If your app generates a lot of telemetry, the adaptive sampling module will automatically reduce the volume that is sent to the portal by sending only a representative fraction of events. 将以组为单位选择或取消选择属于同一操作的事件,以便可以在相关事件之间浏览。Events that are part of the same operation will be selected or deselected as a group, so that you can navigate between related events. 了解采样Learn about sampling.

如何查看请求 POST 数据How to see request POST data

请求详细信息不包含在 POST 调用中发送到应用的数据。Request details don't include the data sent to your app in a POST call. 若要报告此数据:To have this data reported:

  • 在应用程序中安装 SDKInstall the SDK in your application project.
  • 在应用程序中插入代码以调用 Microsoft.ApplicationInsights.TrackTrace()Insert code in your application to call Microsoft.ApplicationInsights.TrackTrace(). 在消息参数中发送 POST 数据。Send the POST data in the message parameter. 允许的大小有限制,因此,应该尝试仅发送必要数据。There is a limit to the permitted size, so you should try to send just the essential data.
  • 调查失败的请求时,查找关联的跟踪。When you investigate a failed request, find the associated traces.

首先,不会在门户中看到在应用中导致失败的所有异常。At first, you won't see in the portal all the exceptions that cause failures in your app. 将显示所有浏览器异常(如果在网页中使用 JavaScript SDK),You'll see any browser exceptions (if you're using the JavaScript SDK in your web pages). 但大多数服务器异常由 IIS 导致,必须编写几行代码才能看到它们。But most server exceptions are caught by IIS and you have to write a bit of code to see them.

方法:You can:

  • 通过在异常处理程序中插入代码来显式记录异常,从而报告这些异常。Log exceptions explicitly by inserting code in exception handlers to report the exceptions.
  • 通过配置 ASP.NET 框架自动捕获异常Capture exceptions automatically by configuring your ASP.NET framework. 框架类型不同,必要的附加内容也不同。The necessary additions are different for different types of framework.

显式报告异常Reporting exceptions explicitly

最简单的方法是在异常处理程序中插入对 TrackException() 的调用。The simplest way is to insert a call to TrackException() in an exception handler.

    try
    { ...
    }
    catch (ex)
    {
      appInsights.trackException(ex, "handler loc",
        {Game: currentGame.Name,
         State: currentGame.State.ToString()});
    }
    var telemetry = new TelemetryClient();
    ...
    try
    { ...
    }
    catch (Exception ex)
    {
       // Set up some properties:
       var properties = new Dictionary <string, string>
         {{"Game", currentGame.Name}};

       var measurements = new Dictionary <string, double>
         {{"Users", currentGame.Users.Count}};

       // Send the exception telemetry:
       telemetry.TrackException(ex, properties, measurements);
    }
    Dim telemetry = New TelemetryClient
    ...
    Try
      ...
    Catch ex as Exception
      ' Set up some properties:
      Dim properties = New Dictionary (Of String, String)
      properties.Add("Game", currentGame.Name)

      Dim measurements = New Dictionary (Of String, Double)
      measurements.Add("Users", currentGame.Users.Count)

      ' Send the exception telemetry:
      telemetry.TrackException(ex, properties, measurements)
    End Try

属性和测量参数是可选的,但对于筛选和添加额外信息很有用。The properties and measurements parameters are optional, but are useful for filtering and adding extra information. 例如,如果有一个可运行多个游戏的应用,可查找与特定游戏相关的所有异常报表。For example, if you have an app that can run several games, you could find all the exception reports related to a particular game. 可向每个字典添加任意数量的项目。You can add as many items as you like to each dictionary.

浏览器异常Browser exceptions

报告大多数浏览器异常。Most browser exceptions are reported.

如果网页包括内容分发网络或其他域中的脚本文件,确保脚本标记具有属性 crossorigin="anonymous",并且服务器可发送 CORS 标头If your web page includes script files from content delivery networks or other domains, ensure your script tag has the attribute crossorigin="anonymous", and that the server sends CORS headers. 这允许从这些资源中获取有关未处理的 JavaScript 异常的堆栈跟踪和详细信息。This will allow you to get a stack trace and detail for unhandled JavaScript exceptions from these resources.

重用遥测客户端Reuse your telemetry client

备注

建议将 TelemetryClient 实例化一次,并在应用程序的整个生命周期内重复使用。TelemetryClient is recommended to be instantiated once and re-used throughout the life of an application.

下面是一个正确使用 TelemetryClient 的示例。Below is an example using TelemetryClient correctly.

public class GoodController : ApiController
{
    // OK
    private static readonly TelemetryClient telemetryClient;

    static GoodController()
    {
        telemetryClient = new TelemetryClient();
    }
}

Web 窗体Web forms

在 Web 窗体中,当不存在通过 CustomErrors 配置的重定向时,HTTP 模块能够收集异常For web forms, the HTTP Module will be able to collect the exceptions when there are no redirects configured with CustomErrors.

但是,如果有活动重定向,在 Global.asax.cs 中将以下行添加到 Application_Error 函数。But if you have active redirects, add the following lines to the Application_Error function in Global.asax.cs. (如果还没有活动重定向,则添加 Global.asax 文件)。(Add a Global.asax file if you don't already have one.)

    void Application_Error(object sender, EventArgs e)
    {
      if (HttpContext.Current.IsCustomErrorEnabled && Server.GetLastError () != null)
      {
         var ai = new TelemetryClient(); // or re-use an existing instance

         ai.TrackException(Server.GetLastError());
      }
    }

MVCMVC

从 Application Insights Web SDK 2.6 版(beta3 及更高版本)开始,Application Insights 会自动收集 MVC 5+ 控制器方法中引发的未经处理异常。Starting with Application Insights Web SDK version 2.6 (beta3 and later), Application Insights collects unhandled exceptions thrown in the MVC 5+ controllers methods automatically. 如果之前已添加自定义处理程序以跟踪此类异常(如下面的示例中所述),则可以删除该处理程序以避免对异常进行双重跟踪。If you have previously added a custom handler to track such exceptions (as described in following examples), you may remove it to prevent double tracking of exceptions.

存在大量无法处理异常筛选器的情况。There are a number of cases that the exception filters cannot handle. 例如:For example:

  • 从控制器构造函数引发的异常。Exceptions thrown from controller constructors.
  • 从消息处理程序引发的异常。Exceptions thrown from message handlers.
  • 在路由过程中引发的异常。Exceptions thrown during routing.
  • 在响应内容序列化期间引发的异常。Exceptions thrown during response content serialization.
  • 在应用程序启动过程中引发的异常。Exception thrown during application start-up.
  • 在后台任务中引发的异常。Exception thrown in background tasks.

仍需要手动跟踪应用程序处理的所有异常。All exceptions handled by application still need to be tracked manually. 源自控制器的未经处理异常通常会导致 500“内部服务器错误”响应。Unhandled exceptions originating from controllers typically result in 500 "Internal Server Error" response. 如果此类响应是由于处理异常而手动构造的(或根本没有异常),则可在 ResultCode 为 500 的相应请求遥测中跟踪它,但是 Application Insights SDK 无法跟踪相应异常。If such response is manually constructed as a result of handled exception (or no exception at all) it is tracked in corresponding request telemetry with ResultCode 500, however Application Insights SDK is unable to track corresponding exception.

以前版本支持Prior versions support

如果使用 Application Insights Web SDK 2.5(及更低版本)的 MVC 4(及更低版本),请参照以下示例跟踪异常。If you use MVC 4 (and prior) of Application Insights Web SDK 2.5 (and prior), refer to the following examples to track exceptions.

如果 CustomErrors 配置为 OffHTTP 模块将可以收集异常。If the CustomErrors configuration is Off, then exceptions will be available for the HTTP Module to collect. 但是,如果它是 RemoteOnly(默认值)或 On,异常将清除,并且 Application Insights 无法自动收集它。However, if it is RemoteOnly (default), or On, then the exception will be cleared and not available for Application Insights to automatically collect. 可通过重写 System.Web.Mvc.HandleErrorAttribute 类并应用重写类来修复该问题,如下面针对不同的 MVC 版本所示(GitHub 源):You can fix that by overriding the System.Web.Mvc.HandleErrorAttribute class, and applying the overridden class as shown for the different MVC versions below (GitHub source):

    using System;
    using System.Web.Mvc;
    using Microsoft.ApplicationInsights;

    namespace MVC2App.Controllers
    {
      [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
      public class AiHandleErrorAttribute : HandleErrorAttribute
      {
        public override void OnException(ExceptionContext filterContext)
        {
            if (filterContext != null && filterContext.HttpContext != null && filterContext.Exception != null)
            {
                //If customError is Off, then AI HTTPModule will report the exception
                if (filterContext.HttpContext.IsCustomErrorEnabled)
                {   //or reuse instance (recommended!). see note above
                    var ai = new TelemetryClient();
                    ai.TrackException(filterContext.Exception);
                }
            }
            base.OnException(filterContext);
        }
      }
    }

MVC 2MVC 2

将 HandleError 属性替换为控制器中的新属性。Replace the HandleError attribute with your new attribute in your controllers.

    namespace MVC2App.Controllers
    {
        [AiHandleError]
        public class HomeController : Controller
        {
    ...

示例Sample

MVC 3MVC 3

AiHandleErrorAttribute 注册为 Global.asax.cs 中的全局筛选器:Register AiHandleErrorAttribute as a global filter in Global.asax.cs:

    public class MyMvcApplication : System.Web.HttpApplication
    {
      public static void RegisterGlobalFilters(GlobalFilterCollection filters)
      {
         filters.Add(new AiHandleErrorAttribute());
      }
     ...

示例Sample

MVC 4、MVC5MVC 4, MVC5

将 AiHandleErrorAttribute 注册为 FilterConfig.cs 中的全局筛选器:Register AiHandleErrorAttribute as a global filter in FilterConfig.cs:

    public class FilterConfig
    {
      public static void RegisterGlobalFilters(GlobalFilterCollection filters)
      {
        // Default replaced with the override to track unhandled exceptions
        filters.Add(new AiHandleErrorAttribute());
      }
    }

示例Sample

Web APIWeb API

从 Application Insights Web SDK 2.6 版(beta3 及更高版本)开始,Application Insights 会自动收集 WebAPI 2+ 控制器方法中引发的未经处理异常。Starting with Application Insights Web SDK version 2.6 (beta3 and later), Application Insights collects unhandled exceptions thrown in the controller methods automatically for WebAPI 2+. 如果之前已添加自定义处理程序以跟踪此类异常(如下面的示例中所述),则可以删除该处理程序以避免对异常进行双重跟踪。If you have previously added a custom handler to track such exceptions (as described in following examples), you may remove it to prevent double tracking of exceptions.

存在大量无法处理异常筛选器的情况。There are a number of cases that the exception filters cannot handle. 例如:For example:

  • 从控制器构造函数引发的异常。Exceptions thrown from controller constructors.
  • 从消息处理程序引发的异常。Exceptions thrown from message handlers.
  • 在路由过程中引发的异常。Exceptions thrown during routing.
  • 在响应内容序列化期间引发的异常。Exceptions thrown during response content serialization.
  • 在应用程序启动过程中引发的异常。Exception thrown during application start-up.
  • 在后台任务中引发的异常。Exception thrown in background tasks.

仍需要手动跟踪应用程序处理的所有异常。All exceptions handled by application still need to be tracked manually. 源自控制器的未经处理异常通常会导致 500“内部服务器错误”响应。Unhandled exceptions originating from controllers typically result in 500 "Internal Server Error" response. 如果此类响应是由于处理异常而手动构造的(或根本没有异常),则可在 ResultCode 为 500 的相应请求遥测中跟踪它,但是 Application Insights SDK 无法跟踪相应异常。If such response is manually constructed as a result of handled exception (or no exception at all) it is tracked in a corresponding request telemetry with ResultCode 500, however Application Insights SDK is unable to track corresponding exception.

以前版本支持Prior versions support

如果使用 Application Insights Web SDK 2.5(及更低版本)的 WebAPI 1(及更低版本),请参照以下示例跟踪异常。If you use WebAPI 1 (and prior) of Application Insights Web SDK 2.5 (and prior), refer to the following examples to track exceptions.

Web API 1.xWeb API 1.x

替换 System.Web.Http.Filters.ExceptionFilterAttribute:Override System.Web.Http.Filters.ExceptionFilterAttribute:

    using System.Web.Http.Filters;
    using Microsoft.ApplicationInsights;

    namespace WebAPI.App_Start
    {
      public class AiExceptionFilterAttribute : ExceptionFilterAttribute
      {
        public override void OnException(HttpActionExecutedContext actionExecutedContext)
        {
            if (actionExecutedContext != null && actionExecutedContext.Exception != null)
            {  //or reuse instance (recommended!). see note above
                var ai = new TelemetryClient();
                ai.TrackException(actionExecutedContext.Exception);
            }
            base.OnException(actionExecutedContext);
        }
      }
    }

可将此替换属性添加到特定控制器,或者将其添加到 WebApiConfig 类中的全局筛选器配置:You could add this overridden attribute to specific controllers, or add it to the global filter configuration in the WebApiConfig class:

    using System.Web.Http;
    using WebApi1.x.App_Start;

    namespace WebApi1.x
    {
      public static class WebApiConfig
      {
        public static void Register(HttpConfiguration config)
        {
            config.Routes.MapHttpRoute(name: "DefaultApi", routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional });
            ...
            config.EnableSystemDiagnosticsTracing();

            // Capture exceptions for Application Insights:
            config.Filters.Add(new AiExceptionFilterAttribute());
        }
      }
    }

示例Sample

Web API 2.xWeb API 2.x

添加 IExceptionLogger 的实现:Add an implementation of IExceptionLogger:

    using System.Web.Http.ExceptionHandling;
    using Microsoft.ApplicationInsights;

    namespace ProductsAppPureWebAPI.App_Start
    {
      public class AiExceptionLogger : ExceptionLogger
      {
        public override void Log(ExceptionLoggerContext context)
        {
            if (context !=null && context.Exception != null)
            {//or reuse instance (recommended!). see note above
                var ai = new TelemetryClient();
                ai.TrackException(context.Exception);
            }
            base.Log(context);
        }
      }
    }

将其添加到 WebApiConfig 中的服务:Add this to the services in WebApiConfig:

    using System.Web.Http;
    using System.Web.Http.ExceptionHandling;
    using ProductsAppPureWebAPI.App_Start;

    namespace WebApi2WithMVC
    {
      public static class WebApiConfig
      {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
            config.Services.Add(typeof(IExceptionLogger), new AiExceptionLogger());
        }
      }
     }

示例Sample

作为替代项,可以:As alternatives, you could:

  1. 仅将 ExceptionHandler 替换为 IExceptionHandler 的自定义实现。Replace the only ExceptionHandler with a custom implementation of IExceptionHandler. 这仅在框架仍能够选择要发送哪个响应消息时调用(不会在终止实例连接时调用)This is only called when the framework is still able to choose which response message to send (not when the connection is aborted for instance)
  2. 异常筛选器(如上述 Web API 1.x 控制器上的部分中所述),并非在所有情况下都调用。Exception Filters (as described in the section on Web API 1.x controllers above) - not called in all cases.

WCFWCF

添加可扩展属性并实现 IErrorHandler 和 IServiceBehavior 的类。Add a class that extends Attribute and implements IErrorHandler and IServiceBehavior.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.ServiceModel.Description;
    using System.ServiceModel.Dispatcher;
    using System.Web;
    using Microsoft.ApplicationInsights;

    namespace WcfService4.ErrorHandling
    {
      public class AiLogExceptionAttribute : Attribute, IErrorHandler, IServiceBehavior
      {
        public void AddBindingParameters(ServiceDescription serviceDescription,
            System.ServiceModel.ServiceHostBase serviceHostBase,
            System.Collections.ObjectModel.Collection<ServiceEndpoint> endpoints,
            System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
        {
        }

        public void ApplyDispatchBehavior(ServiceDescription serviceDescription,
            System.ServiceModel.ServiceHostBase serviceHostBase)
        {
            foreach (ChannelDispatcher disp in serviceHostBase.ChannelDispatchers)
            {
                disp.ErrorHandlers.Add(this);
            }
        }

        public void Validate(ServiceDescription serviceDescription,
            System.ServiceModel.ServiceHostBase serviceHostBase)
        {
        }

        bool IErrorHandler.HandleError(Exception error)
        {//or reuse instance (recommended!). see note above
            var ai = new TelemetryClient();

            ai.TrackException(error);
            return false;
        }

        void IErrorHandler.ProvideFault(Exception error,
            System.ServiceModel.Channels.MessageVersion version,
            ref System.ServiceModel.Channels.Message fault)
        {
        }
      }
    }

Add the attribute to the service implementations:

    namespace WcfService4
    {
        [AiLogException]
        public class Service1 : IService1
        {
         ...

示例Sample

异常性能计数器Exception performance counters

如果在服务器上安装了 Application Insights 代理,可以获取 .NET 测量的异常率图表。If you have installed the Application Insights Agent on your server, you can get a chart of the exceptions rate, measured by .NET. 这包括经处理和未经处理的 .NET 异常。This includes both handled and unhandled .NET exceptions.

打开“指标资源管理器”选项卡,添加新图表,然后选择在“性能计数器”下列出的“异常率”。Open a Metric Explorer tab, add a new chart, and select Exception rate, listed under Performance Counters.

.NET Framework 通过对间隔中的异常数进行计数并除以间隔长度计算异常率。The .NET framework calculates the rate by counting the number of exceptions in an interval and dividing by the length of the interval.

这与 Application Insights 门户通过对 TrackException 报告计数计算得出的“异常”计数不同。This is different from the 'Exceptions' count calculated by the Application Insights portal counting TrackException reports. 采样间隔不同,SDK 不会为所有经处理和未经处理的异常发送 TrackException 报告。The sampling intervals are different, and the SDK doesn't send TrackException reports for all handled and unhandled exceptions.

后续步骤Next steps