Tuesday, August 24, 2010

Finding the calling method.

I've been tasked with writing a logging component of a current application we're working on. My co-worker provided me with a snippet of code that has proven to be quite useful:

using System.Diagnostics;
using System.Reflection;
//dig through the stack trace to find the calling method
StackTrace stackTrace = new StackTrace();
//since this is two methods removed from the caller, go two deep
StackFrame stackFrame = stackTrace.GetFrame(2); 
MethodBase methodBase = stackFrame.GetMethod();
string caller = methodBase.ReflectedType + "." + methodBase.Name;

I'm getting the third frame, because the method is two deep in the logger code, but you can use whatever number necessary to get the right frame. This gives you the whole Fully.Qualified.Namespace.Class.MethodName, which can be quite useful.

No comments:

Post a Comment

Speak your mind.