System.Diagnostics.Trace, simplest possible programmatic configuration
Asked Answered
M

1

7

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();
        }
    }
}
Moose answered 9/11, 2013 at 1:4 Comment(1)
If you're using the Release configuration, define the TRACE symbol. Or switch to the Debug configuration.Hydroxyl
T
9

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;
Todo answered 9/11, 2013 at 1:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.