alek kowalczyk
alek kowalczyk

Reputation: 4936

Global exception handling in ASP.NET 5

How can I attach my own logging logic to an ASP.NET 5 application to handle each exception thrown in the business logic and lower layers?

I tried with own ILoggerProvider implementation and loggerfactory.AddProvider(new LoggerProvider(Configuration)) in Startup.cs. But it seems that it intercepts inner ASP.NET stuff, and not my thrown exceptions in lower layers.

Upvotes: 15

Views: 6656

Answers (2)

alek kowalczyk
alek kowalczyk

Reputation: 4936

Worked it out, by using two options:

1) ILoggerProvider Implement your own ILoggerProvider and ILogger from the namespace Microsoft.Framework.Logging Then attach it to the MVC Framework in Startup.cs add following code:

 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerfactory)
 {
        loggerfactory.AddProvider(new YourCustomProvider());
 }

But this above option, seems to only call the Write function of the ILogger on MVC specific events, routing related and so on, it wasn't called when I threw exceptions on my lower layers, so the second option worked out:

2) Global Filter Register your own ActionFilterAttribute implementation in Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc().Configure<MvcOptions>(options =>
    {
        options.Filters.Add(new YourCustomFilter());
    });
}

It's important, that the custom filter class implements the IExceptionFilter interace:

  public class YourCustomFilter : ActionFilterAttribute, IExceptionFilter
  {
             public void OnException(ExceptionContext context)
             {
              ///logic...
             }
 }

(EDIT:) And then in the Startup class we add the filter:

    public void ConfigureServices(IServiceCollection services)
    {
         services.AddMvc(options =>
            {
                options.Filters.Add(new YourCustomFilter());
            });
    }

Upvotes: 10

code5
code5

Reputation: 4794

If you want a really global exception trap framework, not just at the controller level, take a look at one of my open source projects. I plan to make it into a Nuget Package soon after the holidays. I'm also planning to update my blog showing why I developed it.

The open source project is on github: https://github.com/aspnet-plus/AspNet.Plus.Infrastructure Take a look at the sample for usage.

Upvotes: 2

Related Questions