How to access the name of the running method?

I would like to write the name of the current method to the log. I know that I can manually enter the name of each method in a line written to the log, but I would like something more automated and reusable. I guess this can be achieved through reflection, but I don’t know where to start.

Any suggestions or code examples? Thank!

+3
source share
3 answers

Take a look at the System.Diagnostics.StackTrace class

System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace();
string methodName = st.GetFrame(0).GetMethod().Name;

Keep in mind that there is a performance cost. You want to be careful using this in performance-sensitive code.

+2
source

System.Reflection.MethodBase.GetCurrentMethod().Name gotta do the trick.

+4

?

log4net %

<layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%date [%thread] %-5level %logger [%ndc] - %message - Method:%method%newline"/>
</layout>

: http://logging.apache.org/log4net/release/sdk/index.html

If you use NLog 2.0, you can use $ {callsite} in your layout. See: https://github.com/nlog/nlog/wiki/Callsite-Layout-Renderer

That way, you don’t even need to care, or the name of the method yourself. Let the framework do it for you. But keep in mind that the stackframe is slow.

+2
source

Source: https://habr.com/ru/post/1773353/


All Articles