RaY*_*ell 14 c# debugging formatting trace trace-listener
我正在使用TextWriterTraceListener将诊断消息记录到文本文件中.但是,我也不想记录添加的每条跟踪消息的时间戳.是否可以为侦听器定义一种自动添加时间戳的格式化程序?
目前我正在每次Trace.WriteLine()通话时手动添加时间戳,但这不是很舒服.
Jon*_*eet 14
我建议您使用Log4Net,它具有更多的可定制性.
或者,您可以编写自己的TraceListener实现,为您设置时间戳.你可能甚至能够从刚刚获得TextWriterTraceListener和覆盖Write以及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));
}
Run Code Online (Sandbox Code Playgroud)
Eug*_*sev 13
我最近遇到过类似的情况,看起来我们现在有一个非常适合这项任务的工具,即Essential Diagnostics.您在app.config中设置了一个监听器,如下面的代码所示,然后Essential.Diagnostics.dll放入同一个文件夹.不需要重新调整.即使您不拥有源,也可以将此用于使用System.Diagnostics进行跟踪的任何应用程序.这不是很奇妙吗?
<sharedListeners>
<add name="rollingfile"
type="Essential.Diagnostics.RollingFileTraceListener, Essential.Diagnostics"
initializeData="{ApplicationName}-{DateTime:yyyy-MM-dd}.log"
convertWriteToEvent="true"
template="{DateTime:yyyy-MM-dd HH:mm:ss.fff} {Message}{Data}"
/>
</sharedListeners>
Run Code Online (Sandbox Code Playgroud)