using Microsoft.Extensions.Logging; using WarcViewerBlazorWinForm.Library.EventBus; namespace WarcViewerBlazorWinForm.Backend.Logging { internal class LoggingIntoEventBus : ILoggerProvider { public IEventBus? EventBus { get; set; } public void Dispose() { } public ILogger CreateLogger(string categoryName) { return new LoggingIntoEventBusLogger(categoryName, this); } private class LoggingIntoEventBusLogger : ILogger { private readonly string _categoryName; private readonly LoggingIntoEventBus _owner; private const string CAT_TRIM_PREFIX1 = $"{nameof(WarcViewerBlazorWinForm)}."; public LoggingIntoEventBusLogger(string categoryName, LoggingIntoEventBus owner) { _categoryName = categoryName; if (_categoryName.StartsWith(CAT_TRIM_PREFIX1)) _categoryName = _categoryName[CAT_TRIM_PREFIX1.Length..]; _owner = owner; } public IDisposable? BeginScope(TState state) where TState : notnull => default; public bool IsEnabled(LogLevel logLevel) => true; public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) { if (_owner.EventBus == null) return; var content = Convert.ToString(state); if (exception != null) { content = $"{content} {exception}"; } var formatted = $"[{DateTime.Now:dd HH:mm:ss}] {_categoryName} {content}"; _owner.EventBus.Publish(new LoggingEvent(logLevel, _categoryName, formatted)); } } } }