2011-01-31 44 views
8

我想了解Trace.WriteTrace.TraceInformation之间的区别以及应该使用哪一个。如何在跟踪中包含用户友好的时间戳

我试图配置traceOutputOptions的时间戳/日期时间。我只需要为我写的每条消息添加一个时间戳。我得到的日期时间有点麻烦,因为它会在下一行添加应用程序名称和用户友好时间戳。

ConsoleApplication1.exe Information: 0 : Hello - Trace! 
DateTime=2011-01-31T14:26:11.1538509Z 
ConsoleApplication1.exe Error: 0 : Hello - Trace! 
DateTime=2011-01-31T14:26:11.1538509Z 

所有我需要的是一样的东西

2011-01-31 11:32 Information: Hello - Trace! 
2011-01-31 11:33 Error: Hello - Trace! 

是否有App.config设置它做的任何简单的方法?

+0

`Trace.Write`及其之类是追踪(使用OutputDebugString)的“旧方法”。 “新的方式”是跟踪来源:http://msdn.microsoft.com/en-us/library/ms228989.aspx – Tergiver 2011-01-31 16:16:35

回答

1

查看codeplex上的Ukadc.Diagnostics项目。它提供了一个很好的基于System.Diagnostics的插件包,它提供了比使用内置的System.Diagnostics TraceListeners所能实现的更强大的输出格式化功能(类似于log4net和NLog)。您甚至可以编写自己的格式/标记对象,并将它们包括在输出格式化过程中。

这个库很容易使用,效果很好。

+0

感谢您的链接。包含一个简单的外部依赖关系似乎有点“沉重”。我希望能够找到一些能够实现这一目标的东西。无论如何,将在codeplex上看看这个项目。 – imak 2011-02-01 21:52:20

+0

@imak - 内置的TraceListeners没有非常灵活的格式选项。你的另一个选择是编写你自己的TraceListener,然后实现格式化,然而你会喜欢它。 – wageoghe 2011-02-01 22:02:36

10

我已经找到一个更好的方法,而无需任何其他外部依赖(我认为包括System.Diagnostics程序功能已经丰富)

我继承了我所需要的两个监听器(ConsoleTraceListener而TextWriterTraceListener会)以这样的方式

namespace MyApp 
{ 
    namespace Diagnostics 
    { 
     public class DateTimeConsoleTraceListener : ConsoleTraceListener 
     { 
      public override void Write(string message) 
      { 
       base.Write(DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss.fffffff ") + message); 
      } 
     } 

     public class DateTimeTextWriterTraceListener : TextWriterTraceListener 
     { 
      public DateTimeTextWriterTraceListener(string fileName) : base(fileName) { } 

      public override void Write(string message) 
      { 
       base.Write(DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss.fffffff ") + message); 
      } 
     } 
    } 
} 

然后,在App.config中:

<sharedListeners> 
    <add name="ConsoleListener" 
    type="MyApp.Diagnostics.DateTimeConsoleTraceListener, MyApp"> 
    <filter type="System.Diagnostics.EventTypeFilter" 
     initializeData="All"/> 
    </add> 
    <add name="FileListener" 
    type="MyApp.Diagnostics.DateTimeTextWriterTraceListener, MyApp" 
    initializeData="MyApp.log" > 
    <filter type="System.Diagnostics.EventTypeFilter" 
     initializeData="All"/> 
    </add> 
</sharedListeners> 

希望这有助于!