Log4Net是否可以附加到正确结构化的XML文档?

时间:2012-04-12 10:39:43

标签: c# xml log4net

我遇到的问题是它只是将XML标记写入文件,但它不是格式正确的XML文件。

正在填充文件,如下所示:

<LogEntry><Date>12/04/2012 11:16:26</Date><Message>An error message.</Message><StackTrace>..StackTrace omitted..</StackTrace></LogEntry>
<LogEntry><Date>12/04/2012 11:21:27</Date><Message>Another error message.</Message><StackTrace>..StackTrace omitted..</StackTrace></LogEntry>
<LogEntry><Date>12/04/2012 11:21:37</Date><Message>More messages.</Message><StackTrace>..StackTrace omitted..</StackTrace></LogEntry>

我有没有办法附加到正确结构化的XML文档?

理想情况下,它看起来如下:

<?xml version="1.0" encoding="utf-8"?>
<Logs>
    <LogEntry><Date>12/04/2012 11:16:26</Date><Message>An error message.</Message><StackTrace>..StackTrace omitted..</StackTrace></LogEntry>
    <LogEntry><Date>12/04/2012 11:21:27</Date><Message>Another error message.</Message><StackTrace>..StackTrace omitted..</StackTrace></LogEntry>
    <LogEntry><Date>12/04/2012 11:21:37</Date><Message>More messages.</Message><StackTrace>..StackTrace omitted..</StackTrace></LogEntry>
</Logs>

我正在使用的代码是:

public class MyXmlLayout : XmlLayoutBase
{
    protected override void FormatXml(XmlWriter writer, LoggingEvent loggingEvent)
    {
        writer.WriteStartElement("LogEntry");

        writer.WriteStartElement("Date");
        writer.WriteString(loggingEvent.TimeStamp.ToString(CultureInfo.CurrentCulture));
        writer.WriteEndElement();

        writer.WriteStartElement("Message");
        writer.WriteString(loggingEvent.RenderedMessage);
        writer.WriteEndElement();

        writer.WriteStartElement("StackTrace");
        writer.WriteString(loggingEvent.ExceptionObject.StackTrace);
        writer.WriteEndElement();

        if (loggingEvent.ExceptionObject.InnerException != null)
        {
            writer.WriteStartElement("InnerException");
            writer.WriteString(loggingEvent.ExceptionObject.InnerException.ToString());
            writer.WriteEndElement();
        }

        writer.WriteEndElement();
    }
}

,其配置为:

<log4net>
  <appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender" >
    <param name="File" value="Logs/log.xml" />
    <param name="AppendToFile" value="true" />
    <rollingStyle value="Size" />
    <maxSizeRollBackups value="10" />
    <maximumFileSize value="10MB" />
    <staticLogFileName value="true" />
    <layout type="MyNamespace.MyXmlLayout" />
  </appender>

  <root>
    <level value="DEBUG" />
    <appender-ref ref="LogFileAppender" />
  </root>
</log4net>

1 个答案:

答案 0 :(得分:5)

XmlLayoutBase课程不支持您要找的内容。原因很简单:如果必须确保xml始终格式良好,那么每当条目添加到文件时,它都需要覆盖关闭的根节点。只需将xml片段附加到文件就更容易,更快。