问题描述
我目前正在开发使用内置的TraceListener一个应用程序日志库。该库将在许多项目中使用,并应提供一个简单的界面,我只需要关心的是将被写入到日志文件,而不是如何。
I'm currently developing a application logging library using the built in TraceListener. This library will be used in many projects and should offer a simple interface where I only have to care about WHAT is going to be written in into the log file, but not HOW.
通过使用反射命名空间,我可以找出哪个应用程序目前被称为日志功能(检索执行程序集名称),但我想也该函数和类调用日志函数的名称。
By using the reflection namespace, I can figure out which application currently called a log function (retrieving execution assembly name), but I want also the name of the function and class that called the logging function.
让我们说我有:
public static void LogInfo(string vLogText) {
Trace.WriteLine(
MethodInfo.GetCurrentMethod().Name
+ this.GetType().ToString() + vLogText);
}
当我从另一个项目调用(类:识别TestClass,方法:TestMethod的)
When I call from another project (class: TestClass, method: TestMethod)
Tracer.LogInfo("log this!")
我希望看到在日志中:
I expect to see in the log:
TestClass, TestMethod, log this!
而是我得到了
But instead I got
TracerClass, LogInfo, log this!
如何获得父类的方法和类的名称?
How to get the parent method and class name?
推荐答案
最新C#和VS 2012附带的(即 CallerFilePathAttribute
, CallerLineNumberAttribute
和 CallerMemberNameAttribute
),这将帮助你,如果你只能用它。
The newest C# and VS 2012 shipped with Caller Information (namely CallerFilePathAttribute
, CallerLineNumberAttribute
and CallerMemberNameAttribute
), which will help you if you can only use it.
如果你不能,你必须参考其他的答案。
If you can't, you'd have to refer to other answers.
这篇关于如何确定调用方法和类的名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!