Liero
Liero

Reputation: 27328

How to log exceptions in asp.net core app using ApplicationInsights 2.x when DeveloperExceptionPage is used

Is there any documentation regarding ApplicationInsights 2.x and asp.net core?

I've found this: https://learn.microsoft.com/en-us/azure/application-insights/app-insights-asp-net-exceptions, but is looks obsolete.

It uses 'HandleErrorAttribute', but it is .NET Framework's class, not .net core.

Upvotes: 2

Views: 1446

Answers (1)

Amor
Amor

Reputation: 8491

In ASP.NET Core, you could handle exception by implementing IExceptionFilter interface. Code below is for your reference.

public class GlobalExceptionFilter : Microsoft.AspNetCore.Mvc.Filters.IExceptionFilter
{
    public void OnException(ExceptionContext context)
    {
        var telemetry = new TelemetryClient();
        var properties = new Dictionary<string, string> { { "custom-property1", "property1-value" } };
        telemetry.TrackException(context.Exception, properties);
    }
}

After define the filter, you could register it when adding MVC service in ConfigureServices method.

services.AddMvc().AddMvcOptions(opt=> { opt.Filters.Add(new GlobalExceptionFilter()); });

Upvotes: 5

Related Questions