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

One thought on “Tip for debugging console applications in C#

  1. Thanks.
    I’m always in favour of nice simple techniques where it fits the bill just right.
    Right tool the for the right job,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s