ASP.NET Web API v2 and logging all errors/exceptions with ELMAH

3.8k Views Asked by At

Despite spending hours searching the net I couldn't find a solution to this problem. Being a noob to Web API v2 this is probably a really easy question for someone with more experience.

I have a clean MVC project updated to use Web API v2. I've installed a number of ELMAH packages via Nuget.

When working with the normal Home controller in MVC if I put an invalid page e.g. /Home/test it would generate a 404. Elmah in turn captures this and I know just from the logs what pages might be broken etc.

I want to transfer this level of logging over to the API controller. The logging does work, but I have to throw an exception to the controller to get something logged in Elmah.

I'm guessing that things like 404/415 errors are classed as 'handled' exceptions, but I'm only getting un-handled exceptions logged.

At any rate what I want is for ANY errors on the API controller to be logged. This way I can monitor how the API is being used and any errors caused by calling clients. Errors might be 404s, 415 for unsupported data types and so on. That way if there are any problems with posted data from a client I can easily see the response that would have been passed back.

Thanks in advance!

WebApi.config:

Public static void Register(HttpConfiguration config)
{
    ...
       config.filters.add(new Elmah.Contrib.WebApi.ElmahHandleErrorApiAttribute());
}

Filter.config:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
   filters.Add(new Elmah.Contrib.Mvc.ElmahHandleErrorAttribute());
   filters.Add(new HandleErrorAttribute();
}
2

There are 2 best solutions below

4
On

You need to register an exception logger with Web API as well. Check out this awesome post: http://www.jasonwatmore.com/post/2014/05/03/Getting-ELMAH-to-catch-ALL-unhandled-exceptions-in-Web-API-21.aspx

0
On

It turns out that 404 errors are treated a bit differently in Web API, they bypass the usual request pipeline and are sent directly to the browser before ELMAH knows anything about them.

So in order to log 404 errors with ELMAH you need to add a 'catch all' route as the last route in your WebApiConfig to log the errors manually.

I've just updated the post and included a working example solution - http://jasonwatmore.com/post/2014/05/03/Getting-ELMAH-to-catch-ALL-unhandled-exceptions-in-Web-API-21.aspx