.Net Core - Azure Application Insights不显示异常

时间:2016-10-24 11:53:37

标签: azure azure-application-insights

在.net核心项目中,在全球范围内放置azure应用程序洞察异常的位置和方式?我正在安装应用程序洞察,我可以在azure中跟踪遥测,但失败的请求会缺少异常。

1 个答案:

答案 0 :(得分:0)

一种方法是创建自定义中间件,捕获错误并将异常发送到AppInsights。

using System;
using System.Threading.Tasks;
using Microsoft.ApplicationInsights;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;

namespace Middleware
{
    public static class ApplicationBuilderExtensions
    {
        public static IApplicationBuilder UseHttpException(this IApplicationBuilder application)
        {
            return application.UseMiddleware<HttpExceptionMiddleware>();
        }
    }

    public class HttpExceptionMiddleware
    {
        private readonly RequestDelegate _next;

        public HttpExceptionMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            try
            {
                await _next.Invoke(context);
            }
            catch (Exception ex)
            {
                var telemetryClient = new TelemetryClient();
                telemetryClient.TrackException(ex);

                //handle response codes and other operations here
            }
        }
    }
}

然后,在Startup的Configure方法中注册中间件:

  

app.UseHttpException();