.net – Why is ConsoleTraceListener not writing to a Console


Quite often, I run into items in the .NET Framework that have little or no code examples on how to use the features. On other occasions, there are plenty of examples, but none of them seem to work as prescribed.

Case in point: The System.Diagnostics.ConsoleTraceListener class.

From everything I've read and every code example I've seen, when I'm doing something like the following:

ConsoleTraceListner listener = new ConsoleTraceListener();

…I should see a console window pop up with "Yo". However, instead of that expected output, it's writing "Yo" to the Visual Studio Output where one would see normal Trace/Debug messages.

I've attempted every iteration of examples I've Googled for, including config file setup of the appropriate listener, adding the listener to the Trace.Listeners collection, custom ConsoleTraceListener types, etc. I've even just compiled to a Release version and ran the executable (which does absolutely nothing).

What the heck am I missing?

Best Solution

Answering your comment to Orion Adrian's answer...

The point of a ConsoleTraceListenter or any TraceListener isn't to call it directly - it's to add it to the trace listener collection so that the rest of your code just has to call Trace.Write etc. For instance:

using System;
using System.Diagnostics;

class Test
    static void Main()
        ConsoleTraceListener listener = new ConsoleTraceListener();



    static void DoSomething()

    static void DoSomethingElse()
        // We don't want to have to pass all our logging
        // baggage down this far
        Trace.WriteLine("In DoSomethingElse");

Compile that with TRACE defined, and you've got simple logging to the console. Personally I prefer logging with a bit more "oomph" such as log4net, but tracing is a good start.