.NET: Is there a way to find out which method the current executable code is in? (for the logging class)

I am writing a log class in C # and would like to add the method from which the log call was made. Doing this manually is not too attractive. Is there a way to find out which method is in the current executable code?

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); 
+4
source share
2 answers

Use MethodBase.GetCurrentMethod :

Returns a MethodBase object representing the current executable method.

The MethodBase type has a Name property, which is the name of the current executable method as a string.

As a side note, you might want to study the existing logging framework so you don't have to reinvent the wheel.

+13
source

I would advise against this.

  • The logging method should usually have the lowest possible overhead, so you can call it from performance-sensitive code.

  • An attachment means that you cannot get the correct method, especially in release builds.

  • When registering exceptions, you will have a stack trace as part of the exception, which will give you a call stack at the time of the exception. When registering a normal thread, it is much less useful to know the name of the method.

+4
source

All Articles