Tip #83: Did you know... You can get the name of the calling method from the stack using reflection?

Nearly every program needs a logger to log events, errors and exceptions. Sometimes it is also useful to log the name of the method that logged the event. The easiest way to do that is to make the log method take both the calling method name and event as parameters:

[C#]

 void Log(string callingMethodName, string eventMessage) 

{   
   Console.WriteLine("Event logged by " + callingMethodName);  
   Console.WriteLine("Event: " + eventMessage); 

}

In this case, every method will need to specify its name when calling Log(). In addition to this, the developer will have to watch if methods name change. However, there is a cleaner way to get the name of the calling method. It can be extracted from the stack. Since the method on top of the stack is the method that is currently being executed, the calling method will be right below it. Thus, by instantiating StackTrace (don’t forget to include System.Diagnostics) and getting the frame with index 1 will result in getting a StackFrame that corresponds to the call from the calling method. Finally, reflection can be used to get method name.

 using System.Diagnostics;
    
void Log(string eventMessage)
{ 

   Console.WriteLine("Event logged by " + (new StackTrace()).GetFrame(1).GetMethod().Name); 

   Console.WriteLine("Event: " + eventMessage);

}
 

Katerina Rohonyan
SDET, IIS Team