虽然已经晚了,但是您考虑过使用 TraceSource 吗? TraceSources 为您提供可用于记录到 System.Diagnostics 的实际对象实例(这意味着您可以按照您在问题中建议的方式使用扩展方法来扩展它们)。 TraceSources 通常在 app.config 中配置(类似于配置 log4net 记录器的方式)。您可以控制日志记录的级别以及正在侦听的跟踪侦听器。因此,您可以拥有针对 TraceSource 进行编程的应用程序代码,其可能如下所示:
public class MyClassThatNeedsLogging
{
private static TraceSource ts =
new TraceSource(MethodBase.GetCurrentMethod().DeclaringType.Name);
//Or, to get full name (including namespace)
private static TraceSource ts2 =
new TraceSource(MethodBase.GetCurrentMethod().DeclaringType.FullName);
private count;
public MyClassThatNeedsLogging(int count)
{
this.count = count;
ts.TraceEvent(TraceEventType.Information, 0, "Inside ctor. count = {0}", count);
}
public int DoSomething()
{
if (this.count < 0)
{
ts.TraceEvent(TraceEventType.Verbose, 0, "Inside DoSomething. count < 0");
count = Math.Abs(count);
}
for (int i = 0; i < count; i++)
{
ts.TraceEvent(TraceEventType.Verbose, 0, "looping. i = {0}", i);
}
}
}
您还可以使用任何名称创建 TraceSource(即不必是类名):
TraceSource ts1 = new TraceSource("InputProcessing");
TraceSource ts2 = new TraceSource("Calculations");
TraceSource ts3 = new TraceSource("OutputProcessing");
正如我之前提到的,每个 TraceSource 通常在 app.config 文件中配置,以及日志记录“级别”和应接收输出的侦听器。
对于您的扩展方法,您可以执行以下操作:
public static class TraceSourceExtensions
{
public static void TraceVerbose(this TraceSource ts, string message)
{
ts.TraceEvent(TraceEventType.Verbose, 0, message);
}
}
如果您需要对 TraceSource 进行更多自定义(例如添加其他级别),这是一篇非常好的文章,描述了如何做到这一点:
http://msdn.microsoft.com/en-us/magazine/cc300790.aspx
如果您最终在 TraceListener 内部使用 log4net(并使用它来定义命名记录器、日志记录级别等),则可能不需要配置许多 TraceSource。您甚至可能只能配置一个(其名称众所周知),或者您可以以编程方式创建一个,将其设置为记录“全部”,并将其连接到您的特定 TraceListener。
最后,您可以通过 TraceSource 实例进行日志记录,而不是通过静态 Trace 对象进行日志记录。如果配置了一个 TraceSource 并且其名称众所周知,则可以在任何位置创建有效的 TraceSource(用于日志记录),如下所示:
TraceSource ts = new TraceSource("logger");
ts.TraceEvent(TraceEventType.Information, 0, "Hello World!");
//Or, via your extension method
ts.TraceVerbose(TraceEventType.Verbose, 0, "Logged via extension method");
可能有更好的方法来完成您想要完成的任务,但这可能会让您考虑使用 TraceSource 与静态 Trace 类。