问题描述
我正在使用 TextWriterTraceListener
将诊断消息记录到文本文件中。但是,我也不记录添加的每个跟踪消息的时间戳。可以为侦听器定义一种能自动添加时间戳的格式化程序?
I'm using TextWriterTraceListener
to log diagnostics messages to a text file. However I wan't also to log a timestamp of every trace message added. Is it possible to define a kind of formatter for the listener that would automatically add timestamps?
目前,我在每个 Trace上手动添加时间戳。 WriteLine()
调用,但这不是很舒服。
Currently I'm adding timestamps manually on every Trace.WriteLine()
call but this isn't very comfortable.
推荐答案
我建议你使用,它具有更多的可定制性。
I suggest you use Log4Net instead, which has a lot more customizability.
或者,您可以编写自己的 TraceListener
实现,将时间戳放在您的身上。您可以甚至可以从 TextWriterTraceListener
中导出,并覆盖写入
和 WriteLine
:
Alternatively you could write your own TraceListener
implementation which put the timestamps on for you. You may even be able just derive from TextWriterTraceListener
and override Write
and WriteLine
:
public override void Write(string x)
{
// Use whatever format you want here...
base.Write(string.Format("{0:r}: {1}", DateTime.UtcNow, x));
}
public override void WriteLine(string x)
{
// Use whatever format you want here...
base.WriteLine(string.Format("{0:r}: {1}", DateTime.UtcNow, x));
}
这篇关于格式化跟踪输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!