Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting trace output

I'm using TextWriterTraceListener to log diagnostics messages to a text file. However I wan't also to log a timestamp of every trace message added. Is it possible to define a kind of formatter for the listener that would automatically add timestamps?

Currently I'm adding timestamps manually on every Trace.WriteLine() call but this isn't very comfortable.

like image 895
RaYell Avatar asked Jul 23 '09 13:07

RaYell


1 Answers

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.

like image 69
Jon Skeet Avatar answered Sep 28 '22 03:09

Jon Skeet