log4net - Exception renderer

June 12th, 2009

If you use log4net you have probably noticed that this logger does not write information from exception's "Data" property. Here is the renderer which does:

C#:
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Text;
  5. using log4net.ObjectRenderer;
  6.  
  7. namespace SomeNamespace
  8. {
  9.     public class ExceptionRenderer : IObjectRenderer
  10.     {
  11.         #region IObjectRenderer Members
  12.  
  13.         public void RenderObject(RendererMap rendererMap, object obj, TextWriter writer)
  14.         {
  15.             if (rendererMap == null)
  16.             {
  17.                 throw new ArgumentNullException("rendererMap");
  18.             }
  19.  
  20.             if (obj == null)
  21.             {
  22.                 throw new ArgumentNullException("obj");
  23.             }
  24.  
  25.             if (writer == null)
  26.             {
  27.                 throw new ArgumentNullException("writer");
  28.             }
  29.  
  30.             if (obj is Exception)
  31.             {
  32.                 Exception ex = (Exception)obj;
  33.                 writer.WriteLine(ex.ToString());
  34.  
  35.                 if (ex.Data.Count> 0)
  36.                 {
  37.                     writer.WriteLine("Exception Data:");
  38.                 }
  39.                 foreach (string key in ex.Data.Keys)
  40.                 {
  41.                     writer.WriteLine("\t {0} = {1}", key, rendererMap.FindAndRender(ex.Data[key]));
  42.                 }
  43.             }
  44.             else
  45.             {
  46.                 throw new InvalidOperationException(string.Format("Object of type {0} cannot be rendered with ExceptionRenderer", obj.GetType()));
  47.             }
  48.         }
  49.  
  50.         #endregion
  51.     }
  52. }

and the configuration needed for this to work is:

XML:
  1. <log4net>
  2. ...
  3.     <renderer renderingClass="SomeNamespace.ExceptionRenderer" renderedClass="System.Exception" />
  4. ...
  5. </log4net>

Sample output for NullReferenceException with Data["configPath"] = "myconfig.config":

2009-06-12 22:22:04,038 INFO  [LoggerTest.Program] - Exception during init
System.NullReferenceException: Something was null
   at LoggerTest.Program.Main(String[] args) in G:\C#\Temp\LoggerTest\Program.cs:line 26
Exception Data:
         configPath = myconfig.config

Feel free to use and modify it.

Leave a Reply

Designed by SirMike © All rights reserved

Valid XHTML 1.0! Valid CSS!

Powered by Rootnode