views:

482

answers:

4

Im a little confused over how to use the .NET Trace and Debug classes.

Why would you bother using Trace instead of Debug?

Trace.TraceError() Trace.TraceInformation() Trace.Assert()

Debug.WriteLine() Debug.Assert()

Also, I understand that Debug statements are ignored when your in Release config mode, but If trace statements apply all the time, how does this affect performance?

A: 

You can turn both on and off independantly with a compiler switch, if you go to the build page of your project properties, you have some checkboxes there.

The rule of thumb for me is that I use debug for actual debugging information, i.e. the value of variable x at this point is ... etc, and Trace for tracing flow of control through my app (more spam like).

Tim Jarvis
A: 

As you say, Trace calls are only executed when you are in release mode. Compiling in Release mode has some performance benefits that you may want in the end application, and there may be other reasons you want to turn on Release mode. However, there may be times when you want to record information to the trace console, which can be viewed with applications such as SysInternal's DbgView. These are typically messages that you don't necessarily want to send to a log output, or which you always want to have available for debugging purposes even if the user has turned off logging.

You certainly wouldn't want to send a lot of information to the Trace console as it does impose a performance penalty, but some critical information might be appropriate.

Michael Bray
+2  A: 

At the simplest level, they have different compilation switches - i.e. Debug.WriteLine etc is only toggled if you have the DEBUG compilation symbol (not common for release builds), where-as Trace.WriteLine will usually be included even in release builds.

The Trace route has customizable trace-listeners, that can be plumbed in via configuration; Debug generally goes to a debugger as the listener. Of course, there are 3rd-party trace systems that offer much more flexibility.

Marc Gravell
A: 

I've tended to use Trace (with an associated TraceSwitch) for logging efforts in release environments -- a quick tweak of the app.config can then give different levels of logging without the need for recompilation (which might make a problem go away anyway) or the the need to attach a debugger. Especially handy for issues that only occur on customer's machines for whatever reason -- I've used this to successfully dump logging out of an FTP class (back in the old Framework 1.1 days) to help diagnose network transfer issues between two companies

Rowland Shaw