Thursday, December 18, 2008

How to contro whether output Trace

We already know Listner affect Trace object's output destination. But that is only an aspect of behavior, another aspect is whether the message should be output. The control this we can test a configurable switch's value to determine whether we should output the message. But we need to manually Test the the switch, or we need to write a helper class to wrap the test code. Here is the code.

class Program { static TraceSwitch switch1 = new TraceSwitch("global", "global switch"); static void Main(string[] args) { Trace.WriteLine(switch1.Level); Trace.Assert(2 == 1, "error message is here, because assert fail(condition is false)"); if (switch1.TraceError) { Trace.TraceError("An error happend"); } if (switch1.TraceInfo) { Trace.TraceInformation("just for your information"); } if (switch1.TraceWarning) { Trace.TraceWarning("just a warning"); } } }

We can also use another filter feature of Listener, without using switch1.

<sharedListeners> <add type="System.Diagnostics.ConsoleTraceListener" name="Console"> <filter type="System.Diagnostics.EventTypeFilter" initializeData="Error"/> </add> </sharedListeners>

No comments:

Post a Comment