tags:

views:

519

answers:

2
+1  Q: 

Log4net xml output

I want full control over log4net xml output.

How is it possible to customize the output template?

A: 

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.

Russell Troywest
Could I have a little more detail please?
JL
+5  A: 

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>
Darin Dimitrov
Darin, thank you so much, finally getting to the bottom of this, but can you please tell me, do I need to have this custom layoutbase in its own class library, in my application class library, or in log4net class library (recomplile)?
JL
You can have this class in its own class library or in your application class library. If you have it in its own class library you need to specify the name of the assembly that contains it: <layout type="MyNamespace.MyXmlLayout, MyCustomLog4NetExtensions" />
Darin Dimitrov
Darin are you still monitoring this question?
JL
Ok solved once and for all.. turns out I didn't need to specify the namespace... thanks!
JL