Getting the name of the calling method

Basically, I have a web service that I am trying to include in the log. To do this, I created a class with a logging method. I set the class in the service and then call the logging method in each of the web methods.

I am trying to find a way to get the name of the method that called the loggong method

Public sub tstmethod log_object.log_method end sub 

in this case, the return name I'm looking for is "tstmethod"

Everywhere I saw said to use

 Dim stackframe As New Diagnostics.StackFrame Return stackframe.GetMethod.Name.ToString 

Or use

 Dim stackframe As New Diagnostics.StackFrame Return stackframe.GetMethod.DeclaringType.FullName 

which I call inside the logging method

getmethod.name.tostring returns the name of the logging method

getmethod.declaringtype.fullname returns the name of the logging class

no matter what i do, i can't find a way to get the name of the method that called the logging method in this case "tstmethod"

+4
source share
8 answers

You need to create a StackFrame instance using the appropriate constructor. For instance,

 Dim stackframe As New Diagnostics.StackFrame(1) 

skips one stack frame (the logging method itself) and receives a frame for the caller of this method.

However, if at all possible, I highly recommend using a standard logging mechanism such as log4net .

+10
source

I think the above statement can be done in one line:

 MsgBox((New System.Diagnostics.StackTrace).GetFrame(1).GetMethod.Name) 

This displays the message box as with the name of the invocation method.

+8
source

Vb.net

 System.Reflection.MethodBase.GetCurrentMethod.Name() 
+4
source

You should be able to get this from a StackFrame using a constructor telling how many frames should go along the chain, so getting the parent will use 1 (the frame is zero, so 0 is the current method):

 Dim stackTrace as New Diagnostics.StackFrame(1) Return stackTrace.GetMethod.Name 
0
source

I highly recommend ELMAH

0
source

I use this code to get the calling method

 string methodName = new StackFrame( 1, true ).GetMethod().Name; methodName = " [" + methodName + "]"; return methodName; 

don't forget to add a namespace Diagnostics

0
source

I add a call form as the first parameter for all routines and functions, for example, functionfunction (me, para1, para2 ......) so that I can identify the calling form and use its name or text in the called procedure

0
source

Do not try to use a stackframe. It will only work in debug mode, which is a killer for application speed.

You cannot get this information in Release mode, you should consider changing the design and adding a parameter.

-2
source

All Articles