Question

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>
Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top