13.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

Modify web.config to:

  1. Add the EventLogTraceListener listener to the Listeners collection and make it available to your application, as shown in Example 13-18.

  2. Add the TraceSwitch, as shown in Example 13-18.

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 use the WriteIf and WriteLineIf methods of the Trace class to output the required messages, as we demonstrate in our sample application shown in Examples 13-19, 13-20 through 13-21.

Discussion

The technique we advocate for writing trace information to the event log involves adding the EventLogTraceListener to the listener collection in web.config to write the trace information to the event log. We find it useful to control the level of messages 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 13.5, you can add additional listeners to the TraceListeners collection via the web.config file. When a Trace.Write or Trace.WriteLine is executed, all listeners in the TraceListeners collection receive and process their output.

The support ...

Get ASP.NET 2.0 Cookbook, 2nd Edition 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.