TraceFilter Class
Represents the base class for filtering trace output. The TraceFilter class is an abstract class.
Namespace:
System.Diagnostics
Assembly:
System.dll
Inheritance Hierarchy:
System.ObjectSystem.Diagnostics.TraceFilter
Derived Classes:
System.Diagnostics.EventTypeFilterSystem.Diagnostics.PerformanceCounterPermissionFilter
Remarks
You can create custom trace filters by deriving from the TraceFilter class and implementing the ShouldTrace method. This method determines whether a trace event should be passed to a trace listener. The .NET Framework provides two built-in trace filters: EventTypeFilter and PerformanceCounterPermissionFilter.
Trace filters are associated with trace listeners. When a trace event is sent to a trace listener, the listener calls the filter's ShouldTrace method to determine if the event should be processed. This allows you to control the granularity of your trace output without modifying the trace source or the trace listener itself.
Methods
ShouldTrace(TraceEventCache cache, string source, TraceEventType severity, object id, object data)
Abstract. Determines whether the specified trace event should be traced.
Parameters:
cache: ATraceEventCacheobject that contains the current process, thread, and stack information.source: The name of the trace source that generated the event.severity: ATraceEventTypevalue indicating the severity of the event.id: The identifier of the trace event.data: An object containing additional trace data.
Returns:
true if the trace event should be traced; otherwise, false.
Example
The following example shows how to create a custom trace filter that only traces TraceEventType.Error and TraceEventType.Critical events.
Custom Trace Filter Implementation
using System;
namespace MyTracing
{
public class ErrorOnlyTraceFilter : System.Diagnostics.TraceFilter
{
public override bool ShouldTrace(
System.Diagnostics.TraceEventCache cache,
string source,
System.Diagnostics.TraceEventType severity,
int id,
object data)
{
return (severity == System.Diagnostics.TraceEventType.Error ||
severity == System.Diagnostics.TraceEventType.Critical);
}
}
}
Applying the Custom Filter
using System;
using System.Diagnostics;
public class Program
{
public static void Main(string[] args)
{
TraceSource ts = new TraceSource("MyApp");
ConsoleTraceListener consoleListener = new ConsoleTraceListener();
consoleListener.Filter = new MyTracing.ErrorOnlyTraceFilter();
ts.Listeners.Clear();
ts.Listeners.Add(consoleListener);
ts.TraceInformation("This is an informational message."); // Will not be displayed
ts.TraceWarning("This is a warning message."); // Will not be displayed
ts.TraceError("This is an error message."); // Will be displayed
ts.TraceCritical("This is a critical message."); // Will be displayed
ts.Close();
}
}