15

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.

3
  • Are you looking to catch completely arbitrary exceptions? Or exceptions that end up causing the request to fail? If it's trying to catch all exceptions, that's not realistically possible because most exceptions are caught and handled by parts of the system (and then fed to a logger). If you're finding that some exceptions aren't logged, please log a bug in the appropriate repo on github.com/aspnet (e.g. MVC, or XRE).
    – Eilon
    Feb 11, 2015 at 16:56
  • Yes, that was the case why it didn't worked, because I catched them in lower layers, but when I temporary commented the catching, only the filter approach allowed me to catch the thrown exception, I didn't get it in the ILogger, is this normal behavior? If not I can try once again (as I have currently the Global Filter approach implemented), and if that is the case I can write about it on github. Feb 11, 2015 at 18:36
  • Yeah if you catch the exception, no one else will see it, so there's nothing to log. But you could very well be right that there's some other component, such as error handling middleware, which isn't logging the exception. Might be appropriate for the github.com/aspnet/Diagnostics repo.
    – Eilon
    Feb 11, 2015 at 19:51

2 Answers 2

10

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());
            });
    }
7
  • Is it possible to update the response content from the OnException method ? I am able to update the status code, but I would like to update the response body too but I do not find how
    – RPDeshaies
    Jul 15, 2015 at 12:28
  • 2
    Yes, it is possible, by setting the ExceptionContext which is provided to the OnException method. For example context.Result = new RedirectResult... or context.Result = new JsonResult.... Jul 15, 2015 at 14:21
  • 1
    @alekkowalczyk Hi I was following your example and the syntax that worked for me in the second step is a little bit different. Here is my version, maybe can help someone else, services.AddMvc((options => { options.Filters.Add(new CustomFilerForExceptionHandling()); }));
    – Juan
    Oct 21, 2015 at 14:57
  • 1
    By the way, this code doesn't catch exceptions that occur during Startup.Configure() Jan 6, 2016 at 6:56
  • Perhaps silly question, but how do you pass logger to YourCustomFilter? Jan 6, 2016 at 11:33
2

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.