Logging Umbraco Api errors with a custom action filter
Table of contents
How to log exceptions in Umbraco Api Controller?
In this short article, I am going to present a simple technique for logging exceptions in UmbracoApi with ActionFilters.
There are many ways to handle exceptions in Umbraco CMS, however, logging using filters has quite a benefits:
Filter implementation
First, you should create UmbracoCustomLoggingAttribute class extending ActionFilterAttribute and override OnActionExecutedAsync method.
Now, we can access the HttpActionExecutedContext object and the inspect "Exception" property.
When the exception property is not empty - just log the exception with a built-in logger for further diagnosis.
public sealed class UmbracoCustomLoggingAttribute : ActionFilterAttribute
{
public override Task OnActionExecutedAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)
{
if (actionExecutedContext.Exception != null)
{
Current.Logger.Error<UmbracoCustomLoggingAttribute>(actionExecutedContext.Exception, "An unexpected error has occurred");
}
return base.OnActionExecutedAsync(actionExecutedContext, cancellationToken);
}
}
Using the filter
Once the attribute is ready, it's possible to decorate any UmbracoApiController with a new filter as follows:
[UmbracoCustomLogging]
public class TestUmbracoApiController : UmbracoApiController
{
public IHttpActionResult EndpointA(string id)
{
return Json("Hello from Endpoint A");
}
public IHttpActionResult EndpointB(string id)
{
return Json("Hello from Endpoint B");
}
}
Thanks to this, each error will be logged for further investigation. Naturally, you can put attributes on specific methods as you like and log errors only for chosen endpoints. When using filters, we have a choice and flexibility.
Configure log engine with appropriate logging level
Umbraco 8 allows you to easily save logs using the popular Serilog library.
To set logging level to "Error" and above with Serilog you need to:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<!-- VALID Values: Verbose, Debug, Information, Warning, Error, Fatal -->
<add key="serilog:minimum-level" value="Error" />
</appSettings>
</configuration>
Final words
In the end, good luck to you, and Happy Umbraco logging!😉