Audit Trail Interceptor

Let's start by thinking about what we want to do here. Now there could be some requirement where we want to log all the web calls that the user is making so that we can log some audit trail.
An audit trail is good to keep accountability in the application so that problem and breach detection is easy and trackable.
If you want to add an audit trail on a request level it's really easy. You can make a filter that can intercept each web request and log that action. You can either log the action name or decorate each action name and use that to log.
Let's start by writing some code. So first we need to write that attribute or filter,
If you notice this is a very basic class that is driving from the action filter attribute. By doing that we also get access to the override methods of ActionFilterAttribute, one of which is OnActionExecuted. This method will be invoked when the action method is finished execution.
This method will be called on each web request and you can log/validate the action call here.
Let's say there are some actions that you don’t want to log like API calls. In those cases, you can write exception classes which are simple action attribute.
Audit Trail Interceptor
To use this we will go to our LogThisAttribute and add an exclusion so that we can skip logging if the action method is decorated with DoNotLogThis attribute.
Audit Trail Interceptor
Now that we have all the building blocks setup let's start using it.
I am going to use it in my basic MVC Dotnet Core web application. To use this I need to configure it in the startup.cs class,
If you notice on line 38 I added the filter to the global Filters so it should be called on every action call. This is added to the MVC middleware options.
In the action executed method one could say that I only want to login stuff on successful execution, otherwise I want to skip the logging. There is no direct way of handling that except you throw a validation exception indicating that the method execution was unsuccessful. You have to process that exception in the context and make decisions on it.
You can find the code at here.