How to keep XmlWriterTraceListener from xml-encoding characters in the message

485 views Asked by At

I am trying to use System.Diagnostics.XmlWriterTraceListener to log to a local file. I start by creating a source and adding a new XmlWriterTraceListener to it, like so:

public class Logger
{
    const string LOG_ERR_FMT = "<message><![CDATA[{0}]]></message>{2}";

    TraceSource tSource = new TraceSource(
        "MyApp",
        SourceLevels.Verbose | SourceLevels.ActivityTracing
    );

    public Logger() {
        tSource.Listeners.Add(
            new XmlWriterTraceListener("C:\\app_path\\app_tracelog.svclog", "LocalListener")
        );
    }

    public static Logger defLogger = new Logger();
    public static Logger Default {
        get {return defLogger; }
        set { if (value != null) defLogger = value; }
    }

    public void LogError(string msg, string extraXmlData) {
        tSource.TraceEvent(TraceEventType.Error, 0, LOG_ERR_FMT, logMsg, extraXmlData);
    }
}

I've simplified the log format in the sample above. The actual LogError method takes an Exception object and inserts some xml-serialized data about it into the message, but that's not needed to show what my problem is here.

Anyways, any other part of my app can now log an error to the "app_tracelog.svclog" file with a simple line like, oh say...

Logger.Default.LogError(
    "Error parsing response from web service \"someservice.com\".",
    "<RequestBody><![CDATA[" + responseBody + "]]></RequestBody>"
);

All is well until I open up app_tracelog.svclog. First of all, when I try to open it with Microsoft Service Trace Viewer, that program behaves like it's empty, and gives me a message of "There is no trace loaded from the file."

Second, I open the file with good old Notepad++ and find that my app DID INDEED log to it. I select all and tell XmlTools to pretty it up, and the tool tells me it can't do it because there's errors in the XML.

So, I start formatting it manually. All goes well at first, until I get to the actual application message that I logged. Here, I find that this STUPID @#$ class has screwed up all my nested XML by replacing brackets and such with encoded XML/HTML entities!

All my '<'s have become "&lt;", All my '>'s have become "&gt;", etc... So the log message that SHOULD have looked like:

<message><![CDATA[Error parsing response from web service "someservice.com".]]></message><RequestBody...

Now looks like:

&lt;message&gt;&lt;![CDATA[Error parsing response from web service "someservice.com".]]&gt;&lt;/message&gt;&lt;RequestBody...

So the big question is: How can I FORCE XmlWriterTraceListener to stop trashing my message when I log? I know what I'm doing when I put in special XML characters, and it thinks it knows better! --OR- Is there another listener class that will log to a local XML file the way I want?

0

There are 0 answers