Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to switch between Debug.WriteLine() at debug and Console.WriteLine() in release mode in .NET/C#

Tags:

c#

.net

In my C# code I would like to wrap Debug.WriteLine() and Console.WriteLine() into one function, so that it targets the debug window in debug mode and console in release mode. What is the best way to achieve it? I am new to C#. Thanks.

like image 905
t.g. Avatar asked Jan 15 '23 07:01

t.g.


1 Answers

Look at the System.Diagnostics.Trace class.

Trace includes a WriteLine() method similar to that on the Debug and Console classes, and supports attaching/detaching various listeners at runtime or via config file, such as the ConsoleTraceLister, DefaultTraceListner (for Debug), the TextWriterTraceListener (for files), the EventLogTraceListener, or you can create your for writing to places like database tables or syslogd aggregators.

You can just about change every current call to Debug or Console to use Trace instead, and just set the listeners you want to use. Note that the Trace methods are missing a few formatting features, but I think the configurable output source more than makes up for it.

like image 70
Joel Coehoorn Avatar answered Jan 22 '23 21:01

Joel Coehoorn