开发者

How do I access the running method's name?

I'd like to write the name of the currently running m开发者_如何学Pythonethod 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!


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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜