Implementing Audit Trail using Interceptor Attribute

Lets start by thinking what we want to do here. Now there could be some requirement where we want to log all the web calls that user is making so that we can log some audit trail.

Audit trail are good to keep accountability in the application so that problem and breach detection is easy and trackable.

If you want to add audit trail on a request level its 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.

Lets start by writing some code. So first we need to write that attribute or filter

audit1

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 overrideable 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.

Lets say there are some action that you don’t want to log like api calls. In those cases you can write exception classes which are simple action attribute.

audit2

To use this we will go to our LogThisAttribute and add a exclusion so that we can skip logging if he action method is decorated with DoNotLogThis attribute.

audit3

Now that we have all the building blocks setup lets 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

audit4

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 in the MVC middleware options.

NOTE: IN the action executed method one could say that I only want to login stuff on successful execution else I want to skip the logging. There is no directly 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

https://github.com/alineutron/Lab/tree/master/dotnet/HttpLogIntercepter