问题
I've implemented BufferingAppenderSkeleton in my custom logger class and override SendBuffer method for logging batch logs in the database.
Here is an implementation:
protected override void SendBuffer(LoggingEvent[] events)
{
List<Log> logs = new List<Log>();
if (events != null && events.Length > 0)
{
foreach (var log in events)
{
var logWithLogSessionId = GetLogWithLogSession(log);
logs.Add(logWithLogSessionId);
}
}
Analytics.SaveLogs(logs);
}
And here web.config configuration for log4net:
<log4net>
<appender name="LogAppender" type="MyApp.LogAppender">
<bufferSize value="20"/>
</appender>
<root>
<level value="DEBUG"/>
<appender-ref ref="LogAppender"/>
</root>
As per documentation, this method will trigger only when event count reaches equal to configured buffer size but sometimes this is calling with random event counts.
eg. Sometimes triggers when there is only 1 event in the buffer, sometimes when event count reached buffer size + 1 etc?
回答1:
BufferSize property represents number of events that can be stored in memory, not number of event to be send in SendBuffer method. If you set BufferSize to 20, than 21st event will trigger that method and will be sent with other events as well. Check SendFromBuffer method in BufferingAppenderSkeleton class.
So basically, if you want to send 20 events in batch, set your BufferSize to 19.
This might seems wrong, but you will need to see how Lossy and Evaluator properties in BufferingAppenderSkeleton works. If you set Lossy to true, then you will only keep 20 latest/most important messages in memory, and disregards oldest events until Evaluator triggers SendBuffer. Check implementation of Append method to fully understand this.
来源:https://stackoverflow.com/questions/51502502/why-sometimes-log4net-events-are-logging-with-random-event-count-though-buffer