gpt4 book ai didi

c# - Log4Net 自定义 AdoNetAppender 缓冲区问题

转载 作者:太空宇宙 更新时间:2023-11-03 16:46:15 26 4
gpt4 key购买 nike

我正在使用 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 缓冲区已满但从未在数据库中刷新,因为没有更多新日志将“推送”到数据库旧日志中。

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

最佳答案

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

<lossy value="false" />

关于c# - Log4Net 自定义 AdoNetAppender 缓冲区问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5884137/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com