I'd like to sprinkle some print statements in my code to show where I am and print important values to a console window.
How do I do that, but then be able to turn it off for the release version?
I'd like to sprinkle some print statements in my code to show where I am and print important values to a console window.
How do I do that, but then be able to turn it off for the release version?
All calls to System.Diagnostics.Debug.Print()
will be removed when you switch to a release version.
Look at the System.Diagnostics.Debug and System.Diagnostics.Trace classes.
Use Log4net with logging at debug level in release and warn or error level in production.
Benefit to this is that you can turn logging back on in the release environment if you have problems there that you can't recreate in development.
[EDIT] FWIW, I find that I do a LOT less debug logging now that I use Test-Driven Development. Most of my logging is of the warn/error variety.
I use: System.Console.WriteLine()
#if DEBUG
System.Console.WriteLine("Message");
#endif
Debugging and tracing are related but distinct activities. The System.Diagnostics
namespace supports them both.
Use Debug.Write/WriteLine
to write debugging messages to a log file. (And to the Output window.) Use Debug.Assert
, well, pretty much everywhere. All code that you write using the Debug
class is removed before complilation if you don't define a DEBUG symbol in your code - this is done by default in the options for Debug and Release configurations.
Use Trace.Write/WriteLine
to write tracing messages. These methods are functionally equivalent to the methods of the Debug class; the difference is that they are removed if you don't define a TRACE symbol in your code.
The Debug and Trace classes also have a whole slightly-cumbersome infrastructure of other classes, like TextWriterTraceListener
, that allow you to do spiffy things like change the output of your trace log from a local file on disk to a web service (or to nothing) just by editing the application configuration file. My favorite trick is to implement a TextWriter
that can write text to a TextBox
, and use that to redirect all the debug and trace output to the UI.
You can also set flags in the app config file that the WriteIf
and WriteLineIf
methods respect, but in my experience those get pretty unwieldy.
I find that in general, I'm happier if I build my own static class to wrap the Trace
methods. That lets me do things like turn tracing on and off in the UI just by setting a property of my Trace
class.
Finally: if you need to instrument your app to do something like trace when every method begins and ends, the tool to use for that is the miraculous PostSharp.
You can also look into Aspect Oriented Programming solutions. They do this sort of thing really well. Look at PostSharp as a good implementation. Their sample code usually contains an example of exactly what you're looking for.