Damian Hickey

Mostly software and .NET related. Mostly.

Putting exception message into NLog's Chainsaw log4j xml output

It doesn't appear possible to get exception infomation into the chainsaw target renderer, so I got around this by extending the Log4JXmlEventLayout and butchering the xml.

Chalk this one up as a nasty hack, it's not pretty.

[Target("ChainsawExtended")]
public class ChainsawExtendedTarget : ChainsawTarget
{
    private readonly Log4JXmlEventLayoutExtended _layout = new Log4JXmlEventLayoutExtended();

    public override Layout Layout
    {
        get { return _layout; }
        set { }
    }

    private class Log4JXmlEventLayoutExtended : Log4JXmlEventLayout
    {
        protected override string GetFormattedMessage(LogEventInfo logEvent)
        {
            string s = base.GetFormattedMessage(logEvent);
            if(logEvent.Exception == null)
            {
                return s;
            }
            s = s.Replace("<log4j:event", "<log4j:event xmlns:log4j=\"http://nlog-project.org/dummynamespace/\"");
            var element = XDocument.Parse(s);
            var messageElement = element.Descendants().Where(e => e.Name.LocalName == "message").Single();
            messageElement.Value += Environment.NewLine + logEvent.Exception;
            s = element.ToString();
            s = s.Replace(" xmlns:log4j=\"http://nlog-project.org/dummynamespace/\"", string.Empty);
            return s;
        }
    }
}