Logging to elmah.io from Web API
Web API provides its own mechanism for handling errors, why ELMAH’s modules and handlers don't work there. Luckily, Richard Dingwall created the Elmah.Contrib.WebApi NuGet package to fix this. We've built a package for ASP.NET Web API exclusively, which installs all the necessary packages.
To start logging exceptions from Web API, install the Elmah.Io.WebApi
NuGet package:
Install-Package Elmah.Io.WebApi
dotnet add package Elmah.Io.WebApi
<PackageReference Include="Elmah.Io.WebApi" Version="5.*" />
paket add Elmah.Io.WebApi
During the installation, you will be asked for your API key (Where is my API key?) and log ID (Where is my log ID?).
Add the following code to your WebApiConfig.cs
file:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// ...
config.Services.Add(typeof(IExceptionLogger), new ElmahExceptionLogger());
// ...
}
}
The registered IExceptionLogger
intercepts all thrown exceptions, even errors in controller constructors and routing errors.
Add the following code to your Global.asax.cs
file:
protected void Application_Start()
{
// ...
GlobalConfiguration.Configuration.Filters.Add(new ElmahHandleErrorApiAttribute());
// ...
}
In this case you register a new global filter with Web API. The downside of this approach is, that only errors thrown in controller actions are logged.
All uncaught exceptions in ASP.NET Web API are now logged to elmah.io
Logging from exception/action filters
It's a widely used Web API approach, to handle all exceptions in a global exception/action filter and return a nicely formatted JSON/XML error response to the client. This is a nice approach to avoid throwing internal server errors, but it also puts ELMAH out of the game. When catching any exception manually and converting it to a response message, errors won't be logged in elmah.io.
To overcome this, errors should be logged manually from your global exception/action filter:
public class NotImplExceptionFilterAttribute : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext context)
{
ErrorSignal.FromCurrentContext().Raise(context.Exception);
// Now generate the result to the client
}
}
This article was brought to you by the elmah.io team. elmah.io is the best error management system for .NET web applications. We monitor your website, alert you when errors start happening, and help you fix errors fast.
See how we can help you monitor your website for crashes Monitor your website