Add Timestamp to Trace.WriteLine()

Soren Mikkelsen picture Soren Mikkelsen · May 14, 2009 · Viewed 36.8k times · Source

In my C# .NET application I have an issue with the Trace.WriteLine()-method. I uses this method alot, and want to add a TimeStamp every time I use it.

Instead of Trace.WriteLine(DateTime.Now + " Something wrong!"), is there a solution where the DateTime is on default?

Answer

user38309 picture user38309 · May 15, 2009

Via code

You can configure the TraceOutputOptions flags enum.

var listener = new ConsoleTraceListener() { TraceOutputOptions = TraceOptions.Timestamp | TraceOptions.Callstack };
Trace.Listeners.Add(listener);

Trace.TraceInformation("hello world");

This does not work for Write and WriteLine, you have use the TraceXXX methods.

Via app.config

This can also be configured in your App.config with a somewhat equivalent and using TraceSource:

<configuration>
  <system.diagnostics>
    <trace autoflush="true">
      <sources>
        <source name="TraceSourceApp">
          <listeners>
            <add name="myListener" type="System.Diagnostics.ConsoleTraceListener" traceOutputOptions="Timestamp" />
          </listeners>
        </source>
      </sources>
    </trace>
  </system.diagnostics>
</configuration>

And in code you can:

private static TraceSource mySource =   
        new TraceSource("TraceSourceApp");
static void Main(string[] args)
{
  mySource.TraceInformation("hello world");
}