我目前正在从事的项目使用 Enterprise Libraries V3.1 框架进行日志记录。
我需要获取生成的日志文件并在特定点将其归档。内置的跟踪侦听器似乎在记录事件之间保持文件打开。我已经设置了一个自定义跟踪侦听器,它将附加到文件并关闭它,以便该文件始终是可移动的。
它看起来像这样(为了清楚起见,减去错误处理):
[ConfigurationElementType(typeof(CustomTraceListenerData))]
public class AlwaysClosedTextFileTraceListener : CustomTraceListener
{
private string logFilePath;
public AlwaysClosedTextFileTraceListener ()
{
logFilePath = @"hardcodedpath\log.txt";
}
public override void Write(string message)
{
using (StreamWriter logFile = File.AppendText(logFilePath))
{
logFile.Write(message);
logFile.Flush();
logFile.Close();
}
}
public override void WriteLine(string message)
{
using (StreamWriter logFile = File.AppendText(logFilePath))
{
logFile.WriteLine(message);
logFile.Flush();
}
}
public override void TraceData(TraceEventCache eventCache, string source, TraceEventType eventType, int id, object data)
{
if (data is LogEntry && this.Formatter != null)
{
WriteLine(this.Formatter.Format(data as LogEntry));
}
else
{
WriteLine(data.ToString());
}
}
}
这很好用,但我更愿意以某种方式将路径作为参数传递,而不是对其进行硬编码。
为了好玩,我尝试将它添加到构造函数中,看看会发生什么:
public LogFolderTraceListener(string logFilePath)
{
this.logFilePath = logFilePath;
}
当我这样做时,我收到一条错误消息,提示我做错了什么:
System.InvalidOperationException : The type 'AlwaysClosedTextFileTraceListener' specified for custom trace listener named 'MyLogFile' does not a default constructor, which is required when no InitData is specified in the configuration.
从这里开始,我的调查已经非常接近死胡同的反面,无限概率问题。
我在翻阅内置的源代码时发现了这个RollingTraceListener
- 有一个类
RollingFlatFileTraceListenerData : TraceListenerData
似乎包含传递给构造函数的所有设置 - 在文件底部露营的
RollingFlatFileTraceListenerData
是RollingTraceListenerAssembler : TraceListenerAsssembler
似乎是工厂的类 - 还有另一个类
SystemDiagnosticsTraceListenerNode : TraceListenerNode
似乎使Data
该类可呈现给配置应用程序
我的问题是:如何CustomTraceListener
使用可配置参数创建一个path
?