Object Rendering

TracerX replicates the Log4Net concept of custom object rendering using IObjectRenderer, DefaultRenderer, and RendererMap. In fact, much of the source code for this feature was copied from Log4Net (proper attribution is given in both the source code and the viewer).

Most of the time, TracerX just calls an object's ToString() implementation to render the object as a string to be logged. When this behavior is not adequate for a given type, you can write an implementation of IObjectRenderer and add it to the RendererMap to cause TracerX to call your code to render objects of the specified type (and derived types) as strings.

For example, suppose we want TracerX to render DateTimes using a certain format specifier that includes milliseconds, like "yyyy/MM/dd HH:mm:ss.fff". First we write a class that implements IObjectRenderer. There is only one method to implement.

using System;
using TracerX;

namespace Tester
{
    class DateTimeRenderer : IObjectRenderer
    {
        public void RenderObject(object obj, System.IO.TextWriter writer) {
            DateTime dateTime = (DateTime)obj;
            writer.Write(dateTime.ToString("yyyy/MM/dd HH:mm:ss.fff"));
        }
    }
} 


Somewhere in our code we must add an instance of DateTimeRenderer to the RendererMap like this.

RendererMap.Put(typeof(DateTime), new DateTimeRenderer()); 


Now suppose we have a Logger named Log and we use it to log the current time with the following statement.

Log.Info("The current time is ", DateTime.Now); 


The DateTime passed to Log.Info is rendered with the registered renderer and the result is...

The current time is 2007/11/23 14:56:06.765 


Note that the following statement has the semantics of string.Format() and therefore produces a different result.

Log.InfoFormat("The current time is {0}", DateTime.Now); 


The result (below) is different because the above statement passes the DateTime object directly to string.Format() instead of rendering it with the registered renderer.

The current time is 11/23/2007 2:56:06 PM 

The Default Renderer

If the object to render is not a string and its type (or base type) is not in the RendererMap, TracerX attempts to use the pre-defined DefaultRenderer. This class has special handling for arrays, collections, and DictionaryEntry objects. If the object is not one of those, it simply calls ToString().

Exception Rendering

TracerX pre-loads the RendererMap with a renderer for the Exception type. This renderer logs all nested inner exceptions and reports more information than Exception.ToString().

Last edited Dec 15, 2007 at 3:06 PM by MarkLTX, version 1

Comments

No comments yet.