From 6726f7b3499a6a6cc7b7fcbf1db4a71a5d428ab8 Mon Sep 17 00:00:00 2001 From: MrSmoke <709976+MrSmoke@users.noreply.github.com> Date: Mon, 11 Nov 2024 09:51:03 +1100 Subject: [PATCH] Add LogScope to QueueHostedService to add the message id --- src/Hosting/Queue/src/MessageContextScope.cs | 28 ++++++++++++++++++++ src/Hosting/Queue/src/QueueHostedService.cs | 2 ++ 2 files changed, 30 insertions(+) create mode 100644 src/Hosting/Queue/src/MessageContextScope.cs diff --git a/src/Hosting/Queue/src/MessageContextScope.cs b/src/Hosting/Queue/src/MessageContextScope.cs new file mode 100644 index 0000000..509c59b --- /dev/null +++ b/src/Hosting/Queue/src/MessageContextScope.cs @@ -0,0 +1,28 @@ +namespace ClickView.GoodStuff.Hosting.Queue; + +using System.Collections; +using Queues.RabbitMq; + +internal class MessageContextScope(MessageContext context) : IReadOnlyList> +{ + public IEnumerator> GetEnumerator() + { + for (var i = 0; i < Count; ++i) + { + yield return this[i]; + } + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + public int Count => 1; + + public KeyValuePair this[int index] => index switch + { + 0 => new KeyValuePair("MessageId", context.Id), + _ => throw new IndexOutOfRangeException(nameof(index)), + }; +} diff --git a/src/Hosting/Queue/src/QueueHostedService.cs b/src/Hosting/Queue/src/QueueHostedService.cs index 809c6be..4b1162a 100644 --- a/src/Hosting/Queue/src/QueueHostedService.cs +++ b/src/Hosting/Queue/src/QueueHostedService.cs @@ -47,6 +47,8 @@ protected override Task SubscribeAsync(IQueueClient queueCl /// private async Task OnMessageAsync(MessageContext messageContext, CancellationToken cancellationToken) { + using var logScope = Logger.BeginScope(new MessageContextScope(messageContext)); + Logger.QueueMessageReceived(messageContext.Id, messageContext.Timestamp); try