Umbraco Api custom logging with ActionFilters

How to log exceptions in Umbraco Api Controller?

There are many ways to handle exceptions in Umbraco CMS.

In this short article, I am going to present a very simple technique on how to log every exception using ActionFilterAttribute in UmbracoApiController.

This approach can be useful when it gets hot 🥵.

Create logging attribute

First, you should create UmbracoCustomLoggingAttribute class and intercept every action executed event.

Then, put the logic checking if the request has an exception.

When any exception object is not empty - the built-in logger just saves the details and that's it.

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);

Now, you should be able to decorate UmbracoApiController with a new filter as follows:

public class BaseUmbracoApiController : UmbracoApiController

Configure appropriate log level

In this case, we will set the level as "Error".

When using serilog:

  • 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" ?>
        <!-- VALID Values: Verbose, Debug, Information, Warning, Error, Fatal -->
        <add key="serilog:minimum-level" value="Error" />

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

Happy Umbraco logging!😉

Leave a Comment