How to distinguish between Trace and Debug calls in a custom trace listener?

Trace.Listeners and Debug.Listeners use the same internal collection, so I cannot add a trace listener to Trace.Listeners and a debug listener Debug.Listeners to distinguish between them.

How can i achieve this?

Edit:

Why I want to do this, simply because I enter the log level in our application, and I want to track various logs through a system in which Debug / Trace are two sources of logs (there are a couple of other sources too) I want to track.

+5
source share
1 answer

[EDIT]

, . , , ( ) TraceListener, Trace.WriteLine Debug.WriteLine. , , , , TraceSources Trace.WriteLine Debug.WriteLine. , , , TraceListener Write WriteLine , - Trace.WriteLine vs Debug.WriteLine.

, , TraceListener Write WriteLine. , , , , TraceSources .

, , , Trace.WriteLine Debug.WriteLine. , TraceListener, , , Trace.WriteLine Debug.WriteLine. - :

public void WriteLine(string msg)
{
  if (WasWrittenFromTrace)
  {
    //Before writing to output, add "TRACE" to front of message
    WriteToOutput("TRACE: {0}", msg);
  }
  else
  if (WasWrittenFromDebug)
  {
    //Before writing to output, add "DEBUG" to front of message
    WriteToOutput("DEBUG: {0}", msg);
  }
}

[END EDIT]

. System.Diagnostics.

, System.Diagnostics, TraceSources, Trace.WriteLine Debug.WriteLine.

, , :

public void MyFunction(int x, int y)
{
  Trace.WriteLine("Entering MyFunction.  x = {0}, y = {1}", x, y);

  int product = x * y;

  Debug.WriteLine("product = {0}", product);

  Trace.WriteLine("Exiting MyFunction");
}

, -, , Trace TraceListener Debug, TraceListener. TraceListener (, ), , Write/WriteLine Trace.Write Debug.Write. , .

(, ?

TraceSources, / , , TraceSources TraceListener TraceListener ( TraceSources TraceListeners).

, TraceSources, :

public class MyClass
{
  //Static variable, so all instances of MyClass will have access to the same instance
  //of the TraceSource
  private static readonly TraceSource ts = new TraceSource("MyClass");

  public void MyMethod(int x, int y)
  {
    ts.TraceEvent(TraceEventType.Information, 0, "Entering MyMethod.  x = {0}, y = {1}", x, y);

    int product = x * y;

    ts.TraceEvent(TraceEventType.Debug, 0, "Product = {0}", product);

    ts.TraceEvent(TraceEventType.Information, 0, "Exiting MyMethod.");
  }
}

TraceSource ?

  • app.config TraceSource MyClass . "" , "" "". "", . , "", .

  • app.config "MyClass" TraceListeners. TraceSources ( "YourClass", "HisClass" ), TraceListener, TraceListener .

  • app.config / , "MyClass" , , TraceListeners. TraceListener , "" , , "".

TraceSources , . . . Ukadc.Diagnostics, . Essential.Diagnostics - , System.Diagnostics, System.Diagnostics. MSDN TraceSources, TraceListeners.

, , TraceSources, Trace. * Debug. *, / .

!

+4

All Articles