6.4. A Custom Trace Class that Outputs Information in an XML Format

Problem

You need to output trace information in an XML format. Unfortunately, the Trace and Debug classes are sealed and therefore cannot be inherited from in order to create more specialized classes. This limitation poses somewhat of a problem if you need to create a Trace or Debug class that outputs XML instead of plain text. You could start from scratch and build new Trace and Debug classes from the ground up, but you would have to handle configuration files, listener collections, and switch information, among other things. This way can become quite time-consuming; you need a better way.

Solution

You could use the Log4Net package found at the SourceForge web site (http://log4net.sourceforge.net); it is a complete logging system that can easily be added to your application. However, if you use the XML logging, you should realize that the XML output is not well-formed. This is done by design so that the XML fragments output from Log4Net can be included as external entities in a different XML file to create a well-formed XML file.

Another solution is to create a new trace listener class, such as XMLTraceListener, that inherits from the framework-provided TraceListener class. The XMLTraceListener class is defined as follows (note that the XMLTraceListener does create a well-formed XML document):

using System; using System.Collections; using System.Diagnostics; using System.IO; using System.Xml; public class XMLTraceListener ...

Get C# 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.