sumit
sumit

Reputation: 21

I need to log in xml format in using log4net

I am using log4net for logging. i am trying to log in xml format. I am also trying to log custom fields .

I have extended the XmlLayoutBase class and in the FormatXml(writer,loggingEvent) i can write the custom fileds. But here is the problem , It does not create well formed xml It does not add under a specified node( cant do that using XmlTextWriter)

What i did so far: I extended RollingFileAppender and overriden the OpenFile virtual function , I can add the required parent nodes now , but the logging gets added at the end and could not find a way to add them under a specific parent node in the xml

public class CustomRollingFileAppender:RollingFileAppender
{

 protected override void OpenFile(string fileName, bool append)
 {
  bool needToWrite = System.IO.File.Exists(fileName);
  base.OpenFile(fileName, append);
  lock (this)
  {
    if (needToWrite == false)
     {
      using (System.IO.StreamWriter file = new System.IO.StreamWriter(fileName))
      {
       file.WriteLine(<System >);
       file.WriteLine(<LogParent >);
       file.WriteLine(</LogParent>);
       file.WriteLine(</System>);
     }
    }
  }
 }
}

using the above snippet i can add the header and other required information in my xml file. Now my xml looks like this

<System CreationDate='4/18/2011 6:30:41 PM'>
<ParentLog TimeStamp='2010-07-01T11:01:58'>
// logs should appear here as children of <ParentLog> 
</ParentLog>
</System>

Next i extended the XmlLayoutBase like below

public class CustomXMLLayout: XmlLayoutBase
{
 protected override void FormatXml(System.Xml.XmlWriter writer,log4net.Core.LoggingEvent loggingEvent)
{
 System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader(@"example.xml");

 writer.WriteStartElement("Log");
 writer.WriteAttributeString("TimeStamp", DateTime.Now.ToString());

 writer.WriteEndElement();

}

}

// the entries are written correctly (excuse the writing part ) but at the end for obvious reason. My questions are Is there any way to attach an xsd along the log4net to tell it as in where to make the log entries or alternatively any way to assign the xsd to the XMLWriter ? I shall not be able to use xmldocument

Any help is appreciated.

regards, sumit

Upvotes: 2

Views: 2737

Answers (1)

Anthony Mastrean
Anthony Mastrean

Reputation: 22394

If you're not satisfied with the built-in XMLLayout pattern and the use of Contexts for "custom" fields, then you don't want to use log4net to do this. You want to create an object model, update its properties, and serialize that to XML. you can then log that XML stream using log4net's file appending facilities. Ok?

Upvotes: 2

Related Questions