65.9K
CodeProject is changing. Read more.
Home

Simple XML based Error Log

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.40/5 (7 votes)

Jul 14, 2004

2 min read

viewsIcon

86327

downloadIcon

1907

This article shows how to write and use simple XML-based error log

Sample Image - XMLErrorLog.gif

Introduction

This article explains how to log errors (actually exceptions) which have occured in your app into an XML file. My error log is actually simple class ErrorLog in namespace DNH.Common.Errors. It's part of my library DNH.Common and I use this class in my projects. Although it is very simple, I think that functionality of ErrorLog really helps in debugging applications. It shows how to write XML using XmlTextWriter .

This article provides some basics of:

  • writing XML files using System.Xml.XmlTextWriter
  • handling exceptions using try-catch
  • detecting unhandled exceptions using Server.GetLastError()

Using the code

First at all, you must add reference to assembly dnh.common.errors.dll into your project. Then you must write using DNH.Common.Errors or use full name of class: DNH.Common.Errors.ErrorLog. Then simply declare variable of ErrorLog class type. Calling constructor is simple:

m_log = new ErrorLog(this.Server.MapPath("errorlogs/SampleXMLLog.xml"))
         
Only argument passed is path to XML file. First time this is called, ErrorLog will create new file. So be sure it has read/write access to that virtual directory.

As I wrote, ErrorLog writes down errors when Exception is thrown. Exception must be catched in try-catch block. Or in ASP.NET web apps, it can be also obtained by calling Server.GetLastError() (probably in Global.asax.cs, Application_Error handler).

This is handler in Global.aspx.cs:

        protected void Application_Error(Object sender, EventArgs e)
        {
            // log unhandled exception

            m_log.SaveExeptionToLog(Server.GetLastError());
            //

            // it's late, but better do something!

            //

        }

Points of Interest

This code writes data from Exception into XML writer:

    
        private void WriteException(Exception e, XmlWriter xmlWriter)
        {
            xmlWriter.WriteStartElement(XML_EXCEPTION);
            xmlWriter.WriteElementString(XML_EXCEPTION_TIME,
                System.DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"));
            // write the description of exeption

            xmlWriter.WriteElementString(XML_EXCEPTION_DESCRIPTION,
                e.Message);
            
            // method where exception was thrown

            if(e.TargetSite!=null)
                xmlWriter.WriteElementString(XML_EXCEPTION_METHOD,
                    e.TargetSite.ToString());
            // help link

            if(e.HelpLink!=null)
                xmlWriter.WriteElementString(XML_EXCEPTION_HELPLINK,
                    e.HelpLink);
            // call stack trace

            xmlWriter.WriteStartElement(XML_EXCEPTION_TRACE);
            xmlWriter.WriteString(e.StackTrace);
            xmlWriter.WriteEndElement();
            if(e.InnerException!=null)
            {
                // recursively writes inner exceptions

                WriteException(e.InnerException,xmlWriter);
            }

This method write data into XML file using method above:

        public void SaveExeptionToLog(System.Exception e)
        {
            string strOriginal = null;

            XmlTextReader xmlReader = new XmlTextReader(m_logFileName);
            xmlReader.WhitespaceHandling = WhitespaceHandling.None;
            //Moves the reader to the root element.

            // skip <?xml version="1.0" ...

            xmlReader.MoveToContent();
            strOriginal = xmlReader.ReadInnerXml();
            xmlReader.Close();
            // write new document

            XmlTextWriter xmlWriter = 
 new System.Xml.XmlTextWriter(m_logFileName,System.Text.Encoding.UTF8);
            xmlWriter.WriteStartDocument();
            xmlWriter.WriteDocType(
              XML_ERRORLOG_DOCTYPE,null,XML_ERRORLOG_DTD,null);
            xmlWriter.WriteStartElement(XML_ERRORLOG);
            // write original content

            xmlWriter.WriteRaw(strOriginal);
            //write down new exception

            WriteException(e,xmlWriter);
            xmlWriter.WriteEndElement();
            xmlWriter.Close();
        }

Please note that I first load original file and then I add new node. Use of XmlDocument and XmlDocument.AppendChild() is maybe better (more obvious). Anyway, I hope this is readable as well. Also note that I track inner exceptions by recursive calling WriteException() with Exception.InnerException as argument.

TODO

There is of course a lot to do...
  • case when more exceptions occurs in same time should be handled
  • add more informations (like infos about currently logged users in your app)
  • manipulating with XML could be done using XmlDocument or XmlDocumentFragment. It's more clear.
  • generated XML is described by DTD. Expect use of XML Schema in next release.
  • this one is difficult: automatic analysis of occured errors. but it would be great :)

History

  • 14.7.2004 - Article first posted to CodeProject