Add logging to MessageBus initialization and error handling

This commit is contained in:
Thorsten Sommer 2025-06-02 19:10:25 +02:00
parent 1a1a385a0b
commit 4cf00f8123
No known key found for this signature in database
GPG Key ID: B0B7E2FC074BF1F5
2 changed files with 15 additions and 1 deletions

View File

@ -160,6 +160,7 @@ internal sealed class Program
// Get the logging factory for e.g., static classes: // Get the logging factory for e.g., static classes:
LOGGER_FACTORY = app.Services.GetRequiredService<ILoggerFactory>(); LOGGER_FACTORY = app.Services.GetRequiredService<ILoggerFactory>();
MessageBus.INSTANCE.Initialize(LOGGER_FACTORY.CreateLogger<MessageBus>());
// Get a program logger: // Get a program logger:
var programLogger = app.Services.GetRequiredService<ILogger<Program>>(); var programLogger = app.Services.GetRequiredService<ILogger<Program>>();

View File

@ -15,10 +15,18 @@ public sealed class MessageBus
private readonly ConcurrentQueue<Message> messageQueue = new(); private readonly ConcurrentQueue<Message> messageQueue = new();
private readonly SemaphoreSlim sendingSemaphore = new(1, 1); private readonly SemaphoreSlim sendingSemaphore = new(1, 1);
private static ILogger<MessageBus>? LOG;
private MessageBus() private MessageBus()
{ {
} }
public void Initialize(ILogger<MessageBus> logger)
{
LOG = logger;
LOG.LogInformation("Message bus initialized.");
}
/// <summary> /// <summary>
/// Define for which components and events you want to receive messages. /// Define for which components and events you want to receive messages.
/// </summary> /// </summary>
@ -61,11 +69,16 @@ public sealed class MessageBus
var eventFilter = this.componentEvents[receiver]; var eventFilter = this.componentEvents[receiver];
if (eventFilter.Length == 0 || eventFilter.Contains(triggeredEvent)) if (eventFilter.Length == 0 || eventFilter.Contains(triggeredEvent))
// We don't await the task here because we don't want to block the message bus: // We don't await the task here because we don't want to block the message bus:
_ = receiver.ProcessMessage(message.SendingComponent, message.TriggeredEvent, message.Data); _ = receiver.ProcessMessage(message.SendingComponent, message.TriggeredEvent, message.Data);
} }
} }
} }
catch (Exception e)
{
LOG?.LogError(e, "Error while sending message.");
}
finally finally
{ {
this.sendingSemaphore.Release(); this.sendingSemaphore.Release();