Neu*_*ekt 38 .net c# reflection logging .net-assembly
我目前正在使用内置的TraceListener开发应用程序日志库.这个库将在许多项目中使用,并且应该提供一个简单的界面,我只需要关心将什么内容写入日志文件,而不是如何.
通过使用反射命名空间,我可以找出当前称为日志函数的应用程序(检索执行程序集名称),但我还想要调用日志记录函数的函数和类的名称.
比方说我有:
public static void LogInfo(string vLogText) {
Trace.WriteLine(
MethodInfo.GetCurrentMethod().Name
+ this.GetType().ToString() + vLogText);
}
Run Code Online (Sandbox Code Playgroud)
当我从另一个项目调用时(类:TestClass,方法:TestMethod)
Tracer.LogInfo("log this!")
Run Code Online (Sandbox Code Playgroud)
我希望在日志中看到:
TestClass, TestMethod, log this!
Run Code Online (Sandbox Code Playgroud)
但相反,我得到了
TracerClass, LogInfo, log this!
Run Code Online (Sandbox Code Playgroud)
如何获取父方法和类名?
Jen*_*ter 27
尝试做这样的事情:
var mth = new StackTrace().GetFrame(1).GetMethod();
var cls = mth.ReflectedType.Name;
// where 1 illustrates how deep into the stack to reflect.
Run Code Online (Sandbox Code Playgroud)
在C#5.0>中有更优雅的解决方案,但是如果您使用的是较旧的框架,则上述内容将有所帮助.
| 归档时间: |
|
| 查看次数: |
58459 次 |
| 最近记录: |