繁体   English   中英

log4net-将错误附加到xml文件

[英]log4net - Append errors to an xml file

我正在尝试将错误附加到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> 

请为我们提供解决方案。

根据您的评论更新。

它过早地结束了Exceptions标签,因为您通过

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

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

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

一个快速的谷歌建议这些应该分别放在页眉和页脚的替代中,而不是像现在那样在格式中替代。

此链接是VB,但提供了有关如何执行所需操作的想法:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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