Skip to main content
 首页 » 编程设计

c#之获取当前类和方法名称会降低性能吗

2024年02月05日10zhenyulu

我有一个日志记录类,它创建了一个 log4net 实例,我可以在我的代码中的任何地方调用它。我还有一种方法可以找出调用者的类名和方法名。这是我的方法:

private static string CurrentMethod() 
{ 
    StackTrace stackTrace = new StackTrace(); 
    MethodBase method = stackTrace.GetFrame(2).GetMethod(); 
    string cn = method.ReflectedType.Name; 
    string mn = method.Name; 
 
    string output = "[" + cn + "." + mn + "]"; 
    return output; 
} 

我找到了这些文章:link1 , Link2 , Link3 , Link4和其他许多人,但他们都没有讨论效率和性能。 现在我有两个问题: 1-我可以在一个大项目中使用这种方法吗(一秒钟内大约有 1000 个请求)?我的意思是这对项目的效率和性能有多大影响? 2- 有没有更好的方法来编写上述方法?

这也是我的日志记录类(class)的一部分。我想它可以帮助:

public static class Tools_Log 
{ 
    private static ILog logger; 
 
    public static ILog GetLogger() 
    { 
        return logger ?? (logger = CreateLogger()); 
    } 
    private static ILog CreateLogger() 
    { 
        //Some log4net initialization 
        return LogManager.GetLogger("WebService"); 
    } 
 
    private static string CurrentMethod() 
    { 
        StackTrace stackTrace = new StackTrace(); 
        MethodBase method = stackTrace.GetFrame(2).GetMethod(); 
        string cn = method.ReflectedType.Name; 
        string mn = method.Name; 
 
        string output = "[" + cn + "." + mn + "]"; 
        return output; 
    } 
 
    public static string MessageForLogFile(string message, string exeption, double time) 
    { 
        string currentMethod; 
        string executiontime; 
        string consumer; 
        string body; 
        string output; 
 
        currentMethod = CurrentMethod(); 
        executiontime = ExecutionTime(time); 
        body = BodyForLog(message, exeption); 
        consumer = Consumer(); 
 
        output = OutPut(currentMethod, executiontime, consumer, body); 
        return output; 
    } 
} 

我这样调用日志类:

Tools_Log.GetLogger().Info(Tools_Log.MessageForLogFile("some text", "some text", execution time)); 

谢谢。

请您参考如下方法:

是的,反射(reflection)总是一个较慢的过程。如果你想要方法的名称,你可以使用 CallerMemberNameAttribute 很容易地得到它。 .添加一个默认值为空的字符串参数,并将该属性应用于它,编译器将为您发送名称。

此外,如果您正在寻找快速日志记录,请查看 ETW 而不是 Log4Net。

此处:https://msdn.microsoft.com/en-us/library/windows/desktop/bb968803(v=vs.85).aspx

这里:http://blogs.msdn.com/b/vancem/archive/2012/07/09/logging-your-own-etw-events-in-c-system-diagnostics-tracing-eventsource.aspx

编辑:
至于您在评论中提出的问题,不幸的是,您至少无法直接获得方法 2 级别的名称。 CallerMemberName 基本上只是语法糖,它告诉编译器获取调用成员的名称,并将其放在参数中,因此它在单个级别上工作。但是,由于它依赖于默认参数来执行此操作,如果您手动发送参数,则 CallerMemberName 功能不适用,因此您可以执行如下操作:

public void UserMethod() 
{ 
    IntermediaryMethod(); 
} 
 
public void IntermediaryMethod([CallerMemberName] caller = "") 
{ 
    LogMethod(caller) 
} 
 
public void LogMethod([CallerMemberName] caller = "") 
{ 
    // Log... 
} 

如果你自己传递一个值,它不会被覆盖,所以做这样的事情将允许你从 2 层以上获取调用者的名字,同时保留一个层的功能。