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.

  1. ILog property that is marked with a dependency attribute.
  2. OnActionExecuting will run before the requested controller method.
  3. 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.

  1. Add a class, UnityActionFilterProvider, to your project. This will buildup the filter when called from the FilterConfig.
  2. Add the RegisterFilterProviders method to the FilterConfig.cs file in the Web API project.

Then you call this from RegisterGlobalFilters in the FilterConfig.cs:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    filters.Add(new HandleErrorAttribute());
    RegisterFilterProviders(); //<-- register your logging filter.

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.

public class ValuesController : ApiController
	// GET api/values
    public IEnumerable<string> Get()
    	return new string[] { "value1", "value2" };

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.