| | | 1 | | using System.Collections.Concurrent; |
| | | 2 | | |
| | | 3 | | namespace AmbientServices; |
| | | 4 | | |
| | | 5 | | /// <summary> |
| | | 6 | | /// Limits in-memory buffering for ambient log queues. When a queue is full, additional lines are written via the ambien |
| | | 7 | | /// </summary> |
| | | 8 | | /// <remarks> |
| | | 9 | | /// <pitch>The shared guardrail that keeps a logging burst from exhausting process memory: every in-memory log queue in |
| | | 10 | | /// <pledge>Below the cap (100,000 lines by default) the line is enqueued normally; at or above it, the line goes to the |
| | | 11 | | /// <plan>A count check against the <see cref="ConcurrentQueue{T}"/> followed by either an enqueue or a swallow-all-exce |
| | | 12 | | /// <priority> |
| | | 13 | | /// 1. Bounded process memory over never losing a line: past the cap, lines divert to the overflow writer instead of gro |
| | | 14 | | /// 2. An approximate cap over an exact one: the check is lock-free, so concurrent writers near the boundary may briefly |
| | | 15 | | /// 3. Never throwing over reporting an overflow failure: the call swallows everything, a missing or failing overflow wr |
| | | 16 | | /// </priority> |
| | | 17 | | /// </remarks> |
| | | 18 | | internal static class AmbientLogBufferLimits |
| | | 19 | | { |
| | 2 | 20 | | private static readonly AmbientService<IAmbientLogOverflowWriter> _OverflowWriter = Ambient.GetService<IAmbientLogOv |
| | | 21 | | |
| | | 22 | | /// <summary> |
| | | 23 | | /// Maximum number of lines held in an in-memory log buffer before additional lines overflow to disk. |
| | | 24 | | /// </summary> |
| | | 25 | | public const int DefaultMaxBufferedLines = 100_000; |
| | | 26 | | |
| | | 27 | | /// <summary> |
| | | 28 | | /// Enqueues <paramref name="line"/> when the queue is below the limit; otherwise writes the line via <see cref="IAm |
| | | 29 | | /// </summary> |
| | | 30 | | public static void EnqueueOrOverflow(ConcurrentQueue<string> queue, string line, int maxBufferedLines = DefaultMaxBu |
| | | 31 | | { |
| | 2 | 32 | | if (queue.Count < maxBufferedLines) |
| | | 33 | | { |
| | 2 | 34 | | queue.Enqueue(line); |
| | | 35 | | } |
| | | 36 | | else |
| | | 37 | | { |
| | | 38 | | try |
| | | 39 | | { |
| | 2 | 40 | | IAmbientLogOverflowWriter? writer = _OverflowWriter.Local ?? _OverflowWriter.Global; |
| | 2 | 41 | | writer?.WriteOverflowLine(line); |
| | 2 | 42 | | } |
| | | 43 | | #pragma warning disable CA1031 |
| | 2 | 44 | | catch |
| | | 45 | | #pragma warning restore CA1031 |
| | | 46 | | { |
| | 2 | 47 | | } |
| | | 48 | | } |
| | 2 | 49 | | } |
| | | 50 | | } |