Log state of a object for diagnostic purposes

Problem:
How do I log state of a object for diagnostic purposes?

Solution:
We extended the class provided at Serialize and Deserialize IEnumerable Objects by adding a ToXMLString() method. This method serializes the passed object parameter to an XML string. The object state is stored in the Data property of the exception and then logged using a logging framework of choice.

var exception = new Exception();
exception.Data.Add("GuestCard", new CustomXmlSerializer().ToXMLString(guestCard));
//Log the exception using a logging framework of your choice. 

Extended Class: (See Serialize and Deserialize IEnumerable Objects)

    using System.Text;
    using System.IO;
    using System.Xml;

    public class CustomXmlSerializer
    {
        public void WriteXml(object source, System.Xml.XmlWriter writer)
        {
            WriteXml(source, writer, null);
        }
        public string ToXMLString(object source)
        {
            var stringBuilder = new StringBuilder();
            var stringWriter = new StringWriter(stringBuilder);
            var xmlTextWriter = new XmlTextWriter(stringWriter);
            WriteXml(source, xmlTextWriter);
            return stringBuilder.ToString();
        }
    }

You may also like