Search code examples
asp.net-web-api2error-logging

Suggestions for error logging in Web API 2


What error logging solution should I use for my ASP.NET Web API 2.1 in a high volume production environment?

I'm trying to keep my Web API as lightweight as possible so there's no MVC in it. Just plain old Web API and I'd like to keep it that way if I can.


Solution

  • I'd take a look at Elmah

    http://www.asp.net/web-forms/overview/older-versions-getting-started/deploying-web-site-projects/logging-error-details-with-elmah-cs

    using: http://www.nuget.org/packages/Elmah.Contrib.WebApi

    Also, in Web Api you can override the OnException and just call you logger from from there (Nlog, or Explicit call to Elmah).

    public sealed class CustomExceptionFilterAttribute : ExceptionFilterAttribute
    {
        public override void OnException(HttpActionExecutedContext actionExecutedContext)
        {
            yourLoggingMechanism.Log(actionExecutedContext.Exception);
            base.OnException(actionExecutedContext);
        }
    }
    

    Then in your WebApiConfig class, in the Register method add:

    config.Filters.Add(new CustomExceptionFilterAttribute());
    

    These are just some ideas, deciding where to log to (i.e. to a Db or maybe Windows Event Viewer etc) really depends on what you're doing and your decision on this may influence whether you want to go with something like Nlog or not.