如何在log4net中注册自定义IObjectRenderer? [英] How do I register a custom IObjectRenderer in log4net?

查看:272
本文介绍了如何在log4net中注册自定义IObjectRenderer?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究使用log4net,并且发现 IObjectRenderer 接口很有趣.这将使我们能够控制记录类型的方式,并提供不同的,可能更用户友好的ToString()实现.不过,我只是开始研究log4net,似乎找不到一种逻辑方式来以编程方式设置类型与渲染器之间的关联.

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.

推荐答案

我在写问题时摸索了一下,并提出了以下建议:

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.

这篇关于如何在log4net中注册自定义IObjectRenderer?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆