Possible Duplicate:
How I can get the calling methods in C#
I have a Log class that’s supposed to prepend its client’s class and method to the logged message like this:
[ClientClass.ClientMethod] This is the logged message.
And I’m looking for a safe way to obtain these values from the Log class, without passing it as a parameter from the client. I have tried this so far:
var stackFrame = new StackFrame(StackFramesToSkip);
var method = stackFrame.GetMethod();
return string.Format("[{0}.{1}] {2}", method.DeclaringType.Name, method.Name, message);
However, this method doesn’t always yield the calling method. Especially when working with multiple threads.
Is there a safe way of doing this? I’m out of ideas.
Thanks!
You could use
System.Reflection.MethodBase.GetCurrentMethod()to get the current method’s name and transfer the name to a parameter, but you said you didn’t want those. Well, I know several other ways.The one time I got to do this, I added the calls by hand. I thought it would be daunting at first, but in my case, it wasn’t really that bad. I had a very limited assortment of methods to log (those that communicated with COM).