Log4Net自定义AdoNetAppender缓冲区问题

时间:2011-05-04 13:25:26

标签: c# log4net

我正在使用log4net,我已经从AdoNetAppender创建了自己的appender。我的appender只是实现了一种缓冲区,它允许在一个日志中对相同的事件进行分组(对于数千个相同的错误,我在数据库中只有一行)。

以下是易于理解的代码(我的appender有一个buffersize = 1):

class CustomAdoNetAppender : AdoNetAppender
{
    //My Custom Buffer
    private static List<LoggingEvent> unSendEvents = new List<LoggingEvent>();
    private int customBufferSize = 5;
    private double interval = 100;
    private static DateTime lastSendTime = DateTime.Now;

    protected override void SendBuffer(log4net.Core.LoggingEvent[] events)
    {
        LoggingEvent loggingEvent = events[0];
        LoggingEvent l = unSendEvents.Find(delegate(LoggingEvent logg) { return GetKey(logg).Equals(GetKey(loggingEvent), StringComparison.OrdinalIgnoreCase); });
        //If the events already exist in the custom buffer (unSendEvents) containing the 5 last events
        if (l != null)
        {
            //Iterate the count property
            try
            {
                l.Properties["Count"] = (int)l.Properties["Count"] + 1;
            }
            catch
            {
                l.Properties["Count"] = 1;
            }
        }

        //Else
        else
        {
            //If the custom buffer (unSendEvents) contains 5 events
            if (unSendEvents.Count() == customBufferSize)
            {
                //Persist the older event
                base.SendBuffer(new LoggingEvent[] { unSendEvents.ElementAt(0) });
                //Delete it from the buffer
                unSendEvents.RemoveAt(0);
            }
            //Set count properties to 1
            loggingEvent.Properties["Count"] = 1;
            //Add the event to the pre-buffer 
            unSendEvents.Add(loggingEvent);
        }

        //If timer is over
        TimeSpan timeElapsed = loggingEvent.TimeStamp - lastSendTime;
        if (timeElapsed.TotalSeconds > interval)
        {
            //Persist all events contained in the unSendEvents buffer
            base.SendBuffer(unSendEvents.ToArray());
            //Update send time
            lastSendTime = unSendEvents.ElementAt(unSendEvents.Count() - 1).TimeStamp;
            //Flush the buffer
            unSendEvents.Clear();
        }
    }

    /// <summary>
    /// Function to build a key (aggregation of important properties of a logging event) to facilitate comparison.
    /// </summary>
    /// <param name="logg">The loggign event to get the key.</param>
    /// <returns>Formatted string representing the log event key.</returns>
    private string GetKey(LoggingEvent logg)
    {
        return string.Format("{0}|{1}|{2}|{3}", logg.Properties["ErrorCode"] == null ? string.Empty : logg.Properties["ErrorCode"].ToString()
                                , logg.Level.ToString()
                                , logg.LoggerName
                                , logg.MessageObject.ToString()
                                );
    }
}

缓冲区和计数部分进展顺利。我的问题是我丢失了最后5个日志,因为缓冲区在程序结束时没有刷新。 unSendEvent缓冲区已满,但从未在数据库中刷新,因为不再有新日志会在db旧日志中“推送”。

我有什么解决方案吗?我试过使用Flush()方法,但没有成功。

2 个答案:

答案 0 :(得分:0)

Smtp appender有一个有损参数。如果未将其设置为false,则无法保证获得所有日志消息。听起来这可能是你的问题吗?我使用配置文件,所以这一行是我的appender定义。

<lossy value="false" />

答案 1 :(得分:0)

我有几种方法可以解决这个问题。第一种是将缓冲区大小更改为1(现在为5)。这将确保所有条目立即被写入。但是,这可能并不理想。如果是这种情况,我可以想到的一个解决方法是将五个虚拟日志消息放入缓冲区。这将清除真实的事件,你的虚拟事件将被丢弃。