log4net – Exception renderer
June 12th, 2009If 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#:
-
using System;
-
using System.Collections.Generic;
-
using System.IO;
-
using System.Text;
-
using log4net.ObjectRenderer;
-
-
namespace SomeNamespace
-
{
-
public class ExceptionRenderer : IObjectRenderer
-
{
-
#region IObjectRenderer Members
-
-
public void RenderObject(RendererMap rendererMap, object obj, TextWriter writer)
-
{
-
if (rendererMap == null)
-
{
-
}
-
-
if (obj == null)
-
{
-
}
-
-
if (writer == null)
-
{
-
}
-
-
{
-
Exception ex = (Exception)obj;
-
writer.WriteLine(ex.ToString());
-
-
if (ex.Data.Count> 0)
-
{
-
writer.WriteLine("Exception Data:");
-
}
-
foreach (string key in ex.Data.Keys)
-
{
-
writer.WriteLine("\t {0} = {1}", key, rendererMap.FindAndRender(ex.Data[key]));
-
}
-
}
-
else
-
{
-
throw new InvalidOperationException(string.Format("Object of type {0} cannot be rendered with ExceptionRenderer", obj.GetType()));
-
}
-
}
-
-
#endregion
-
}
-
}
and the configuration needed for this to work is:
XML:
-
<log4net>
-
...
-
<renderer renderingClass="SomeNamespace.ExceptionRenderer" renderedClass="System.Exception" />
-
...
-
</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.
