There's probably a more elegant way to do this, but I wanted to find out which method had called the current method for logging. For example, I am calling a method in my DAO and i want to know which method from my Service layer called it...the Stack trace caught during an exception cuts me off and I could only find snippets of getting the current method name for logging purposes.
So, here's a method I drummed up to get the name of the calling-calling method:
/// <summary>
/// Helper method for getting the name of the method that got
us here
/// </summary>
/// <param
name="currentMethod"></param>
/// <returns></returns>
private
string GetPreviousMethodName(MethodBase currentMethod)
{
string
methodName = string.Empty;
try
{
StackTrace
sTrace = new System.Diagnostics.StackTrace(true);
//loop
through all the stack frames
for
(Int32 frameCount = 0; frameCount <
sTrace.FrameCount; frameCount++)
{
StackFrame sFrame = sTrace.GetFrame(frameCount);
System.Reflection.MethodBase thisMethod = sFrame.GetMethod();
//If the Type in the frame is the type that is being searched
if (thisMethod == currentMethod)
{
if (frameCount + 1 <= sTrace.FrameCount)
{
StackFrame prevFrame = sTrace.GetFrame(frameCount +
1);
System.Reflection.MethodBase prevMethod
= prevFrame.GetMethod();
methodName =
prevMethod.ReflectedType + "." +
prevMethod.Name;
//get the method and its parameter info
//then exit out of the for loop
}
break;
}
}
}
catch
(Exception)
{
//swallow
all exceptions this may encounter...this is informational and mroe for
convenience anyways
return
string.Empty;
}
return
methodName;
}