我遇到的问题是它只是将 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>