LoggingIntoEventBus.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. using Microsoft.Extensions.Logging;
  2. using WarcViewerBlazorWinForm.Library.EventBus;
  3. namespace WarcViewerBlazorWinForm.Backend.Logging
  4. {
  5. internal class LoggingIntoEventBus : ILoggerProvider
  6. {
  7. public IEventBus? EventBus { get; set; }
  8. public void Dispose()
  9. {
  10. }
  11. public ILogger CreateLogger(string categoryName)
  12. {
  13. return new LoggingIntoEventBusLogger(categoryName, this);
  14. }
  15. private class LoggingIntoEventBusLogger : ILogger
  16. {
  17. private readonly string _categoryName;
  18. private readonly LoggingIntoEventBus _owner;
  19. private const string CAT_TRIM_PREFIX1 = $"{nameof(WarcViewerBlazorWinForm)}.";
  20. public LoggingIntoEventBusLogger(string categoryName, LoggingIntoEventBus owner)
  21. {
  22. _categoryName = categoryName;
  23. if (_categoryName.StartsWith(CAT_TRIM_PREFIX1)) _categoryName = _categoryName[CAT_TRIM_PREFIX1.Length..];
  24. _owner = owner;
  25. }
  26. public IDisposable? BeginScope<TState>(TState state) where TState : notnull => default;
  27. public bool IsEnabled(LogLevel logLevel) => true;
  28. public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
  29. {
  30. if (_owner.EventBus == null) return;
  31. var content = Convert.ToString(state);
  32. if (exception != null)
  33. {
  34. content = $"{content} {exception}";
  35. }
  36. var formatted = $"[{DateTime.Now:dd HH:mm:ss}] {_categoryName} {content}";
  37. _owner.EventBus.Publish(new LoggingEvent(logLevel, _categoryName, formatted));
  38. }
  39. }
  40. }
  41. }