Tracing of WCF services - code example

Tracing can be very beneficial especially when the application has already been deployed and we need to figure out why things do work. Useless errors of type HTTP 500 don't give any meaningful results, so I decided to use System.Diagnostics to help me track down the errors.

Logging

There are two important (and very simplifed definitions):

  1. TraceSource - is used to add messages
  2. TraceListener - is used to output those messages to a file
Note: It is the name that is used to identify the TraceSource, so the same TraceSource can be used across different classes and even different projects, just give them the same name.

Now in order to add a new message:

There are different types messages that can be outputted.

There are several really cool articles that describe how to this functionally effectively.

Outputting

Now we need a trace listner to save our output to a given location

This should save all the files to c:logsservice.svclog. I generally like to keep a backlog of these. It proves useful if you want to find a pattern in behaviour. Microsoft doesn't seem to have implemented something like this. It is beneficial to implement your own TraceListener. Well... It has already been done by hundreds of people. A good example you can find here: http://www.codeproject.com/Articles/30956/A-Rolling-XmlWriterTraceListener

Enumerated value Integer value Type of message displayed (or written to a specified output target)
Off 0 None
Error 1 Only error messages
Warning 2 Warning messages and error messages
Info 3 Informational messages, warning messages, and error messages
Verbose 4 Verbose messages, informational messages, warning messages, and error messages