tags:

views:

92

answers:

3

When an application is launched, I need to know for certain methods when they are fired. How to do this using attributes and AOP techniques?

The simplest way is to record the time in the event method such as this:

private void Page_load()
{
  DateTime dt = DateTime.Now;
}

And save the Datetime into a database. But this is definitely not desirable as doing this will leave the method will a lot of cross cutting functions, making the maintenance job harder. I am thinking about using attributes to solve this problem. PostSharp seems to be a good candidates here as it can intercept method calls and do whatever pre and post processing you want. But one thing that is clearly lacking is that it can't handle events without me writing a lot of custom code.

Is there any framework that can handle events naturally?

+1  A: 

You don't need to have a separate method for every event you want to log like this.

Write a single method to do the logging:

public static void LogEventRaised(string event)
{
    ...
}

then subscribe to the events using an anonymous method:

Load += delegate { LogEventRaised("Load") };

Yes, it's imperative rather than declarative, and repeats the event name - but it's still pretty compact. You could attach handlers to all events using reflection, but that would probably be overkill.

Jon Skeet
+1  A: 

The Spring framework has an Aspect Oriented Programming module that provides logging support.

flesh
+2  A: 

Postsharp can probably help you here

qui
Post sharp is one of the easiest .net AOP frameworks. Glad people like it. +1 to you
Perpetualcoder
Thanks, but unfortunately PostSharp doesn't support events:http://www.postsharp.org/forum/postsharp-laos/equivalent-oneventboundaryaspect-t617.html
Ngu Soon Hui