log4net-将错误附加到xml文件中

本文关键字:xml 文件 错误 log4net- | 更新日期: 2023-09-27 18:30:03

我正试图将错误附加到一个xml文件中,但在该文件中我无法按照我想要的方式进行附加。

我正在使用自定义布局覆盖XmlLayout格式方法,如下所示。

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;
        }
    }
}

是的,它是通过上面的代码附加的,但问题是我无法读取xml文件,因为它的格式不正确。

上面代码生成的xml看起来像

<?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>

它应该是

<?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>

请帮我们解决问题。

log4net-将错误附加到xml文件中

根据您的评论更新。

它过早地结束了Exceptions标签,因为你告诉它使用

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

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

重新排列代码,以便编写器在文件打开时启动XML文档和Exceptions元素,并在文件关闭前结束它。

快速谷歌建议,这些应该分别进入Header和Footer的覆盖中,而不是像目前那样进入Format的覆盖中。

这个链接是VB,但给出了如何做你想做的事情的想法:

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