Queue is not flushed in OnClose
Closed this issue · 4 comments
When Log4net calls OnClose, any messages in the queue are not flushed; it simply aborts the worker thread, which can lead to lost messages if there aren't delays manually added the application exit process, such as the 5 second sleep at the end of the test application.
Adding delays on exit is problematic (and costly) for components such as Azure Function Apps which are billed per gigabyte-second of execution.
One solution is:
- Use a CancellationToken in Queue.TryTake
- Have the loops inside the worker thread exit when cancellation is requested
- Have the worker thread set a ManualResetEvent after it has exited the main loop
- OnClose should request cancellation using the token, then wait for a limited timeout period on the ManualResetEvent for the worker thread to exit
Hi, sorry for the late reply... I will fix it in the next 3 weeks...
Hi Paul, please take a look at QueueLogger.cs I have try to fix the issue but no time to test it at the moment so I will test it next week and release it with version 2.1.2
Unfortunately, I no longer have access to a system where I can test it but reading the code it looks correct. I'd suggest renaming AbortWorkerManualResetEventTimeoutInSec to AbortTimeoutSeconds - it only needs to describe to the caller what it does, not how it's implemented.
Also, you could improve the efficiency of the buffer StringBuilder:
- use append with char types to append a single character rather than 1 character strings
- use a boolean variable to track if you are in the first loop iteration, and write the comma at the start of the second iteration, rather than always writing a comma and Trimming the string
- add the closing ] to the buffer before calling ToString
- don't call ToString twice (lines 148 & 155)
Hi Paul, thanks for your hints now the issue "Queue is not flushed in OnClose" is fixed the efficiency of the log data buffering is also improved - available as version 2.1.2 on Nuget.org