Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 249
imak Avatar asked Jan 31 '11 14:01

imak


1 Answers

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!

like image 75
Jamby Avatar answered Oct 04 '22 19:10

Jamby