Question

I'm doing some research into using log4net, and I found the IObjectRenderer interface interesting. It would allow us to control how types are logged and provide a different, possibly more user-friendly ToString() implementation. I just started looking at log4net though, and can't seem to find a logical way to programmatically set up the association between types and renderers.

I found that this can be set up in the XML configuration file by reading the manual, but it didn't give me any hints about programmatically adding these. It seems to me that you'd rather have a programmatic object renderer in some cases, so I'm curious how to do this.

Was it helpful?

Solution

I poked around with it some while writing the question and came up with this:

using System.IO;
using log4net;
using log4net.Config;
using log4net.ObjectRenderer;
using log4net.Util;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            BasicConfigurator.Configure();

            ILog log = LogManager.GetLogger(typeof(Program));
            var repo = LogManager.GetRepository();
            repo.RendererMap.Put(typeof(Foo), new FooRenderer());

            var fooInstance = new Foo() { Name = "Test Foo" };
            log.Info(fooInstance);
        }
    }

    internal class Foo
    {
        public string Name { get; set; }
    }

    internal class FooRenderer : log4net.ObjectRenderer.IObjectRenderer
    {
        public void RenderObject(RendererMap rendererMap, object obj, TextWriter writer)
        {
            if (obj == null)
            {
                writer.Write(SystemInfo.NullText);
            }

            var fooInstance = obj as Foo;
            if (fooInstance != null)
            {
                writer.Write("", fooInstance.Name);
            }
            else
            {
                writer.Write(SystemInfo.NullText);
            }
        }
    }
}

I am not certain if this is the correct way to do this, but I do know that it worked.

OTHER TIPS

You can also add this line to the root of your log4net if you don't want to register your renderer programatically

<renderer renderingClass="ConsoleApplication1.FooRenderer" renderedClass="ConsoleApplication1.Foo" />
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top