to get logging functionality.
void MyFunction( int aNumber)
{
MyHomemadeLogClass.Logg( "MyFunction", "aNumber=" + aNumber.ToString());
...
}
It would be so nice to just write
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.
void MyFunction( int aNumber)
{
MyHomemadeLogClass.Logg();
...
}
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.
To use this in a Logging class one must implement a GetCallingCallingMethod or even worse, but it would make this example hard to read.
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.
);
}
}
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:
Post a Comment