Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET: Is there a way to know which method the currently executing code is in? (for logging class)

Tags:

c#

.net

logging

I'm writing a logging class in C# and would like to add the method from which the log call was made. Doing this manually isn't too attractive. Is there a way to know which method the currently executing code is in?

Thanks in advance for your awesomeness...

Gregg

EDIT: Using MethodBase...

 System.Reflection.MethodBase thisMethod = System.Reflection.MethodBase.GetCurrentMethod();
 Console.WriteLine("This method is: " + thisMethod.Name);
like image 504
MrGreggles Avatar asked Dec 03 '22 13:12

MrGreggles


1 Answers

Use MethodBase.GetCurrentMethod:

Returns a MethodBase object representing the currently executing method.

The MethodBase type has a Name property that is the name of the currently executing method as a string.

As a side note, perhaps you should look into existing logging frameworks so that you don't have to reinvent the wheel.

like image 125
Andrew Hare Avatar answered Mar 22 '23 23:03

Andrew Hare