Tip for debugging console applications in C#

Sometimes in a C# console application, you want to output text to the console window for release builds, meaning Debug.WriteLine() is out of the question.  Maybe you also want the output in some sort of log file?  It would also be handy to be able to indent the output to make it clearer what your application is doing.  This makes simple Console.WriteLine() impractical, too.

If it’s an enterprise application you’d probably look at Log4Net or similar, but if it’s just a little something you’ve knocked up, then that might be overkill so try this at the start of your application:

Trace.Listeners.Add(new TextWriterTraceListener(Console.Out));

The documentation for Trace and Debug gives more detail, but the great thing with this approach is you can now format your logging output in a more clear way:

Trace.WriteLine("Starting loop...");
Trace.Indent();
foreach (string name in names)
{
	Trace.WriteLine(name);
}
Trace.Unindent();
Trace.WriteLine("Completed loop");

Like I said, I’m not proposing it as best practice for large-scale production systems, but for those occasions when you need to see into your application without debugging it, it might prove useful.

Advertisements