|
| 1 | +using System; |
| 2 | +using System.Collections.Concurrent; |
| 3 | +using System.Threading; |
| 4 | +using Serilog.Core; |
| 5 | +using Serilog.Debugging; |
| 6 | +using Serilog.Events; |
| 7 | + |
| 8 | +namespace Serilog.Sinks.Async |
| 9 | +{ |
| 10 | + sealed class AsyncWorkerSink : ILogEventSink, IDisposable |
| 11 | + { |
| 12 | + readonly Logger _pipeline; |
| 13 | + readonly int _bufferCapacity; |
| 14 | + volatile bool _disposed; |
| 15 | + readonly CancellationTokenSource _cancel = new CancellationTokenSource(); |
| 16 | + readonly BlockingCollection<LogEvent> _queue; |
| 17 | + readonly Thread _worker; |
| 18 | + |
| 19 | + public AsyncWorkerSink(Logger pipeline, int bufferCapacity) |
| 20 | + { |
| 21 | + if (pipeline == null) throw new ArgumentNullException(nameof(pipeline)); |
| 22 | + if (bufferCapacity <= 0) throw new ArgumentOutOfRangeException(nameof(bufferCapacity)); |
| 23 | + _pipeline = pipeline; |
| 24 | + _bufferCapacity = bufferCapacity; |
| 25 | + _queue = new BlockingCollection<LogEvent>(_bufferCapacity); |
| 26 | + _worker = new Thread(Pump) { IsBackground = true }; |
| 27 | + _worker.Start(); |
| 28 | + } |
| 29 | + |
| 30 | + public void Emit(LogEvent logEvent) |
| 31 | + { |
| 32 | + // The disposed check is racy, but only ensures we don't prevent flush from |
| 33 | + // completing by pushing more events. |
| 34 | + if (!_disposed && !_queue.TryAdd(logEvent)) |
| 35 | + SelfLog.WriteLine("{0} unable to enqueue, capacity {1}", typeof(AsyncWorkerSink), _bufferCapacity); |
| 36 | + } |
| 37 | + |
| 38 | + public void Dispose() |
| 39 | + { |
| 40 | + _disposed = true; |
| 41 | + _cancel.Cancel(); |
| 42 | + _worker.Join(); |
| 43 | + _pipeline.Dispose(); |
| 44 | + // _cancel not disposed, because it will make _cancel.Cancel() non-idempotent |
| 45 | + } |
| 46 | + |
| 47 | + void Pump() |
| 48 | + { |
| 49 | + try |
| 50 | + { |
| 51 | + try |
| 52 | + { |
| 53 | + while (true) |
| 54 | + { |
| 55 | + var next = _queue.Take(_cancel.Token); |
| 56 | + _pipeline.Write(next); |
| 57 | + } |
| 58 | + } |
| 59 | + catch (OperationCanceledException) |
| 60 | + { |
| 61 | + LogEvent next; |
| 62 | + while (_queue.TryTake(out next)) |
| 63 | + _pipeline.Write(next); |
| 64 | + } |
| 65 | + } |
| 66 | + catch (Exception ex) |
| 67 | + { |
| 68 | + SelfLog.WriteLine("{0} fatal error in worker thread: {1}", typeof(AsyncWorkerSink), ex); |
| 69 | + } |
| 70 | + } |
| 71 | + } |
| 72 | +} |
0 commit comments