3

I'd like to write the name of the currently running method to a log. I know I can manually type the name of each method into the string being written to the log but I'd like something more automated and reusable. I assume this can be accomplished using reflection but I don't know where to start with this.

Any suggestions or code samples? Thanks!

3 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

Comments

2

Take a look at System.Diagnostics.StackTrace class

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

Keep in mind there is a performance cost here. You'll want to be careful using this in performance sensitive code.

Comments

2

What logging framework are you using?

In log4net use %method in the pattern layout

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

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

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

That way you do not even have to take care or the method name yourself. Let the logging framework do it for you. But be aware getting the Stackframe is slow.

3 Comments

At this time, we're not using a logging framework. This is a very small project but I'm considering a FW for my next project.
In that case you have to go the new StackFrame(1, false).GetMethod() way. Assuming that you write a LogWithMethodName(string message) method for code reuse.
Thanks for pointing that out for the group. I figured it out once I ran the code only to realize the method name returned was the method containing the stacktrace code above. Not very useful when trying to reuse a method throughout my project :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.