Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting the name of the calling method

Basically i've got a web service that i'm trying to put some kind of usage logging in. To do this i've created a class with a logging method. I instatiate the class on the service and then call the logging method in each of the web methods.

I'm trying to find a way of getting the name of the method that has called the loggong method

Public sub tstmethod
log_object.log_method
end sub

in this case the returned name i'm looking for is "tstmethod"

Everywhere i've seen has said to either use

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

Or to 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 cannot find a way of getting the name of the method that called the logging method in this case "tstmethod"

like image 630
zeocrash Avatar asked Sep 14 '09 11:09

zeocrash


People also ask

What is calling method in C#?

Calling a method is like accessing a field. After the object name (if you're calling an instance method) or the type name (if you're calling a static method), add a period, the name of the method, and parentheses. Arguments are listed within the parentheses and are separated by commas.

Which of the following methods can be used to get the caller of a function a funk?

To find out the caller function name, we will use the Function object's caller property. Property used: Function. caller.

What is StackTrace in C#?

A trace of the method calls is called a stack trace. The stack trace listing provides a way to follow the call stack to the line number in the method where the exception occurs. The StackTrace property returns the frames of the call stack that originate at the location where the exception was thrown.


2 Answers

You need to instantiate the StackFrame with an appropriate constructor. For example,

Dim stackframe As New Diagnostics.StackFrame(1)

will skip one stack frame (the logging method itself) and get the frame for the caller of that method.

That said - if at all possible, I'd strongly recommend using a standard logging mechanism such as log4net.

like image 113
Vinay Sajip Avatar answered Oct 08 '22 16:10

Vinay Sajip


I think the above statement can be made into one single line:

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

This will display a Message Box as with calling method name.

like image 28
Er. ßridy Avatar answered Oct 08 '22 16:10

Er. ßridy