Sunday, March 6, 2011

What is the best way to dump entire objects to a log in C#?

So for viewing a current object's state at runtime, I really like what the Visual Studio Immediate window gives me. Just doing a simple

? objectname

Will give me a nicely formatted 'dump' of the object.

Is there an easy way to do this in code, so I can do something similar when logging?

From stackoverflow
  • You could use reflection and loop through all the object properties, then get their values and save them to the log. The formatting is really trivial (you could use \t to indent an objects properties and its values):

    MyObject
        Property1 = value
        Property2 = value2
        OtherObject
           OtherProperty = value ...
    
  • You could base something on the ObjectDumper code that ships with the Linq samples.

    Dan Esparza : Wow -- great idea. Also, here is this idea as an extension method http://blogs.msdn.com/danielfe/archive/2005/09/22/473018.aspx
    John Hunter : Doesn't seem to work for XmlDocuments...
  • I'm certain there are better ways of doing this, but I have in the past used a method something like the following to serialize an object into a string that I can log:

      private string ObjectToXml(object output)
      {
         string objectAsXmlString;
    
         System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(output.GetType());
         using (System.IO.StringWriter sw = new System.IO.StringWriter())
         {
            try
            {
               xs.Serialize(sw, output);
               objectAsXmlString = sw.ToString();
            }
            catch (Exception ex)
            {
               objectAsXmlString = ex.ToString();
            }
         }
    
         return objectAsXmlString;
      }
    

    You'll see that the method might also return the exception rather than the serialized object, so you'll want to ensure that the objects you want to log are serializable.

  • What I like doing is overriding ToString() so that I get more useful output beyond the type name. This is handy in the debugger, you can see the information you want about an object without needing to expand it.

  • It might be a little off-topic here, but Darryl Braaten's post reminded me the DebuggerDisplay attribute for object preview in the watch window while debugging.

  • I have a T.Dump() extension method that does exactly this, recursively dumps all properties of any type in a nice readable format.

0 comments:

Post a Comment