Graviton
Graviton

Reputation: 83254

Capturing Events For Logging Purpose

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?

Upvotes: 1

Views: 193

Answers (3)

Chris James
Chris James

Reputation: 11701

Postsharp can probably help you here

Upvotes: 2

flesh
flesh

Reputation: 23935

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

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500185

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.

Upvotes: 1

Related Questions