以下代码:
static void Main(string[] args)
{
TraceSource ts = new TraceSource("MyApplication");
ts.Switch = new SourceSwitch("MySwitch");
ts.Switch.Level = SourceLevels.All;
ts.Listeners.Add(new TextWriterTraceListener(Console.Out));
ts.TraceInformation("Hello World");
Console.ReadKey();
}
生成以下输出:
MyApplication Information: 0 : Hello World
跟踪输出开头的“MyApplication Information: 0 :”部分来自 TraceSource 类本身。
但是,我需要在行的开头有一个时间戳,我也想将“信息”更改为“信息”。
有什么方法可以让跟踪输出更自由,这样我就可以将其配置为:
13:03:00 - MyApplication Info: Hello World
我尝试了几个小时,但没有成功。无论我做什么,在输出行的开头,总是有这个常量预定义的“MyApplication Information: 0 : Hello World”输出。
MSDN 文档也没有透露任何有用的信息。
最佳答案
也迟到了,但万一有人降落在这里...
我喜欢保持简单。我在我的 App.cs 中使用一个静态 Trace 方法,它与我在启动时创建的单个 TraceSource 相关联。这允许我在我的应用程序中访问它并保持 app.config 简单:
public static void Trace(TraceEventType eventType, string message)
{
if (_TraceSource.Switch.ShouldTrace(eventType))
{
string tracemessage = string.Format("{0}\t[{1}]\t{2}", DateTime.Now.ToString("MM/dd/yy HH:mm:ss"), eventType, message);
foreach (TraceListener listener in _TraceSource.Listeners)
{
listener.WriteLine(tracemessage);
listener.Flush();
}
}
}
我的 app.config 条目:
<system.diagnostics>
<sources>
<source name="mytracesource" switchValue="All">
<listeners>
<add name="mytracelistener"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="trace.log">
</add>
</listeners>
</source>
</sources>
</system.diagnostics>
关于c# - System.Diagnostics.TraceSource 中跟踪输出的格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13288783/