简体   繁体   中英

log4net - Append errors to an xml file

I am trying to append error to an xml file, where I am not able to append the way I wanted.

I am using custom layout overriding XmlLayout format method as shown below.

public class MyXmlLayout : log4net.Layout.XmlLayout
{
    public static bool isFirstTime = true;

    protected override void FormatXml(System.Xml.XmlWriter writer, LoggingEvent loggingEvent)
    {
        if (isFirstTime)
        {
            writer.WriteStartDocument();
            writer.WriteStartElement("Exceptions");
        }

        writer.WriteStartElement("Exception");

        writer.WriteStartElement("Error");
        writer.WriteAttributeString("Date", loggingEvent.TimeStamp.ToUniversalTime().ToString());
        writer.WriteAttributeString("User", loggingEvent.UserName);
        writer.WriteString(loggingEvent.RenderedMessage);

        writer.WriteEndElement();
        writer.WriteEndElement();

        if (isFirstTime)
        {
            writer.WriteEndElement();
            writer.WriteEndDocument();

            isFirstTime = false;
        }
    }
}

Yes, Its appending through the above code, but the problem is I am unable to read xml file as its not in proper format.

The generated xml by above code looks like

 <?xml version="1.0" encoding="Windows-1252"?> <Exceptions> <Exception> <Error Date="11-11-2014 13:47:53" User="SOURCEEDGE SunilKumar">Exception 1</Error> </Exception> </Exceptions> <?xml version="1.0" encoding="Windows-1252"?> <Exceptions> <Exception> <Error Date="11-11-2014 14:01:44" User="SOURCEEDGE\\SunilKumar">Exception 2</Error> </Exception> </Exceptions> 

And What it should be is

 <?xml version="1.0" encoding="Windows-1252"?> <Exceptions> <Exception> <Error Date="11-11-2014 13:47:53" User="SOURCEEDGE\\SunilKumar">Exception 1</Error> </Exception> <Exception> <Error Date="11-11-2014 14:01:44" User="SOURCEEDGE\\SunilKumar">Exception 2</Error> </Exception> </Exceptions> 

Please help us with the solution.

Updated per your comment.

Its ending the Exceptions tag prematurely because you told it to with

if (isFirstTime)
{
    writer.WriteStartDocument();
    writer.WriteStartElement("Exceptions");
}

and

if (isFirstTime)
{
    writer.WriteEndElement();
}

Rearrange your code so that the writer starts the XML document and Exceptions element when the file is opened and ends it just before the file is closed.

A quick google suggests that these should go into the overrides for Header and Footer respectively, instead of in the override for Format as you currently have.

This link is VB, but gives an idea of how to do what you want:

http://blogs.lessthandot.com/index.php/DesktopDev/MSTech/making-an-xmllayout-for-log4net/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM