views:

41

answers:

3

When spiking on how something works or when my unit test behave in an unpredictable manner I usually have to drop into debug mode. 99% of my time in debug mode is spent checking the values of fields on objects to verify its state.

I already have log4net set up, it would seem that if I could easily add a line of code to log out the state of objects I could remove most of my need to start up the bulky debugger. The problem is of course that to expose object state implicitly you need to manually override each object's ToString() method. What I would like to be able to do is the ability to do logger.LogState(someObject) and have logged out the object state including at least a formatted list of all the private variables, references (to some arbitrary depth), and collections.

Does anyone know a tool/framework/code snippet that can be used to generate a string of the internal state of any object? I could of course write one myself but its a non-trivial problem and I'd prefer something someone has put some thought into.

+1  A: 

What you might be able to do is to mark your objects as Serializable, and then use, for example, an XMLSerializer to serialize it to some stream, similar to what is done in the accepted answer to this question. This could then be output into your log.

Of course, it does assume that you actually can make all of your objects serializable.

Michael Madsen
Yes, that assumes you have control of your objects. Not much good when exploring how NHibernate works for example.
George Mauer
+1  A: 

If you want to generate object state dumps, you need a tool that understands the type information of the objects states that can generate logging information for each field. Such a tool needs to be able to parse the source code, build symbol tables, enumerate fields in objects, and generate code to dump each object field.

The DMS Software Reengineering Toolkit has all the requisite elements for Java, C, C++ and most of this for C# and JavaScript. You'd need to build a custom script to drive DMS to enumerate the classes you care about (you need to define this unless you want to dump information from every possible class and every possible method call) and generate logging dumps on function entry (and even perhaps inside control flow blocks) in the code of interest.

Ira Baxter
+1  A: 

SmartInspect's LogObject method might be useful for this. This method logs all object properties and fields and you can easily analyze them in the Console:

alt text

Dennis G.