Search code examples
visual-studiodebuggingconsoleconsole.writeline

Debug.WriteLine shows up only in Output window and not Console window


I am trying to clear up what gets written in the console when not debugging so for example when running in release it will not show up. So for that i use this method for the Logging that should not be shown

    public static void DebugWriteConsole(string s)
    {
        Debug.WriteLine(DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss | ") + s);
        if (Log.logger != null)
        {
            Log.Info(s);
        }
    }

And it works in that regard that it doesn't show up when running in release but the problem i have is that i run the application with -c so it runs in a console window but when running in debug the Debug.WritLine only prints into the vs output window and nothing in the console window. Anyone know how to solve this?


Solution

  • Has been explained in the Microsoft Docs in the TraceListeners collection topic

    You can use TextWriterTraceListener and specify the System.Console.Out as the stream where you want to write (or any other suitable stream instance)

    TextWriterTraceListener myWriter = new TextWriterTraceListener(System.Console.Out);
    Debug.Listeners.Add(myWriter);
    

    or just use ConsoleTraceListener.

    ConsoleTraceListener trc = new ConsoleTraceListener();
    Debug.Listeners.Add(trc);
    

    Another option is to use a pragma directive to overcome the NET Core problem

    public static void DebugWriteConsole(string s)
    {
        #if DEBUG
            Console.WriteLine(DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss | ") + s);
        #endif
        Debug.WriteLine(DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss | ") + s);
        if (Log.logger != null)
        {
            Log.Info(s);
        }
    }