Log4net xml output

霸气de小男生 提交于 2019-12-17 06:42:18

问题


I want full control over log4net xml output.

How is it possible to customize the output template?


回答1:


As suggested by MrPeregrination you need to write a class deriving from XmlLayoutBase, override the FormatXml method and instruct your appender to use it as layout:

class Program
{
    static void Main(string[] args)
    {
        XmlConfigurator.Configure();
        ILog log = log4net.LogManager.GetLogger(typeof(Program));
        log.Debug("Hello world");
    }
}

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

And in app.config put this:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/>
  </configSections>

  <log4net>
    <appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender" >
      <param name="File" value="log.txt" />
      <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>
</configuration>

This will produce entries like this in your log file:

<LogEntry><Message>Hello world</Message></LogEntry>



回答2:


Adding to Darin's answer, in log4net 2.0.8, I had to change the layout a little:

<layout type="MyNamespace.MyClass, MyNamespace"/>

I found this here http://www.codewrecks.com/blog/index.php/2008/04/29/writing-a-custom-formatter-for-log4net/




回答3:


Check out the XmlLayoutBase class. I think thats probably what you need. There's a FormatXML function you will need to override to supply the XmlWriter with the correctly formatted data.



来源:https://stackoverflow.com/questions/1147103/log4net-xml-output

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!