imak
imak

Reputation: 6689

How to include user friendly timestamp in traces

I am trying to understand the difference between Trace.Write vs Trace.TraceInformation and which one should be used.

I tried to configure traceOutputOptions for timestamp/datetime. I just need an add timestamp with each message that I am writing. The datetime I am getting is a bit messay as it appends application name and less user friendly time stamp in next line like below.

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  

All I need is something like

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

Is there any easy way of setting it up in App.config doing it?

Upvotes: 12

Views: 4034

Answers (2)

Jamby
Jamby

Reputation: 1917

I've found a better approach, without the need of any other external dependency (I think that the included System.Diagnostics features are already rich)

I've inherited the two listeners that I needed (ConsoleTraceListener And TextWriterTraceListener) in this way:

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);
            }
        }
    }
}

Then, in 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>

Hope this helps!

Upvotes: 13

wageoghe
wageoghe

Reputation: 27608

Have a look at the Ukadc.Diagnostics project at codeplex. It provides a nice System.Diagnostics based addon package that provides more powerful output formatting capability (similar to log4net and NLog) than can be achieved with the built in System.Diagnostics TraceListeners. You can even write your own formatting/token objects and have them included in the output formatting process.

The library is easy to use and works quite well.

Upvotes: 1

Related Questions