【发布时间】:2015-08-25 08:18:28
【问题描述】:
我有一个日志记录类,它创建了一个 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- 上面的方法有更好的写法吗?
这也是我的日志类的一部分。我想它会有所帮助:
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));
谢谢。
【问题讨论】:
-
如答案中所述,新的 CallerMemberNameAttribute 是救生员。如果由于某种原因您卡在较旧的 .net 框架版本中,则获取特定的堆栈帧应该比获取整个堆栈跟踪具有更好的性能,尤其是对于较大的堆栈(例如
new StackFrame(2,false).GetMethod();) -
您可能还需要考虑编译器可能会优化/内联您的某些方法调用,并且您看到的堆栈跟踪或
CallerMemberName可能与您在调试时看到的不匹配。
标签: c#