在log4net中扩展AsyncForwardingAppender

时间:2015-03-10 07:29:58

标签: .net log4net log4net-configuration log4net-appender

大家好我想扩展AsyncForwardingAppender。 我有以下配置文件:

<log4net>
    <appender name="AsyncForwardingAppenderExtender" type="log4net.Async.AsyncForwardingAppender,Log4net.Async" >
    <layout type="log4net.Layout.PatternLayout,log4net">
        <param name="ConversionPattern" value="%d [%t] %-5p %c %m%n" />
    </layout>
    </appender>
    <root>
        <level value="Info" />
        <appender-ref ref="AsyncForwardingAppenderExtender" />
    </root>
</log4net>

现在在我的代码中,我已经覆盖了Append方法,如下所示

public class AsyncForwardingAppenderExtender : Log4Net.Async.AsyncForwardingAppender
{
    private Queue<LoggingEvent> buffer = new Queue<LoggingEvent>();
    private static readonly Type ThisType = typeof (AsyncForwardingAppender);

    public AsyncForwardingAppenderExtender()
    {
    }

    protected override void Append(LoggingEvent loggingEvent)
    {
        buffer.Enqueue(loggingEvent);
    }

    protected override void Append(LoggingEvent[] loggingEvents)
    {
        foreach (var loggingEvent in loggingEvents)
        {
            Append(loggingEvent);
        }
    }

    public override void ActivateOptions()
    {
        base.ActivateOptions();
        InitializeBuffer();
        StartForwarding();
    }

    private void StartForwarding()
    {
        Thread forwardingThread =
            new Thread(ForwardingThreadExecute)
            {
                Name = String.Format("{0} Forwarding Appender Thread", Name),
                IsBackground = false,
            };
        forwardingThread.Start();
    }

    public void InitializeBuffer()
    {
        buffer = new Queue<LoggingEvent>();
    }

    private void ForwardingThreadExecute()
    {
        try
        {
            ForwardLoggingEventsFromBuffer();
        }
        catch (Exception exception)
        {
            // ForwardInternalError("Unexpected error in asynchronous forwarding loop", exception, ThisType);
        }
    }

    private void ForwardLoggingEventsFromBuffer()
    {
        CLSAdapter adapter = new CLSAdapter();
        while (buffer.Count > 0)
        {
            LoggingEvent l = buffer.Dequeue();
            LoggingEventData data = l.GetLoggingEventData();
            adapter.CreateConnection(data.Message);
        }
    }
}

Append将附加到队列中。然后StartForwading通过函数从队列推送到Splunk。

问题是:当我从程序中执行Append之类的操作时,Log.Fatal("hhhh")没有被触发。创建这个自定义appender时我缺少什么?

1 个答案:

答案 0 :(得分:0)

<appender name="AsyncForwardingAppenderExtender" type="log4net.Async.AsyncForwardingAppender,Log4net.Async" >

类型错误 - 应该是你的AsyncForwardingAppenderExtender