2010-01-16

Get calling method's name automatically in dotnet

Way too many times have I written

void MyFunction( int aNumber)
{
MyHomemadeLogClass.Logg( "MyFunction", "aNumber=" + aNumber.ToString());
...
}
to get logging functionality.

It would be so nice to just write

void MyFunction( int aNumber)
{
MyHomemadeLogClass.Logg();
...
}
It is no hard to do. Use reflection to get the call stack to get to the method and the parameters. Convert all this to a readable string.
Unfortunately it is not that easy to log the contents of the parameters, one has to get into some sort of debugger area to do that.

class ReflectionUtility
{
private static System.Reflection.MethodBase GetCallingMethod()
{
return new System.Diagnostics.StackTrace().GetFrame(2).GetMethod();
}
public static string GetCallingMethodFullNameReturnParametertypes()
{
return MethodFullNameReturnParametertypes(GetCallingMethod());
}
private static string MethodFullNameReturnParametertypes(System.Reflection.MethodBase method)
{
return string.Format("{0} {1}.{2} ({3})",
((System.Reflection.MethodInfo)method).ReturnType, // System.Void, System.Int32 etc.
method.DeclaringType.FullName, // MyNamespace.MyClass.
method.Name, // MyMethod.
string.Join(",", method.GetParameters().Select(p => p.ParameterType.ToString() + " " + p.Name).ToArray()) // () or (int) or (int,string) etc.
);
}
}
To use this in a Logging class one must implement a GetCallingCallingMethod or even worse, but it would make this example hard to read.

One can use the Conditional attribute to avoid the call when not debugging.

I also put the code on pastebin to make the copy-paste easier. (I have yet to find a good way to present code.)

No comments: