Search code examples
c#tracetracelistenertraceswitchtracesource

How to filter trace listened by event id?


I'm using next method to add a trace record:

TraceSource.TraceEvent(TraceEventType, Int32, String)

where Int32 represents event id.

So how to filter in TraceSwitch to listen only by specified event id? Ir this is impossible?

<system.diagnostics>
    <sources>
        <source name="MyTraceSource" switchName="sourceSwitch" switchType="System.Diagnostics.SourceSwitch>"
            <listeners>
                <add name="console" type="System.Diagnostics.ConsoleTraceListener" />
            </listeners>
        </source>
    </sources>
    <switches>
        <add name="sourceSwitch" value="?" />
    </switches>
</system.diagnostics>

Solution

  • It's possible but you need to write a custom TraceFilter and override the ShouldTrace method. The id is passed to it, but no out-of-the-box filter supports it.

    Then, you can declare it like this in a .config file:

    <source name="MyTraceSource" switchName="sourceSwitch" switchType="System.Diagnostics.SourceSwitch">
      <listeners>
        <add name="console" type="System.Diagnostics.ConsoleTraceListener">
          <filter type="YourNamespace.YourFilter, YourAssembly, ..." />
        </add>
      </listeners>
    </source>