Kartikeyan
Kartikeyan

Reputation: 15

.Net Core - Azure Application Insights not showing exceptions

Where and how to put azure application insights exceptions on global level in .net core project? I am having app insights installed and I can follow telemetry in azure, but exceptions are missing for failed requests.

Upvotes: 1

Views: 1170

Answers (1)

Don Lockhart
Don Lockhart

Reputation: 914

One approach would be to create custom middleware which would catch the error and send the exception to 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
            }
        }
    }
}

Then, register the middleware in the Startup's Configure method:

app.UseHttpException();

Upvotes: 2

Related Questions