Reputation: 3067
I have a code base with hundreds of classes and methods. For debugging purposes, I would like to add automatically a line of code on the top each method that prints the method name and the name of the file containing the method . Is there a simple way to achieve this using visual studio ?
Upvotes: 0
Views: 94
Reputation: 1576
I'm not sure if there is a way to automatically have the code added to each method, but I can give you something I wrote that you can use if you go the route of manually adding in a line. I wrote the code below that uses System.Diagnostics to get the name of the class and method - I think I originally cribbed it from an MSDN example.
public static string GetClassAndMethod() {
string className = "", methodName = "";
try {
StackTrace st = new StackTrace(true);
StackFrame sf = st.GetFrame(1);
string filename = sf.GetFileName();
className = filename.Substring(filename.LastIndexOf("\\") + 1);
className = className.Substring(0, className.IndexOf("."));
methodName = sf.GetMethod().Name;
} catch (Exception ex) {
className = "UnknownClass";
methodName = "UnknownMethod";
}
return className + "." + methodName;
}
I've put this in a class called Diag and can then call it when I need, such as within a Trace statement like so:
Trace.Write(Diag.GetClassAndMethod());
I also wrote separate GetClass() and GetMethod() ones to just get the class or method. The advantage of combining it with Trace is it only gets called when tracing is enabled.
Hope this helps.
Upvotes: 2
Reputation: 2857
You can use AOP to log when you start and/or finish a method execution.
I advise you to take a read about Spring.Net.
Upvotes: 2