Thibaut

Thibaut

  • NA
  • 3
  • 1.7k

Call a function when any method from a class is called ?

Aug 27 2010 7:26 AM

Hi all,
I have a class (called MyClass), that contains about 20 misc methods, and a logging method. I want to call the logging method each time any method in that class is called, so for now, my code looks like:
class MyClass
{
   void log()
   {
      // log stuff
   }
   void method1()
   {
      this.log();
      //do stuff 1
   }
   void method2()
   {
      this.log();
      //do stuff 2
   }
 
   // ... 18 other methods that also call this.log()
}

This works fine, but it's a bit painful to have to call log() in each method, and the risk is high that if someone adds a method in there, he will forget to call it.
Is there any way I could attach an event or something, so that whenever a method from that class is called, my log() function is called ?
Any idea appreciated
Thanks,
Thibaut

Answers (2)