Logging ASP.NET Web API 2 Unhandled Exceptions to Windows Event Log

In ASP.NET MVC Applications all unhandled exceptions are logged to windows Event Log by default using ASP.NET Health Monitoring,
but in WEB API this doesn’t happen automatically.

We can directly write logs to Event Log and it means you need extra permissions.
But if you want to log exceptions to Event Log without extra permissions you should use ASP.NET Health Monitoring events.

(ASP.NET Health Monitoring is enabled by default and can be configured in web.config file.)

Here are required steps to log exceptions to Event Log using ASP.Net Health Monitoring:

internal class WebApiErrorEvent : WebRequestErrorEvent
{
protected internal WebApiErrorEvent(string message, object eventSource, int eventCode, Exception exception) : base(message, eventSource, eventCode, exception)
{
}
}
  • Create a class called EventLogExceptionLogger and implement IExceptionLogger interface.
  • Inside “LogAsync” method create an instance of WebApiErrorEvent using required parameters and call Raise() method.
internal class EventLogExceptionLogger : IExceptionLogger
{
public EventLogExceptionLogger()
{
}
public Task LogAsync(ExceptionLoggerContext context, CancellationToken cancellationToken)
{
new WebApiErrorEvent(context.Exception.Message, context.Request, 103005, context.Exception).Raise();
return Task.CompletedTask;
}
}

For source parameter we used context.Request to log request information such as Request URL, Request Path, Thread Id, User Host Address, etc.

The tricky part is that Event Codes less than 100000 are reserved for ASP.NET and by using them you get an exception, so we are using 103005 instead of 3005 that is for unhandled exceptions.

  • Register EventLogExceptionLogger to Web API HttpConfiguration services to log all exceptions that occurs in Web API methods:
config.Services.Replace(typeof(IExceptionLogger), new EventLogExceptionLogger());

(You can read more about Global Error Handling in ASP.NET Web API 2 here.)

Done, now all unhandled exceptions will be logged to Event Log.