Write raw text in log file using log4net

I have create the custom xml layout using this post. i need log message with character < but in log file it converted to &lt; this is my code sample

public class MyXmlLayout : XmlLayoutBase
{
    protected override void FormatXml(XmlWriter writer, LoggingEvent loggingEvent)
    {
        writer.WriteStartElement("LogEntry");
        writer.WriteStartElement("Exception");
        writer.WriteString("<![CDATA[\n" + loggingEvent.GetExceptionString() + "\n]]>");
        writer.WriteEndElement();
        writer.WriteEndElement();
    }
}

Output log file

<LogEntry>
    <Exception>&lt;![CDATA[
        System.DivideByZeroException: Attempted to divide by zero.
           at ConsoleApplication5.Program.Main(String[] args) in c:\Users\MahendranM\Documents\Visual Studio 2013\Projects\ConsoleApplication5\ConsoleApplication5\Program.cs:line 24
        ]]&gt;
    </Exception>
</LogEntry>

How can print raw character like <,>in log4net?

Jon Skeet
people
quotationmark

If you really want to do this, you could use

writer.WriteRaw("<![CDATA[\n" + loggingEvent.GetExceptionString() + "\n]]>");

or

writer.WriteCData(loggingEvent.GetExceptionString());

However, I would strongly discourage you from doing this. There's no guarantee that you'll end up with valid XML at the end... if your text contains "]]>" then it will cause problems. (With WriteRaw you'll end up with invalid XML; with WriteCData you'll end up with an exception.)

I would expect the purpose of using an XML log file to be simply to propagate the data for each log entry, in an XML format. So just use writer.WriteString(loggingEvent.GetExceptionString()) and then whatever reads the log file later can do the right thing with it. Wrapping it in CData rather than letting the XML API just escape it as it needs to seems like a bad idea to me.

people

See more on this question at Stackoverflow