Best practices for logging and tracing in .NET

Posted by Levidad on Programmers See other posts from Programmers or by Levidad
Published on 2011-03-11T12:41:36Z Indexed on 2011/03/11 16:18 UTC
Read the original article Hit count: 389

Filed under:
|

I've been reading a lot about tracing and logging, trying to find some golden rule for best practices in the matter, but there isn't any. People say that good programmers produce good tracing, but put it that way and it has to come from experience.

I've also read similar questions in here and through the internet and they are not really the same thing I am asking or do not have a satisfying answer, maybe because the questions lack some detail.

So, folks say that tracing should sort of replicate the experience of debugging the application in cases where you can't attach a debugger. It should provide enough context so that you can see which path is taken at each control point in the application.

Going deeper, you can even distinguish between tracing and event logging, in that "event logging is different from tracing in that it captures major states rather than detailed flow of control".

Now, say I want to do my tracing and logging using only the standard .NET classes, those in the System.Diagnostics namespace. I figured that the TraceSource class is better for the job than the static Trace class, because I want to differentiate among the trace levels and using the TraceSource class I can pass in a parameter informing the event type, while using the Trace class I must use Trace.WriteLineIf and then verify things like SourceSwitch.TraceInformation and SourceSwitch.TraceErrors, and it doesn't even have properties like TraceVerbose or TraceStart.

With all that in mind, would you consider a good practice to do as follows:

  • Trace a "Start" event when begining a method, which should represent a single logical operation or a pipeline, along with a string representation of the parameter values passed in to the method.
  • Trace an "Information" event when inserting an item into the database.
  • Trace an "Information" event when taking one path or another in an important if/else statement.
  • Trace a "Critical" or "Error" in a catch block depending on weather this is a recoverable error.
  • Trace a "Stop" event when finishing the execution of the method.

And also, please clarify when best to trace Verbose and Warning event types. If you have examples of code with nice trace/logging and are willing to share, that would be excelent.

Note: I've found some good information here, but still not what I am looking for: http://msdn.microsoft.com/en-us/magazine/ff714589.aspx

Thanks in advance!

© Programmers or respective owner

Related posts about .NET

Related posts about logging