System.Diagnostics.Trace, simplest possible programmatic configuration

628426 picture 628426 · Nov 9, 2013 · Viewed 8k times · Source

The following program does not print the text "This is a trace". There is no app.config.

My question is, how can I modify the following code (and only the code, not any configuration files) such that messages passed in calls to t.TraceEvent appear in the Console window

using System;
using System.Collections.Generic;
using System.Diagnostics;

namespace ConsoleApplication1 {
    class Program {
        static void Main(string[] args) {
            Trace.Listeners.Add(
                new TextWriterTraceListener(Console.Out)
            );

            TraceSource t = new TraceSource("Test");
            t.Listeners.AddRange(Trace.Listeners);
            t.TraceEvent(TraceEventType.Critical, 1, "This is a trace");

            Console.Write("Press enter to quit");
            Console.ReadLine();
        }
    }
}

Answer

Andrew Crawford picture Andrew Crawford · Nov 9, 2013

See Trace Listeners.

The DefaultTraceListener will write to the Output window. To send messages to the TraceListener, you just need to call Trace.WriteLine("my output string");.

// C#
System.Diagnostics.Trace.Listeners.Clear();
System.Diagnostics.Trace.Listeners.Add( 
    new System.Diagnostics.TextWriterTraceListener(Console.Out));

EDIT: In response to your comment, the following code will print "my output string" immediately before "Press enter to quit" in the console window:

  static void Main(string[] args)
  {
     Trace.Listeners.Add(new TextWriterTraceListener(Console.Out));

     Trace.WriteLine("my output string");

     Console.Write("Press enter to quit");
     Console.ReadLine();
  }

EDIT2: After re-reading your question, I realised you're specifically trying to use the TraceSource, in which case you just need to set up the Switch so it knows which level of trace events should be sent to the console window. Try adding this after you add your listeners:

SourceSwitch sourceSwitch = new SourceSwitch("SourceSwitch", "Verbose");
t.Switch = sourceSwitch;