jubibanna
jubibanna

Reputation: 1185

Is there an easy way to hide/show Console.WriteLines during runtime?

Question: Is there an easy way to hide/show Console.WriteLines made in a project upon running the project?

These Console.WriteLines are used to give me info while debugging, but they should be hidden when my teacher is running the code.

I've tried to make a new project library (.NET framework 4.7.2) which other projects can reference to:

//=========================== SCOPE ===========================
//   Help the programmer to show/hide Console.WriteLines
//=============================================================

// TODO: Add verbose-levels

using System;

namespace Information
{
    public static class Verbose
    {
        public static bool On { get; set; }
    }
}

And how it would look while being inside another project:

using Information;

...

if (Verbose.On) { Console.WriteLine("Text here!"); }

Upvotes: 1

Views: 301

Answers (2)

Manoj Choudhari
Manoj Choudhari

Reputation: 5634

I believe you should use the System.Diagnostic settings for this purpose.

You can add below configuration section and add console listener.

<configuration>
    <system.diagnostics>
        <sources>
            <source name="primes" switchValue="All">
                <listeners>
                    <add name="console" type="System.Diagnostics.ConsoleTraceListener" />
                </listeners>
            </source>
        </sources>
    </system.diagnostics>
</configuration>

Then use Trace.WriteLines to redirect trace output to console.

Please note that switchValue attribute controls which statements should be logged to console. If its value is set to Off nothing will be logged on console.

In C# code, you can instantiate like below:

TraceSource _source = new TraceSource();

Then while writing the log statements you can set the trace level as below:

_source.TraceEvent(TraceEventType.Information, 0, "statement to be logged");

You can understand more about log levels at this MSDN page.

Please find examples at this MSDN page.

Upvotes: 4

Luke Vo
Luke Vo

Reputation: 20748

You have plenty of choices here:

  • Quick way: I assume you are doing a quick and simple homework, I would simply use Debug.WriteLine as suggested by Damien_The_Unbeliever. The output will be in the Output window during Debug only. Alternatively, you can use #if directive.

  • Proper Tracing using Trace and Trace Listener.

  • Overkill way: use a logging framework like NLog or log4net.

Upvotes: 2

Related Questions