In part one we added a log4net log to our Web API project using Unity.
In this part I will show how to create a filter that runs a function before and after a your controller method, how to inject log4net into the filter, and how to add the filter to your controllers. This part uses the same nuget packages as part one.
Step one is to create a web filter. In the example below there are three main parts.
- ILog property that is marked with a dependency attribute.
- OnActionExecuting will run before the requested controller method.
- OnActionExected will run after the requested controller method.
If this filter executed now, the Log would be NULL. So in step two let’s use Unity to build up the filter.
There are two components to using Unity to buildup the filter.
- Add a class, UnityActionFilterProvider, to your project. This will buildup the filter when called from the FilterConfig.
- Add the RegisterFilterProviders method to the FilterConfig.cs file in the Web API project.
Then you call this from RegisterGlobalFilters in the FilterConfig.cs:
At this point nothing will log until you add an attribute to any controllers you want to log. In the example below, notice the [LogActionWebApiFilter] attribute that is added to the ValuesController.
Now calling the GET method of the values controller, will cause Log4Net to write to any logs you have configured.
In part three I will show how to use Unity and AOP to log other components of your web api project.