| | | 1 | | using System; |
| | | 2 | | using System.Collections.Concurrent; |
| | | 3 | | using System.Diagnostics; |
| | | 4 | | using System.Diagnostics.CodeAnalysis; |
| | | 5 | | |
| | | 6 | | #if NET5_0_OR_GREATER |
| | | 7 | | using System.Runtime.Versioning; |
| | | 8 | | #endif |
| | | 9 | | using System.Text; |
| | | 10 | | using System.Threading; |
| | | 11 | | using System.Threading.Tasks; |
| | | 12 | | |
| | | 13 | | namespace AmbientServices; |
| | | 14 | | |
| | | 15 | | /// <summary> |
| | | 16 | | /// A very basic ambient logger that just sends log data to a high-performance asynchronous wrapper on the system consol |
| | | 17 | | /// This logger is higher performance than the default one that writes to files, but its output persists only if somethi |
| | | 18 | | /// so using the file logger by default is better for diagnosing issues that occur before the user is able to switch log |
| | | 19 | | /// Switch to this logger for better performance, but less persistent log data. |
| | | 20 | | /// Turn the logger off for maximum performance. |
| | | 21 | | /// </summary> |
| | | 22 | | /// <remarks> |
| | | 23 | | /// <pitch>Asynchronous logging to standard output — the natural choice for containers and CLI tools where the console s |
| | | 24 | | /// <pledge><see cref="IAmbientLogger"/></pledge> |
| | | 25 | | /// <pledge><see cref="IAmbientStructuredLogger"/></pledge> |
| | | 26 | | /// <plan> |
| | | 27 | | /// A stateless singleton (<see cref="Instance"/>, private constructor) that forwards every line to the process-wide <se |
| | | 28 | | /// Trade-off profile: same buffering machinery and speed as <see cref="AmbientTraceLogger"/>, but delivered to stdout i |
| | | 29 | | /// </plan> |
| | | 30 | | /// <priority> |
| | | 31 | | /// <see cref="IAmbientLogger"/> |
| | | 32 | | /// 1. Logging-path speed over durability: persistence is whatever is capturing stdout, and with nothing capturing it th |
| | | 33 | | /// </priority> |
| | | 34 | | /// </remarks> |
| | | 35 | | public class AmbientConsoleLogger : IAmbientLogger, IAmbientStructuredLogger |
| | | 36 | | { |
| | | 37 | | /// <summary> |
| | | 38 | | /// Gets the default instance of the ambient console logger. |
| | | 39 | | /// </summary> |
| | 2 | 40 | | public static AmbientConsoleLogger Instance { get; } = new(); |
| | | 41 | | |
| | | 42 | | /// <summary> |
| | | 43 | | /// Constructs an ambient console logger, an implementation of <see cref="IAmbientLogger"/> that outputs log data to |
| | | 44 | | /// </summary> |
| | 2 | 45 | | private AmbientConsoleLogger() |
| | | 46 | | { |
| | 2 | 47 | | } |
| | | 48 | | /// <summary> |
| | | 49 | | /// Buffers the specified structured data to be asynchronously logged. |
| | | 50 | | /// </summary> |
| | | 51 | | /// <param name="structuredData">The structured data object.</param> |
| | | 52 | | #if NET5_0_OR_GREATER |
| | | 53 | | [UnsupportedOSPlatform("browser")] |
| | | 54 | | #endif |
| | | 55 | | public void Log(object structuredData) |
| | | 56 | | { |
| | | 57 | | #if NET5_0_OR_GREATER |
| | 2 | 58 | | ArgumentNullException.ThrowIfNull(structuredData); |
| | | 59 | | #else |
| | | 60 | | if (structuredData is null) throw new ArgumentNullException(nameof(structuredData)); |
| | | 61 | | #endif |
| | 2 | 62 | | string message = AmbientLogger.ConvertStructuredDataIntoSimpleMessage(structuredData); |
| | 2 | 63 | | Log(message); |
| | 2 | 64 | | } |
| | | 65 | | /// <summary> |
| | | 66 | | /// Adds the specified message to the log. |
| | | 67 | | /// </summary> |
| | | 68 | | /// <param name="message">An optional message to log.</param> |
| | | 69 | | #if NET5_0_OR_GREATER |
| | | 70 | | [UnsupportedOSPlatform("browser")] |
| | | 71 | | #endif |
| | | 72 | | public void Log(string message) |
| | | 73 | | { |
| | 2 | 74 | | ConsoleBuffer.BufferLine(message); |
| | 2 | 75 | | } |
| | | 76 | | /// <summary> |
| | | 77 | | /// Asynchronously flushes log entries to the system console output. |
| | | 78 | | /// </summary> |
| | | 79 | | #if NET5_0_OR_GREATER |
| | | 80 | | [UnsupportedOSPlatform("browser")] |
| | | 81 | | #endif |
| | | 82 | | public async ValueTask Flush(CancellationToken cancel = default) |
| | | 83 | | { |
| | 2 | 84 | | await ConsoleBuffer.Flush(cancel); |
| | 2 | 85 | | } |
| | | 86 | | } |
| | | 87 | | /// <summary> |
| | | 88 | | /// A class to buffer debug console messages and display them asynchronously. |
| | | 89 | | /// </summary> |
| | | 90 | | /// <remarks> |
| | | 91 | | /// <pitch>The process-wide asynchronous buffer between logging callers and <see cref="Console"/>: buffering a line is a |
| | | 92 | | /// <pledge> |
| | | 93 | | /// Buffering never blocks on console I/O and may be called concurrently from any thread; buffered lines are written to |
| | | 94 | | /// When the in-memory buffer is at capacity, additional lines spill to the ambient <see cref="IAmbientLogOverflowWriter |
| | | 95 | | /// </pledge> |
| | | 96 | | /// <plan> |
| | | 97 | | /// A static <see cref="ConcurrentQueue{T}"/> drained by one dedicated below-normal-priority background thread that batc |
| | | 98 | | /// Structurally a sibling of <see cref="TraceBuffer"/> with <see cref="Console"/> substituted for <see cref="System.Dia |
| | | 99 | | /// </plan> |
| | | 100 | | /// </remarks> |
| | | 101 | | #if NET5_0_OR_GREATER |
| | | 102 | | [UnsupportedOSPlatform("browser")] |
| | | 103 | | #endif |
| | | 104 | | public static class ConsoleBuffer |
| | | 105 | | { |
| | | 106 | | private static readonly string _FlushString = Guid.NewGuid().ToString(); |
| | | 107 | | private static readonly ConcurrentQueue<string> _Queue = new(); |
| | | 108 | | private static readonly SemaphoreSlim _Semaphore = new(0, short.MaxValue); |
| | | 109 | | private static readonly Thread _FlusherThread = FlusherThread(); |
| | | 110 | | private static readonly SemaphoreSlim _FlusherSemaphore = new(0, short.MaxValue); |
| | | 111 | | |
| | | 112 | | private static Thread FlusherThread() |
| | | 113 | | { |
| | | 114 | | // fire up a background thread to flush the console data |
| | | 115 | | Thread thread = new(new ThreadStart(ConsoleBufferBackgroundFlusher)) { |
| | | 116 | | IsBackground = true, |
| | | 117 | | Name = "ConsoleBuffer.FlusherThread", |
| | | 118 | | Priority = ThreadPriority.BelowNormal, |
| | | 119 | | }; |
| | | 120 | | thread.Start(); |
| | | 121 | | return thread; |
| | | 122 | | } |
| | | 123 | | /// <summary> |
| | | 124 | | /// Buffers the specified line to the concurrent buffer. |
| | | 125 | | /// </summary> |
| | | 126 | | /// <param name="s">The string to buffer.</param> |
| | | 127 | | public static void BufferLine(string s) |
| | | 128 | | { |
| | | 129 | | Buffer(s + Environment.NewLine); |
| | | 130 | | } |
| | | 131 | | private static void Buffer(string s) |
| | | 132 | | { |
| | | 133 | | // enqueue the string given to us (or spill to the standard local overflow log when the buffer is full) |
| | | 134 | | AmbientLogBufferLimits.EnqueueOrOverflow(_Queue, s); |
| | | 135 | | // release the semaphore so the data gets processed |
| | | 136 | | Release(false).Wait(); |
| | | 137 | | } |
| | | 138 | | [DebuggerStepThrough] |
| | | 139 | | private static bool Release() |
| | | 140 | | { |
| | | 141 | | try |
| | | 142 | | { |
| | | 143 | | _Semaphore.Release(); |
| | | 144 | | return true; |
| | | 145 | | } |
| | | 146 | | catch (SemaphoreFullException) |
| | | 147 | | { |
| | | 148 | | // failure! |
| | | 149 | | return false; |
| | | 150 | | } |
| | | 151 | | } |
| | | 152 | | private static async Task Release(bool flush, CancellationToken cancel = default) |
| | | 153 | | { |
| | | 154 | | try |
| | | 155 | | { |
| | | 156 | | // if the release fails, flush the queue |
| | | 157 | | if (!Release()) flush = true; |
| | | 158 | | cancel.ThrowIfCancellationRequested(); |
| | | 159 | | // are we flushing? |
| | | 160 | | if (flush) |
| | | 161 | | { |
| | | 162 | | // boost the priority of the flusher thread for a bit |
| | | 163 | | _FlusherThread.Priority = ThreadPriority.AboveNormal; |
| | | 164 | | cancel.ThrowIfCancellationRequested(); |
| | | 165 | | // wait for the flush to happen |
| | | 166 | | await _FlusherSemaphore.WaitAsync(cancel); |
| | | 167 | | } |
| | | 168 | | } |
| | | 169 | | finally |
| | | 170 | | { |
| | | 171 | | // restore the thread priority |
| | | 172 | | if (flush) _FlusherThread.Priority = ThreadPriority.BelowNormal; |
| | | 173 | | } |
| | | 174 | | } |
| | | 175 | | /// <summary> |
| | | 176 | | /// Asynchronously flushes any queued console lines. |
| | | 177 | | /// </summary> |
| | | 178 | | /// <param name="cancel">A <see cref="CancellationToken"/> that the caller can use to interrupt the operation before |
| | | 179 | | public static async ValueTask Flush(CancellationToken cancel = default) |
| | | 180 | | { |
| | | 181 | | // queue a flush command |
| | | 182 | | _Queue.Enqueue(_FlushString); |
| | | 183 | | // release the semaphore so the data gets processed |
| | | 184 | | await Release(true, cancel); |
| | | 185 | | } |
| | | 186 | | /// <summary> |
| | | 187 | | /// Peeks at all unflushed messages synchronously (for diagnostic purposes only). |
| | | 188 | | /// </summary> |
| | | 189 | | [ExcludeFromCoverage] |
| | | 190 | | [ExcludeFromCodeCoverage, Obsolete("This property should not be used directly--it's only for debugging!")] |
| | | 191 | | public static string PeekUnflushed |
| | | 192 | | { |
| | | 193 | | get |
| | | 194 | | { |
| | | 195 | | StringBuilder ret = new(); |
| | | 196 | | foreach (string s in _Queue) |
| | | 197 | | { |
| | | 198 | | // add this to the result |
| | | 199 | | ret.Append(s); |
| | | 200 | | } |
| | | 201 | | // return the data |
| | | 202 | | return ret.ToString(); |
| | | 203 | | } |
| | | 204 | | } |
| | | 205 | | private static void ConsoleBufferBackgroundFlusher() |
| | | 206 | | { |
| | | 207 | | // loop forever! |
| | | 208 | | while (true) |
| | | 209 | | { |
| | | 210 | | try |
| | | 211 | | { |
| | | 212 | | StringBuilder consoleData = new(); |
| | | 213 | | // get up to 10 lines of console data |
| | | 214 | | for (int line = 0; line < 10; ++line) |
| | | 215 | | { |
| | | 216 | | // get the oldest item on the queue |
| | | 217 | | string? s; |
| | | 218 | | // is there a string to console? |
| | | 219 | | if (_Queue.TryDequeue(out s)) |
| | | 220 | | { |
| | | 221 | | if (s == _FlushString) |
| | | 222 | | { |
| | | 223 | | // release the flusher that told us to flush |
| | | 224 | | _FlusherSemaphore.Release(); |
| | | 225 | | } |
| | | 226 | | else |
| | | 227 | | { |
| | | 228 | | // add this to the console data |
| | | 229 | | consoleData.Append(s); |
| | | 230 | | } |
| | | 231 | | // is there more data? (don't wait if there isn't) |
| | | 232 | | if (_Semaphore.Wait(0)) |
| | | 233 | | { |
| | | 234 | | // try to get some more data (up to ten lines) |
| | | 235 | | continue; |
| | | 236 | | } |
| | | 237 | | // else no data left in queue--no point in waiting before we flush to the output |
| | | 238 | | } |
| | | 239 | | // else nothing left in the queue |
| | | 240 | | else break; |
| | | 241 | | } |
| | | 242 | | // is there a string to console? |
| | | 243 | | if (consoleData.Length > 0) |
| | | 244 | | { |
| | | 245 | | // console out this string |
| | | 246 | | Console.Write(consoleData.ToString()); |
| | | 247 | | } |
| | | 248 | | else |
| | | 249 | | { |
| | | 250 | | // wait for more work (ie. stop using CPU until there is more work to do) |
| | | 251 | | _Semaphore.Wait(TimeSpan.FromMinutes(5)); // we shouldn't ever hang here, but just in case, exit * |
| | | 252 | | } |
| | | 253 | | } |
| | | 254 | | catch (Exception ex) |
| | | 255 | | { |
| | | 256 | | // console out this string |
| | | 257 | | Console.Write(ex.ToString()); |
| | | 258 | | } |
| | | 259 | | } |
| | | 260 | | } |
| | | 261 | | } |