-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
AsyncTargetWrapper.cs
593 lines (542 loc) · 22.9 KB
/
AsyncTargetWrapper.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
//
// Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.Targets.Wrappers
{
using System;
using System.ComponentModel;
using System.Threading;
using NLog.Common;
using NLog.Internal;
/// <summary>
/// Provides asynchronous, buffered execution of target writes.
/// </summary>
/// <seealso href="https://github.com/nlog/nlog/wiki/AsyncWrapper-target">Documentation on NLog Wiki</seealso>
/// <remarks>
/// <p>
/// Asynchronous target wrapper allows the logger code to execute more quickly, by queueing
/// messages and processing them in a separate thread. You should wrap targets
/// that spend a non-trivial amount of time in their Write() method with asynchronous
/// target to speed up logging.
/// </p>
/// <p>
/// Because asynchronous logging is quite a common scenario, NLog supports a
/// shorthand notation for wrapping all targets with AsyncWrapper. Just add async="true" to
/// the <targets/> element in the configuration file.
/// </p>
/// <code lang="XML">
/// <![CDATA[
/// <targets async="true">
/// ... your targets go here ...
/// </targets>
/// ]]></code>
/// </remarks>
/// <example>
/// <p>
/// To set up the target in the <a href="config.html">configuration file</a>,
/// use the following syntax:
/// </p>
/// <code lang="XML" source="examples/targets/Configuration File/AsyncWrapper/NLog.config" />
/// <p>
/// The above examples assume just one target and a single rule. See below for
/// a programmatic configuration that's equivalent to the above config file:
/// </p>
/// <code lang="C#" source="examples/targets/Configuration API/AsyncWrapper/Wrapping File/Example.cs" />
/// </example>
[Target("AsyncWrapper", IsWrapper = true)]
public class AsyncTargetWrapper : WrapperTargetBase
{
private readonly object _writeLockObject = new object();
private readonly object _timerLockObject = new object();
private Timer _lazyWriterTimer;
private readonly ReusableAsyncLogEventList _reusableAsyncLogEventList = new ReusableAsyncLogEventList(200);
private event EventHandler<LogEventDroppedEventArgs> _logEventDroppedEvent;
private event EventHandler<LogEventQueueGrowEventArgs> _eventQueueGrowEvent;
/// <summary>
/// Initializes a new instance of the <see cref="AsyncTargetWrapper" /> class.
/// </summary>
public AsyncTargetWrapper()
: this(null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AsyncTargetWrapper" /> class.
/// </summary>
/// <param name="name">Name of the target.</param>
/// <param name="wrappedTarget">The wrapped target.</param>
public AsyncTargetWrapper(string name, Target wrappedTarget)
: this(wrappedTarget)
{
Name = name;
}
/// <summary>
/// Initializes a new instance of the <see cref="AsyncTargetWrapper" /> class.
/// </summary>
/// <param name="wrappedTarget">The wrapped target.</param>
public AsyncTargetWrapper(Target wrappedTarget)
: this(wrappedTarget, 10000, AsyncTargetWrapperOverflowAction.Discard)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AsyncTargetWrapper" /> class.
/// </summary>
/// <param name="wrappedTarget">The wrapped target.</param>
/// <param name="queueLimit">Maximum number of requests in the queue.</param>
/// <param name="overflowAction">The action to be taken when the queue overflows.</param>
public AsyncTargetWrapper(Target wrappedTarget, int queueLimit, AsyncTargetWrapperOverflowAction overflowAction)
{
#if NETSTANDARD2_0
// NetStandard20 includes many optimizations for ConcurrentQueue:
// - See: https://blogs.msdn.microsoft.com/dotnet/2017/06/07/performance-improvements-in-net-core/
// Net40 ConcurrencyQueue can seem to leak, because it doesn't clear properly on dequeue
// - See: https://blogs.msdn.microsoft.com/pfxteam/2012/05/08/concurrentqueuet-holding-on-to-a-few-dequeued-elements/
_requestQueue = new ConcurrentRequestQueue(10000, AsyncTargetWrapperOverflowAction.Discard);
#else
_requestQueue = new AsyncRequestQueue(10000, AsyncTargetWrapperOverflowAction.Discard);
#endif
TimeToSleepBetweenBatches = 1;
BatchSize = 200;
FullBatchSizeWriteLimit = 5;
WrappedTarget = wrappedTarget;
QueueLimit = queueLimit;
OverflowAction = overflowAction;
}
/// <summary>
/// Gets or sets the number of log events that should be processed in a batch
/// by the lazy writer thread.
/// </summary>
/// <docgen category='Buffering Options' order='100' />
[DefaultValue(200)]
public int BatchSize { get; set; }
/// <summary>
/// Gets or sets the time in milliseconds to sleep between batches. (1 or less means trigger on new activity)
/// </summary>
/// <docgen category='Buffering Options' order='100' />
[DefaultValue(1)]
public int TimeToSleepBetweenBatches { get; set; }
/// <summary>
/// Raise event when Target cannot store LogEvent.
/// Event arg contains lost LogEvents
/// </summary>
public event EventHandler<LogEventDroppedEventArgs> LogEventDropped
{
add
{
if (_logEventDroppedEvent == null && _requestQueue != null )
{
_requestQueue.LogEventDropped += OnRequestQueueDropItem;
}
_logEventDroppedEvent += value;
}
remove
{
_logEventDroppedEvent -= value;
if (_logEventDroppedEvent == null && _requestQueue != null)
{
_requestQueue.LogEventDropped -= OnRequestQueueDropItem;
}
}
}
/// <summary>
/// Raises when event queue grow.
/// Queue can grow when <see cref="OverflowAction"/> was set to <see cref="AsyncTargetWrapperOverflowAction.Grow"/>
/// </summary>
public event EventHandler<LogEventQueueGrowEventArgs> EventQueueGrow
{
add
{
if (_eventQueueGrowEvent == null && _requestQueue != null)
{
_requestQueue.LogEventQueueGrow += OnRequestQueueGrow;
}
_eventQueueGrowEvent += value;
}
remove
{
_eventQueueGrowEvent -= value;
if (_eventQueueGrowEvent == null && _requestQueue != null)
{
_requestQueue.LogEventQueueGrow -= OnRequestQueueGrow;
}
}
}
/// <summary>
/// Gets or sets the action to be taken when the lazy writer thread request queue count
/// exceeds the set limit.
/// </summary>
/// <docgen category='Buffering Options' order='100' />
[DefaultValue("Discard")]
public AsyncTargetWrapperOverflowAction OverflowAction
{
get => _requestQueue.OnOverflow;
set => _requestQueue.OnOverflow = value;
}
/// <summary>
/// Gets or sets the limit on the number of requests in the lazy writer thread request queue.
/// </summary>
/// <docgen category='Buffering Options' order='100' />
[DefaultValue(10000)]
public int QueueLimit
{
get => _requestQueue.RequestLimit;
set => _requestQueue.RequestLimit = value;
}
/// <summary>
/// Gets or sets the limit of full <see cref="BatchSize"/>s to write before yielding into <see cref="TimeToSleepBetweenBatches"/>
/// Performance is better when writing many small batches, than writing a single large batch
/// </summary>
/// <docgen category='Buffering Options' order='100' />
[DefaultValue(5)]
public int FullBatchSizeWriteLimit { get; set; }
/// <summary>
/// Gets or sets whether to use the locking queue, instead of a lock-free concurrent queue
/// The locking queue is less concurrent when many logger threads, but reduces memory allocation
/// </summary>
/// <docgen category='Buffering Options' order='100' />
[DefaultValue(false)]
public bool ForceLockingQueue { get => _forceLockingQueue ?? false; set => _forceLockingQueue = value; }
private bool? _forceLockingQueue;
/// <summary>
/// Gets the queue of lazy writer thread requests.
/// </summary>
AsyncRequestQueueBase _requestQueue;
/// <summary>
/// Schedules a flush of pending events in the queue (if any), followed by flushing the WrappedTarget.
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
protected override void FlushAsync(AsyncContinuation asyncContinuation)
{
if (_flushEventsInQueueDelegate == null)
_flushEventsInQueueDelegate = new AsyncHelpersTask(FlushEventsInQueue);
AsyncHelpers.StartAsyncTask(_flushEventsInQueueDelegate.Value, asyncContinuation);
}
private AsyncHelpersTask? _flushEventsInQueueDelegate;
/// <summary>
/// Initializes the target by starting the lazy writer timer.
/// </summary>
protected override void InitializeTarget()
{
base.InitializeTarget();
if (!OptimizeBufferReuse && WrappedTarget != null && WrappedTarget.OptimizeBufferReuse)
{
OptimizeBufferReuse = GetType() == typeof(AsyncTargetWrapper); // Class not sealed, reduce breaking changes
if (!OptimizeBufferReuse && !ForceLockingQueue)
{
ForceLockingQueue = true; // Avoid too much allocation, when wrapping a legacy target
}
}
if (!ForceLockingQueue && OverflowAction == AsyncTargetWrapperOverflowAction.Block && BatchSize * 1.5m > QueueLimit)
{
ForceLockingQueue = true; // ConcurrentQueue does not perform well if constantly hitting QueueLimit
}
#if NET4_5 || NET4_0
if (_forceLockingQueue.HasValue && _forceLockingQueue.Value != (_requestQueue is AsyncRequestQueue))
{
_requestQueue = ForceLockingQueue ? (AsyncRequestQueueBase)new AsyncRequestQueue(QueueLimit, OverflowAction) : new ConcurrentRequestQueue(QueueLimit, OverflowAction);
}
#endif
if (BatchSize > QueueLimit && TimeToSleepBetweenBatches <= 1)
{
BatchSize = QueueLimit; // Avoid too much throttling
}
_requestQueue.Clear();
InternalLogger.Trace("AsyncWrapper(Name={0}): Start Timer", Name);
_lazyWriterTimer = new Timer(ProcessPendingEvents, null, Timeout.Infinite, Timeout.Infinite);
StartLazyWriterTimer();
}
/// <summary>
/// Shuts down the lazy writer timer.
/// </summary>
protected override void CloseTarget()
{
StopLazyWriterThread();
if (Monitor.TryEnter(_writeLockObject, 500))
{
try
{
WriteEventsInQueue(int.MaxValue, "Closing Target");
}
finally
{
Monitor.Exit(_writeLockObject);
}
}
if (OverflowAction == AsyncTargetWrapperOverflowAction.Block)
{
_requestQueue.Clear(); // Try to eject any threads, that are blocked in the RequestQueue
}
base.CloseTarget();
}
/// <summary>
/// Starts the lazy writer thread which periodically writes
/// queued log messages.
/// </summary>
protected virtual void StartLazyWriterTimer()
{
lock (_timerLockObject)
{
if (_lazyWriterTimer != null)
{
if (TimeToSleepBetweenBatches <= 1)
{
InternalLogger.Trace("AsyncWrapper(Name={0}): Throttled timer scheduled", Name);
_lazyWriterTimer.Change(1, Timeout.Infinite);
}
else
{
_lazyWriterTimer.Change(TimeToSleepBetweenBatches, Timeout.Infinite);
}
}
}
}
/// <summary>
/// Attempts to start an instant timer-worker-thread which can write
/// queued log messages.
/// </summary>
/// <returns>Returns true when scheduled a timer-worker-thread</returns>
protected virtual bool StartInstantWriterTimer()
{
return StartTimerUnlessWriterActive(true);
}
private bool StartTimerUnlessWriterActive(bool instant)
{
bool lockTaken = false;
try
{
lockTaken = Monitor.TryEnter(_writeLockObject);
if (lockTaken)
{
// Lock taken means no other timer-worker-thread is trying to write, schedule timer now
if (instant)
{
lock (_timerLockObject)
{
if (_lazyWriterTimer != null)
{
// Not optimal to schedule timer-worker-thread while holding lock,
// as the newly scheduled timer-worker-thread will hammer into the writeLockObject
_lazyWriterTimer.Change(0, Timeout.Infinite);
return true;
}
}
}
else
{
StartLazyWriterTimer();
return true;
}
}
}
finally
{
// If not able to take lock, then it means timer-worker-thread is already active,
// and timer-worker-thread will check RequestQueue after leaving writeLockObject
if (lockTaken)
Monitor.Exit(_writeLockObject);
}
return false;
}
/// <summary>
/// Stops the lazy writer thread.
/// </summary>
protected virtual void StopLazyWriterThread()
{
lock (_timerLockObject)
{
var currentTimer = _lazyWriterTimer;
if (currentTimer != null)
{
_lazyWriterTimer = null;
currentTimer.WaitForDispose(TimeSpan.FromSeconds(1));
}
}
}
/// <summary>
/// Adds the log event to asynchronous queue to be processed by
/// the lazy writer thread.
/// </summary>
/// <param name="logEvent">The log event.</param>
/// <remarks>
/// The <see cref="Target.PrecalculateVolatileLayouts"/> is called
/// to ensure that the log event can be processed in another thread.
/// </remarks>
protected override void Write(AsyncLogEventInfo logEvent)
{
PrecalculateVolatileLayouts(logEvent.LogEvent);
bool queueWasEmpty = _requestQueue.Enqueue(logEvent);
if (queueWasEmpty)
{
if (TimeToSleepBetweenBatches == 0)
StartInstantWriterTimer();
else if (TimeToSleepBetweenBatches <= 1)
StartTimerUnlessWriterActive(false);
}
}
/// <summary>
/// Write to queue without locking <see cref="Target.SyncRoot"/>
/// </summary>
/// <param name="logEvent"></param>
protected override void WriteAsyncThreadSafe(AsyncLogEventInfo logEvent)
{
try
{
Write(logEvent);
}
catch (Exception exception)
{
if (ExceptionMustBeRethrown(exception))
{
throw;
}
logEvent.Continuation(exception);
}
}
private void ProcessPendingEvents(object state)
{
if (_lazyWriterTimer == null)
return;
bool wroteFullBatchSize = false;
try
{
lock (_writeLockObject)
{
int count = WriteEventsInQueue(BatchSize, "Timer");
if (count == BatchSize)
wroteFullBatchSize = true;
if (wroteFullBatchSize && TimeToSleepBetweenBatches <= 1)
StartInstantWriterTimer(); // Found full batch, fast schedule to take next batch (within lock to avoid pile up)
}
}
catch (Exception exception)
{
wroteFullBatchSize = false; // Something went wrong, lets throttle retry
InternalLogger.Error(exception, "AsyncWrapper(Name={0}): Error in lazy writer timer procedure.", Name);
#if DEBUG
if (exception.MustBeRethrownImmediately())
{
throw; // Throwing exceptions here will crash the entire application (.NET 2.0 behavior)
}
#endif
}
finally
{
if (TimeToSleepBetweenBatches <= 1)
{
if (!wroteFullBatchSize && !_requestQueue.IsEmpty)
{
// If queue was not empty, then more might have arrived while writing the first batch
// Do not use instant timer, so we can process in larger batches (faster)
StartTimerUnlessWriterActive(false);
}
}
else
{
StartLazyWriterTimer();
}
}
}
private void FlushEventsInQueue(object state)
{
try
{
var asyncContinuation = state as AsyncContinuation;
lock (_writeLockObject)
{
WriteEventsInQueue(int.MaxValue, "Flush Async");
if (asyncContinuation != null)
base.FlushAsync(asyncContinuation);
}
if (TimeToSleepBetweenBatches <= 1 && !_requestQueue.IsEmpty)
StartTimerUnlessWriterActive(false);
}
catch (Exception exception)
{
InternalLogger.Error(exception, "AsyncWrapper(Name={0}): Error in flush procedure.", Name);
#if DEBUG
if (exception.MustBeRethrownImmediately())
{
throw; // Throwing exceptions here will crash the entire application (.NET 2.0 behavior)
}
#endif
}
}
private int WriteEventsInQueue(int batchSize, string reason)
{
if (WrappedTarget == null)
{
InternalLogger.Error("AsyncWrapper(Name={0}): WrappedTarget is NULL", Name);
return 0;
}
int count = 0;
for (int i = 0; i < FullBatchSizeWriteLimit; ++i)
{
if (!OptimizeBufferReuse || batchSize == int.MaxValue)
{
var logEvents = _requestQueue.DequeueBatch(batchSize);
if (logEvents.Length > 0)
{
if (reason != null)
InternalLogger.Trace("AsyncWrapper(Name={0}): Writing {1} events ({2})", Name, logEvents.Length, reason);
WrappedTarget.WriteAsyncLogEvents(logEvents);
}
count = logEvents.Length;
}
else
{
using (var targetList = _reusableAsyncLogEventList.Allocate())
{
var logEvents = targetList.Result;
_requestQueue.DequeueBatch(batchSize, logEvents);
if (logEvents.Count > 0)
{
if (reason != null)
InternalLogger.Trace("AsyncWrapper(Name={0}): Writing {1} events ({2})", Name, logEvents.Count, reason);
WrappedTarget.WriteAsyncLogEvents(logEvents);
}
count = logEvents.Count;
}
}
if (count < batchSize)
break;
}
return count;
}
private void OnRequestQueueDropItem(object sender, LogEventDroppedEventArgs logEventDroppedEventArgs)
{
_logEventDroppedEvent?.Invoke(this, logEventDroppedEventArgs);
}
private void OnRequestQueueGrow(object sender, LogEventQueueGrowEventArgs logEventQueueGrowEventArgs)
{
_eventQueueGrowEvent?.Invoke(this, logEventQueueGrowEventArgs);
}
}
}