Saturday, September 20, 2008

[.NET] How to send debug text to output (or file)

If you landed here because you want to send debug text to the output console do not worry, it's piss-easy:
// you can choose between this:
// first par: "a description of the importance of the message"
// second par: text 'category'
Debugger.Log(2, "Test", "this text in the output console - 1");
//or this
Debug.Write("this text in the output console - 2");
//or this
Debug.WriteLine("this text in the output console - 3");
//or this
Trace.Write("this text in the output console - 4");

Obviously you have to build in debug mode to see any output (if you do not know this you're a really lousy developer && human being).

If you feel sophisticated of you have some obscure reason to send your debug text not only to the output console but to a log file, you do like the following:
// clean-up the mess
//create new listener
DefaultTraceListener yourListener = new DefaultTraceListener();
//add new listener to trace
//set log file path
yourListener.LogFileName = @"log_test.txt";
//send text to console && log file like this
Trace.Write("butchers will be butchers"); 

In the case above you can use the Debug class the same way you use Trace (so you could write Debug.Write instead of Trace.Write and so on). Difference between the two is that Trace is implemented in Release build as well while Debug only in Debug mode (will be ignored if you build in Release).

P.S. Lately I've been to lazy to properly format the code - suck it up

kick it on

No comments: