Formatting trace output

I suggest you use Log4Net instead, which has a lot more customizability.

Alternatively you could write your own TraceListener implementation which put the timestamps on for you. You may even be able just derive from TextWriterTraceListener and override Write and WriteLine:

public override void Write(string x)
{
     // Use whatever format you want here...
     base.Write(string.Format("{0:r}: {1}", DateTime.UtcNow, x));
}

public override void WriteLine(string x)
{
     // Use whatever format you want here...
     base.WriteLine(string.Format("{0:r}: {1}", DateTime.UtcNow, x));
}

As noted in comments, this ends up with date duplication for TraceInformation, because that calls Write twice. Using a "proper" logging framework is definitely better.


You could write your own TextWriterTraceListener subclass which overrides the WriteLine methods, decorates the line, and then passes the decorated string to the base class implementation to do the actual output.


I recently encountered similar situation and it looks like now we have a tool very much fit for the task, namely Essential Diagnostics. You set up a listener in app.config like in code below and then just place Essential.Diagnostics.dll into the same folder. NO RECOMPILING IS REQUIRED. You can use this with any applications that uses System.Diagnostics for tracing, even if you do not own the source. Isn't that marvelous?

<sharedListeners>
  <add name="rollingfile"
    type="Essential.Diagnostics.RollingFileTraceListener, Essential.Diagnostics"
    initializeData="{ApplicationName}-{DateTime:yyyy-MM-dd}.log"
    convertWriteToEvent="true" 
    template="{DateTime:yyyy-MM-dd HH:mm:ss.fff} {Message}{Data}"
  />
</sharedListeners>

Or just add "DateTime" as a traceOutputOption.