Sharing my knowledge

Logging execution time using AOP

Download the source code for this tutorial from  - http://www.rajeeshcv.com/download/ProfilingSample.zip

What happens if your client complains that your application is running very slow!!! or in your load/stress testing you found that some functionalities are very slow in executing than expected. This is the time where you go for profiling the execution, to analyse the root cause of these issues.

So how we could develop a profiler, where we don’t have to wrap our normal code in a profiling code.

Before going to create the profiler, we have to decide where to put the profiled information. In this tutorial, I am making use of Log4Net as underlying layer to store this information. If you have not used Log4Net before, I suggest you to read http://www.beefycode.com/post/Log4Net-Tutorial-pt-1-Getting-Started.aspx as a starting point.

With the help of AOP (Aspect-Oriented Programming) we could do the profiling task without interrupting the actual code.

AOP is a programming paradigm in which secondary or supporting functions are isolated from the main program's business logic

Source : Wikipedia

So in order bring the AOP functionality into this application, I am going to use a third party library PostSharp  which I believe this is one of the best that is available in the market. Please download it from http://www.sharpcrafters.com/postsharp/download.

So, now we have got the basic things to start with and now let’s start coding….

Start a new solution in visual studio and add a new console application project to it. Then add the below references to the newly created project

  1. Add reference to the Log4Net.dll
  2. Add reference to PostSharp.Laos.dll and PostSharp.Public.dll (Please read http://www.sharpcrafters.com/postsharp/documentation/getting-started to get the basic installation procedure)

Next, create a new attribute class called “ProfileMethodAttribute” – this class is responsible for doing the profiling work. Make sure that you have decorated this class with “Serializable” attribute