5

What is the difference between "switch" and "filter" in Tracing in .NET ? They seem to work in similar way.

<system.diagnostics>
    <trace autoflush="true" indentsize="5">
      <listeners>
        <add name="DemoListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="D:\output1.txt">
        </add>
        <remove name="Default" />
      </listeners>
    </trace>    
    <sources>
      <source name="DemoApp" switchName="DemoApp">
        <listeners>
          <add name="DemoListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="D:\output2.txt">
            <filter type="System.Diagnostics.EventTypeFilter" initializeData="Error"/>
          </add>
          <remove name="Default" />
        </listeners>
      </source>
    </sources>
    <switches>
      <add name="DemoApp" value="Error"/>
    </switches>
  </system.diagnostics>
Brij
  • 11,731
  • 22
  • 78
  • 116

1 Answers1

6

There is a bit of overlap. A <filter> names a specific class that you write that's derived from TraceFilter. Which you can use to suppress trace output, anything is possible. It always applies to a specific TraceListener.

The <switches> element is useful to configure tracing and set the value of a TraceSwitch object. Which you then test in your code to selectively bypass trace output. Note how <switches> is "global", it doesn't apply to a specific listener. So a logical place to test the switch is in the TraceSource. A good use for a switch is to configure the tracing verbosity. Like your "Error" value would indicate that only errors are ever traced.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • 1
    In other words the `` element restricts the input messages sent to the listeners and the `` element restricts the messages the listener outputs. – Suncat2000 Nov 08 '16 at 13:13