10.6. Writing Trace Data to the Event Log with Controllable Levels
Problem
You want your application to output trace information to the event log and, at the same time, control what level of information is output.
Solution
Create your own trace listener that inherits from the
TraceListener
class and overrides the
Write
and WriteLine
methods to
write
their output to
the event log. A sample trace listener we’ve written
to demonstrate this solution is shown in Example 10-20
(VB) and Example 10-21 (C#).
Next, modify your web.config
file to add the
custom TraceListener
and
TraceSwitch
, as shown in Example 10-22.
In the classes you want to output trace information, create a
TraceSwitch
object using the name of the
TraceSwitch
you added to the web.config file, and then use the
WriteIf
and WriteLineIf
methods
of the Trace
class to output the required
messages, as we demonstrate in our class in Example 10-23 (VB) and Example 10-24 (C#).
Discussion
The technique we advocate for writing trace information to the event
log involves creating your own custom trace listener that overrides
the Write
and WriteLine
methods
and directs their output to the event log. We also find it useful to
control the level of messages that are output to the event log, such
as outputting only error messages or outputting error and warning
messages. Controlling the level of messages that are output involves
the use of switches (more about this in a minute).
As discussed in Recipe 10.5, you can add additional listeners to ...
Get ASP.NET Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.