System.Diagnostics.Trace, the simplest possible software configuration

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

My question is how can I change the following code (and only the code, not any configuration files) so that messages sent when t.TraceEvent is called 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(); } } } 
+6
source share
1 answer

See Trace Listeners .

DefaultTraceListener will be written to the output window. To send messages to 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 line” 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 reading your question again, I realized that you were specifically trying to use TraceSource , in which case you just need to configure the switch so that it knows what level of trace events should be sent to the console window. Try adding this after adding listeners:

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

Source: https://habr.com/ru/post/957717/


All Articles