Gondwana Game Engine Development (master) - 2.7.0
Gondwana is a cross-platform 2.5D game and rendering engine written in C#/.NET 8. It provides fine-grained control over rendering, timing, and scene composition, with built-in support for parallax, z-ordering, pixel overhang, collision detection, and particle effects. Gondwana targets desktop and web platforms using SkiaSharp for graphics and pluggable audio backends for desktop and browser targets.
Loading...
Searching...
No Matches
EngineLogger.cs
1using System.Collections.Concurrent;
2using System.Diagnostics;
3using System.Threading.Channels;
4using Microsoft.Extensions.Logging;
5
7
38public static partial class EngineLogger
39{
40 private static ILoggerFactory? _loggerFactory;
41 private static bool _usingExternalLoggerFactory;
42 private static readonly object _factoryLock = new();
43
44 private static readonly Dictionary<string, Func<ILoggerProvider>> _persistentProviderFactories =
45 new(StringComparer.Ordinal);
46
47 // Cache wrappers (not raw loggers)
48 private static readonly ConcurrentDictionary<Type, ILogger> _loggerCache = new();
49
50 // Mode (default async)
51 private static volatile EngineLoggingMode _mode = EngineLoggingMode.Asynchronous;
52
57 public static event EventHandler<LoggingErrorEventArgs>? LoggingError;
58
68 public static EngineLoggingMode Mode
69 {
70 get => _mode;
71 set
72 {
73 _mode = value;
74
75 // If switching to async, ensure worker exists.
76 // EnsureAsyncStarted is idempotent and safely handles repeated calls.
77 if (_mode == EngineLoggingMode.Asynchronous)
78 EnsureAsyncStarted(forceRestart: false);
79 }
80 }
81
82 // Async pipeline
83 private static readonly object _asyncGate = new();
84 private static Channel<LogEvent>? _channel;
85 private static Task? _worker;
86 private static CancellationTokenSource? _cts;
87
88 // Defaults: bounded + drop on full (fire-and-forget)
89 private const int DefaultCapacity = 8192;
90 private static int _capacity = DefaultCapacity;
91
98 private static ILoggerFactory GetOrCreateLoggerFactory()
99 {
100 if (_loggerFactory != null)
101 return _loggerFactory;
102
103 lock (_factoryLock)
104 {
105 if (_loggerFactory != null)
106 return _loggerFactory;
107
108 // Check if we're running in a browser/WASM environment
109 bool isBrowser = OperatingSystem.IsBrowser();
110
111 _loggerFactory = LoggerFactory.Create(builder =>
112 {
113 builder.AddDebug();
114
115 // Only add Console logger on non-browser platforms
116 // Console logging creates background threads which are not supported in WASM
117 if (!isBrowser)
118 builder.AddConsole();
119
120 AddPersistentProviders(builder);
121 });
122
123 return _loggerFactory;
124 }
125 }
126
131 public static void StartAsyncLogging(int capacity = DefaultCapacity)
132 {
133 if (capacity <= 0)
134 throw new ArgumentOutOfRangeException(nameof(capacity), "Capacity must be > 0.");
135
136 lock (_asyncGate)
137 {
138 _capacity = capacity;
139 }
140
141 EnsureAsyncStarted(forceRestart: false);
142 }
143
149 public static void StopAsyncLogging(bool flush = true, TimeSpan? flushTimeout = null)
150 {
151 Channel<LogEvent>? ch;
152 Task? worker;
153 CancellationTokenSource? cts;
154
155 lock (_asyncGate)
156 {
157 ch = _channel;
158 worker = _worker;
159 cts = _cts;
160
161 if (ch == null || worker == null)
162 return;
163
164 // Completing the writer lets the worker drain then exit.
165 try
166 {
167 ch.Writer.TryComplete();
168 }
169 catch
170 {
171 /* ignore */
172 }
173
174 // Clear shared references so other threads can't enqueue on this instance.
175 _channel = null;
176 _worker = null;
177 _cts = null;
178 }
179
180 try
181 {
182 cts?.Cancel();
183 }
184 catch
185 {
186 /* never crash */
187 }
188
189 if (flush)
190 {
191 var timeout = flushTimeout ?? TimeSpan.FromSeconds(2);
192
193 try
194 {
195 worker!.Wait(timeout);
196 }
197 catch
198 {
199 /* never crash */
200 }
201 }
202
203 try
204 {
205 cts?.Dispose();
206 }
207 catch
208 {
209 /* ignore */
210 }
211 }
212
217 public static void SwitchToSyncAndFlush(TimeSpan? flushTimeout = null)
218 {
219 if (_mode == EngineLoggingMode.Asynchronous)
220 StopAsyncLogging(flush: true, flushTimeout: flushTimeout);
221
222 _mode = EngineLoggingMode.Synchronous;
223 }
224
229 public static void SwitchToAsync(int? capacity = null)
230 {
231 lock (_asyncGate)
232 {
233 if (capacity is not null)
234 {
235 if (capacity.Value <= 0)
236 throw new ArgumentOutOfRangeException(nameof(capacity), "Capacity must be > 0.");
237
238 _capacity = capacity.Value;
239 }
240
241 _mode = EngineLoggingMode.Asynchronous;
242 }
243
244 EnsureAsyncStarted(forceRestart: false);
245 }
246
247 internal static void Initialize(ILoggerFactory loggerFactory)
248 {
249 lock (_factoryLock)
250 {
251 _loggerFactory = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory));
252
253 foreach (Func<ILoggerProvider> providerFactory in _persistentProviderFactories.Values)
254 _loggerFactory.AddProvider(providerFactory());
255
256 _usingExternalLoggerFactory = true;
257 _loggerCache.Clear(); // refresh wrappers
258 }
259 }
260
267 internal static void RegisterPersistentProvider(
268 string key,
269 Func<ILoggerProvider> providerFactory)
270 {
271 ArgumentException.ThrowIfNullOrWhiteSpace(key);
272 ArgumentNullException.ThrowIfNull(providerFactory);
273
274 lock (_factoryLock)
275 {
276 if (_persistentProviderFactories.ContainsKey(key))
277 return;
278
279 _persistentProviderFactories.Add(key, providerFactory);
280 _loggerFactory?.AddProvider(providerFactory());
281 }
282 }
283
292 public static ILoggerFactory EngineLoggerFactory => GetOrCreateLoggerFactory();
293
307 public static ILogger<T> GetLogger<T>() =>
308 (ILogger<T>)_loggerCache.GetOrAdd(typeof(T), static _ => new ModeLogger<T>());
309
322 public static void SetLogLevel(LogLevel level)
323 {
324 lock (_factoryLock)
325 {
326 if (_usingExternalLoggerFactory)
327 return;
328
329 // Check if we're running in a browser/WASM environment
330 bool isBrowser = OperatingSystem.IsBrowser();
331
332 _loggerFactory = LoggerFactory.Create(builder =>
333 {
334 builder.AddDebug()
335 .SetMinimumLevel(level);
336
337 // Only add Console logger on non-browser platforms
338 if (!isBrowser)
339 builder.AddConsole();
340
341 AddPersistentProviders(builder);
342 });
343
344 _loggerCache.Clear(); // refresh wrappers
345 }
346 }
347
348 private static void AddPersistentProviders(ILoggingBuilder builder)
349 {
350 foreach (Func<ILoggerProvider> providerFactory in _persistentProviderFactories.Values)
351 builder.AddProvider(providerFactory());
352 }
353
354 private static void EnsureAsyncStarted(bool forceRestart)
355 {
356 lock (_asyncGate)
357 {
358 EnsureAsyncStarted_NoLock(forceRestart);
359 }
360 }
361
362 // Must be called under _asyncGate.
363 private static void EnsureAsyncStarted_NoLock(bool forceRestart)
364 {
365 if (_mode != EngineLoggingMode.Asynchronous)
366 return;
367
368 if (!forceRestart && _worker != null)
369 return;
370
371 if (forceRestart && _channel != null)
372 {
373 // Best-effort stop without flush; caller controls flush via StopAsyncLogging.
374 try
375 {
376 _channel.Writer.TryComplete();
377 }
378 catch
379 {
380 /* ignore */
381 }
382 }
383
384 int capacityLocal = _capacity;
385
386 var channel = Channel.CreateBounded<LogEvent>(
387 new BoundedChannelOptions(capacityLocal)
388 {
389 SingleReader = true,
390 SingleWriter = false,
391 FullMode = BoundedChannelFullMode.DropWrite // fire-and-forget; drop if full
392 });
393
394 _channel = channel;
395
396 _cts?.Dispose();
397 _cts = new CancellationTokenSource();
398
399 // Pass reader so WorkerLoop never dereferences static _channel (avoids races with Stop).
400 var reader = channel.Reader;
401 var token = _cts.Token;
402 _worker = Task.Run(() => WorkerLoop(reader, token));
403 }
404
405 private static bool TryEnqueue(in LogEvent ev)
406 {
407 lock (_asyncGate)
408 {
409 if (_mode != EngineLoggingMode.Asynchronous)
410 return false;
411
412 EnsureAsyncStarted_NoLock(forceRestart: false);
413
414 var ch = _channel;
415
416 if (ch == null)
417 return false;
418
419 // Fire-and-forget: never block, drop if full
420 return ch.Writer.TryWrite(ev);
421 }
422 }
423
424 private static async Task WorkerLoop(ChannelReader<LogEvent> reader, CancellationToken ct)
425 {
426 try
427 {
428 while (await reader.WaitToReadAsync(ct).ConfigureAwait(false))
429 {
430 while (reader.TryRead(out var ev))
431 {
432 try
433 {
434 // Executes formatting + sinks (console) off the engine thread.
435 var logger = GetOrCreateLoggerFactory().CreateLogger(ev.CategoryName);
436
437 logger.Log(
438 ev.LogLevel,
439 ev.EventId,
440 ev.State,
441 ev.Exception,
442 ev.Formatter);
443 }
444 catch (Exception ex)
445 {
446 // Fallback: write to debug output to aid diagnostics without crashing.
447 Debug.WriteLine($"[EngineLogger] Logging failed: {ex.GetType().Name}: {ex.Message}");
448
449 // Raise event for applications that want to monitor logging failures.
450 try
451 {
452 LoggingError?.Invoke(null, new LoggingErrorEventArgs(ex, ev.CategoryName, ev.LogLevel));
453 }
454 catch
455 {
456 // Never let event handlers crash the logging infrastructure.
457 }
458 }
459 }
460 }
461 }
462 catch (System.OperationCanceledException) when (ct.IsCancellationRequested)
463 {
464 // Normal cancellation: no action required.
465 }
466 catch
467 {
468 // Swallow any channel or unexpected exceptions.
469 }
470 }
471}
472
476public sealed class LoggingErrorEventArgs : EventArgs
477{
481 public Exception Exception { get; }
482
486 public string CategoryName { get; }
487
491 public LogLevel LogLevel { get; }
492
493 internal LoggingErrorEventArgs(Exception exception, string categoryName, LogLevel logLevel)
494 {
495 Exception = exception ?? throw new ArgumentNullException(nameof(exception));
496 CategoryName = categoryName ?? throw new ArgumentNullException(nameof(categoryName));
497 LogLevel = logLevel;
498 }
499}
Provides data for the LoggingError event.
Exception Exception
Gets the exception that occurred during logging.
string CategoryName
Gets the category name of the logger that failed.
LogLevel LogLevel
Gets the log level of the message that failed to log.
EngineLoggingMode
Specifies the logging mode for the engine.