简体   繁体   English

登录C#:获取类/方法名称性能

[英]Logging in C#: Getting the class/method name performance

I've recently been tasked with adding logging statements to every method call in a solution. 我最近的任务是将日志语句添加到解决方案中的每个方法调用。 These log entries need to contain the class and method name. 这些日志条目需要包含类和方法名称。

I know I can use MethodBase.GetCurrentMethod() and the StackFrame.GetMethod() methods. 我知道我可以使用MethodBase.GetCurrentMethod()StackFrame.GetMethod()方法。 Which is better? 哪个更好? Is there a better (or more performant) way to get the class and method name? 是否有更好(或更高性能)的方法来获取类和方法名称?

I have two suggestions: 我有两个建议:

  1. Use ready-made AOP frameworks (like http://www.sharpcrafters.com/ ) they can handle this easily 使用现成的AOP框架(如http://www.sharpcrafters.com/ ),他们可以轻松处理这个问题
  2. Do a custom prebuild action where you replace some kind of stub in the beginning of every method: 执行自定义预构建操作,在每个方法的开头替换某种存根:

    void PerformSomeAction() { //PUT_LOGGING_HERE } void PerformSomeAction(){// PUT_LOGGING_HERE}

then in custom tool replace those stubs with method names. 然后在自定义工具中用方法名称替换那些存根。 This is guaranteed fastest method, but requires some investments. 这是保证最快的方法,但需要一些投资。

Well, the best/fastest way is to include a string in every function. 嗯,最好/最快的方法是在每个函数中包含一个字符串。 That may not appear the most practical solution, but MethodBase.GetCurrentMethod() requires coding inside every method that using it anyway. 这可能不是最实用的解决方案,但MethodBase.GetCurrentMethod()需要在每个使用它的方法内编码。 ie You can write 即你可以写

string funcName = "MyClass.MyFunction(int, int)";

or you can write 或者你可以写

string funcName = MethodBase.GetCurrentMethod().Name

Now, if you want to get the Name of the function that called the current function (ie, you want to do this in one spot in your logging function), then your only option is reading through the StackFrame. 现在,如果您想获取调用当前函数的函数的名称(即,您希望在日志记录函数中的一个位置执行此操作),那么您唯一的选择是读取StackFrame。

this.getType().toString() should get you the class this.getType().toString()可以让你上课

About the method it seems stackFrame and methodbase are the most obvouis solutions, I cant comment on which is more efficient. 关于方法看起来stackFrame和methodbase是最明显的解决方案,我不能评论哪个更有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM