tags:

views:

103

answers:

4

I've recently been tasked with adding logging statements to every method call in a solution. These log entries need to contain the class and method name.

I know I can use MethodBase.GetCurrentMethod() and the StackFrame.GetMethod() methods. Which is better? Is there a better (or more performant) way to get the class and method name?

A: 

this.getType().toString() should get you the class

About the method it seems stackFrame and methodbase are the most obvouis solutions, I cant comment on which is more efficient.

Raynos
except this is C#, not Java, but you are generally right
Andrey
Should it be this.GetType().ToString() ? or am I missing something else
Raynos
Object.ToString() will return the class name unless ToString() was overridden.
Nate Bross
+4  A: 

I have two suggestions:

  1. Use ready-made AOP frameworks (like http://www.sharpcrafters.com/ ) they can handle this easily
  2. Do a custom prebuild action where you replace some kind of stub in the beginning of every method:

    void PerformSomeAction() { //PUT_LOGGING_HERE }

then in custom tool replace those stubs with method names. This is guaranteed fastest method, but requires some investments.

Andrey
+1, It's this type of scenario that AOP was made for.
Dan Bryant
Would that I could, I've already brought up that suggestion. Not that it isn't an excellent point.
Zachary Yates
+2  A: 

Well, the best/fastest way is to include a string in every function. That may not appear the most practical solution, but MethodBase.GetCurrentMethod() requires coding inside every method that using it anyway. i.e. You can write

string funcName = "MyClass.MyFunction(int, int)";

or you can write

string funcName = MethodBase.GetCurrentMethod().Name

Now, if you want to get the Name of the function that called the current function (i.e., you want to do this in one spot in your logging function), then your only option is reading through the StackFrame.

James Curran
If I recall right, MethodBase.GetCurrentMethod() might also return different results based on any inlining/optimization done by the compiler, so hardcoding function names may be more reliable in that sense.
Anna Lear
you can automate including function name as string at build process
Andrey