Tuesday, 11 October 2011

nLog - Updating ExceptionLayoutRenderer to capture “Exception.Data”

Something that appears to be missing from many logging frameworks is the ability to log/report the “data” collection of any thrown exceptions. I originally encountered this issue with log4net, and have recently found nLog appears to be lacking the same desired functionality. As our current project looks like it will be switching to using nLog I’ve had a dig around in the source code to see how easily this functionality can be added.

Basically for a quick and dirty solution the desired functionality can be added by adding the following function to the class “ExceptionLayoutRenderer”:

private static void AppendData(StringBuilder sb, Exception ex)
{
var separator = string.Empty;
foreach (var key in ex.Data.Keys)
{
sb.Append(separator);
sb.AppendFormat("{0}: {1}", key, ex.Data[key]);
separator = " ";
}
}

And the referencing this new function inside the “switch” statement of “CompileFormat”:

case "DATA":
dataTargets.Add(AppendData);
break;

Finally to use this new functionality, in the configuration section add “data” to the ${exception:format=} comma delimited list any where you want to report on exception data. Right now the formatting is pretty basic, I want to play some more to see what options are available to improve the rendering options whilst adhering to the existing nLog configuration model. It may be easier to add a custom LayoutRenderer just for exception data that can be held outside of the nLog DLL, removing the requirement to reference a custom build of the DLL (which probably breaks NuGet package deployments, etc).