If you have missed my last few posts, I’ve been writing a bit about tracing in .NET 2.0, this post is no exception. An interesting addition to the tracing APIs is trace filtering. A trace filter is a class that derives from the TraceFilter class and is associated with a TraceListener via the TraceFilter property.

The TraceFilter class is pretty simple, on top of the usual methods exposed by System.Object it has a ShouldTrace(…) method which returns a boolean. The method is supplied a number of arguments which help you write code to make a decision whether tracing information should be logged.

TraceFilter

It is important to note that a TraceFilter is not intended to be a replacement for a TraceSwitch (which are incredibly under used already), instead it is supposed to be used to provide an additional interception point if a diagnostic message does make it past a trace filter. The logic should work something like this:

TraceSwitchFlowChart

The key difference (other than the API) between a trace switch and trace filter is that while trace switches are good for applying rules across all listeners – a trace filter can be applied on a per listener basis. One curious omission (I feel) is the lack of ability to specify in the configuration file the type of filter that is being wired up.

My assumption is that they intend us to have listeners supply their own filters by default, and if we want to override them, do it in code. In the code below I have written a simple trace filter “LtuaeFilter” only logs out messages that contain the answer to life, the universe and everything.

TraceFilterSampeCode

When you run the program you get a whole heap of numeric output (because I am using a ConsoleTraceListener), but notice that every number contains the text “42”.

TraceFilterOutput

Of course, you can filter on more than just the text of the diagnostic message, the cache argument to the ShouldTrace message is of type TraceEventCache and gives us access to useful information like the LogicalOperationStack which I wrote about in my previous post.

All in all its a nice little enhancement and will probably be used by a couple of people, however I feel that a lack of configurability post compile time means that we’ll see all sorts of wierd and wonderful implementations.

P.S. You can download the code from here.