Logging Umbraco Api errors with a custom action filter

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:

  • Short implementation time
  • Can be applied globally or only on individual endpoints
  • Works asynchronously

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 future diagnosis. 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:

  • Go to \config directory
  • Find serilog.config file and open the configuration file
  • Go to <appSettings> section
  • Set "serilog:minimum-level" value as "Error" (serilog supports many log levels such as Verbose, Debug, Information, Warning, Error, Fatal)
<?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

I hope you find this technique useful and you can adapt it to your needs. 

Happy Umbraco logging!😉

Comments
Leave a Comment