From d7415fd7483df49f14c9989a81fb4758af9565cd Mon Sep 17 00:00:00 2001 From: Andreas Bednarz Date: Mon, 16 Jun 2025 13:46:07 +1000 Subject: [PATCH 1/5] Convert SC primary instance loggers to ILogger --- .../StartupModeTests.cs | 3 +- .../When_a_retry_fails_to_be_sent.cs | 3 +- .../ServiceControlComponentRunner.cs | 3 +- .../MonitoringDataStoreTests.cs | 19 ++--- .../ReturnToSenderDequeuerTests.cs | 11 +-- .../RetryStateTests.cs | 66 +++++++++++----- .../API/APIApprovals.cs | 14 ++-- .../EndpointInstanceMonitoringTests.cs | 3 +- .../CorruptedReplyToHeaderStrategyTests.cs | 9 ++- .../Recoverability/RetryOperationTests.cs | 23 +++--- .../MessageView_ScatterGatherTest.cs | 8 +- .../GetAuditCountsForEndpointApi.cs | 8 +- .../Messages/GetAllMessagesApi.cs | 5 +- .../Messages/GetAllMessagesForEndpointApi.cs | 5 +- .../Messages/GetMessagesController.cs | 11 ++- .../Messages/MessagesByConversationApi.cs | 6 +- .../Messages/ScatterGatherApi.cs | 20 ++--- .../Messages/ScatterGatherApiMessageView.cs | 5 +- .../Messages/ScatterGatherRemoteOnly.cs | 5 +- .../CompositeViews/Messages/SearchApi.cs | 5 +- .../Messages/SearchEndpointApi.cs | 5 +- ...RemotePlatformConnectionDetailsProvider.cs | 8 +- .../CustomCheckResultProcessor.cs | 10 +-- .../FailedErrorImportCustomCheck.cs | 10 +-- .../InternalCustomCheckManager.cs | 16 ++-- .../InternalCustomChecks.cs | 4 +- .../InternalCustomChecksHostedService.cs | 6 +- .../EventDispatcherHostedService.cs | 24 +++--- .../IntegrationEventWriter.cs | 17 ++--- .../RepeatedFailuresOverTimeCircuitBreaker.cs | 39 +++++++--- .../HostApplicationBuilderExtensions.cs | 6 +- .../Commands/ImportFailedErrorsCommand.cs | 8 +- .../Hosting/Commands/SetupCommand.cs | 8 +- .../Metrics/MetricsReporterHostedService.cs | 14 ++-- .../Infrastructure/Settings/Settings.cs | 34 ++++----- .../SignalR/MessageStreamerHub.cs | 14 ++-- src/ServiceControl/Licensing/ActiveLicense.cs | 8 +- .../Licensing/LicenseCheckHostedService.cs | 8 +- .../Api/EditFailedMessagesController.cs | 15 ++-- .../Api/RetryMessagesController.cs | 13 ++-- .../Monitoring/EndpointInstanceMonitor.cs | 9 ++- .../Monitoring/EndpointInstanceMonitoring.cs | 15 ++-- .../HeartbeatMonitoringHostedService.cs | 15 ++-- .../Monitoring/Web/GetKnownEndpointsApi.cs | 7 +- .../Api/NotificationsController.cs | 4 +- .../Email/CustomChecksMailNotification.cs | 12 +-- .../Notifications/Email/EmailSender.cs | 9 +-- .../Email/SendEmailNotificationHandler.cs | 20 ++--- .../Operations/ErrorIngestion.cs | 40 +++++----- .../Operations/ErrorIngestionFaultPolicy.cs | 9 ++- .../Operations/ErrorIngestor.cs | 44 ++++------- .../Operations/ErrorProcessor.cs | 28 +++---- src/ServiceControl/Program.cs | 10 ++- .../Archiving/ArchiveAllInGroupHandler.cs | 10 +-- .../Archiving/UnArchiveAllInGroupHandler.cs | 10 +-- .../Recoverability/Editing/EditHandler.cs | 15 ++-- .../Recoverability/RecoverabilityComponent.cs | 24 +++--- .../CorruptedReplyToHeaderStrategy.cs | 10 +-- .../Handlers/RetryAllInGroupHandler.cs | 11 +-- .../Recoverability/Retrying/InMemoryRetry.cs | 13 +++- .../Retrying/Infrastructure/ReturnToSender.cs | 36 ++++----- .../Infrastructure/ReturnToSenderDequeuer.cs | 76 +++++++------------ .../Recoverability/Retrying/RetriesGateway.cs | 25 +++--- .../Retrying/RetryDocumentManager.cs | 16 ++-- .../Recoverability/Retrying/RetryProcessor.cs | 74 ++++++++---------- .../Retrying/RetryingManager.cs | 7 +- .../SagaAudit/GetSagaByIdApi.cs | 5 +- .../SagaAudit/SagaUpdatedHandler.cs | 14 ++-- 68 files changed, 549 insertions(+), 518 deletions(-) diff --git a/src/ServiceControl.AcceptanceTests.RavenDB/StartupModeTests.cs b/src/ServiceControl.AcceptanceTests.RavenDB/StartupModeTests.cs index 6aef55b25e..3e568ebc46 100644 --- a/src/ServiceControl.AcceptanceTests.RavenDB/StartupModeTests.cs +++ b/src/ServiceControl.AcceptanceTests.RavenDB/StartupModeTests.cs @@ -5,6 +5,7 @@ using System.Threading.Tasks; using Hosting.Commands; using Microsoft.Extensions.Hosting; + using Microsoft.Extensions.Logging.Abstractions; using NServiceBus; using NUnit.Framework; using Particular.ServiceControl.Hosting; @@ -57,7 +58,7 @@ public async Task CanRunMaintenanceMode() public async Task CanRunImportFailedMessagesMode() => await new TestableImportFailedErrorsCommand().Execute(new HostArguments(Array.Empty()), settings); - class TestableImportFailedErrorsCommand : ImportFailedErrorsCommand + class TestableImportFailedErrorsCommand() : ImportFailedErrorsCommand(NullLogger.Instance) { protected override EndpointConfiguration CreateEndpointConfiguration(Settings settings) { diff --git a/src/ServiceControl.AcceptanceTests/Recoverability/MessageFailures/When_a_retry_fails_to_be_sent.cs b/src/ServiceControl.AcceptanceTests/Recoverability/MessageFailures/When_a_retry_fails_to_be_sent.cs index ff843ecd2c..3e4e4e89cd 100644 --- a/src/ServiceControl.AcceptanceTests/Recoverability/MessageFailures/When_a_retry_fails_to_be_sent.cs +++ b/src/ServiceControl.AcceptanceTests/Recoverability/MessageFailures/When_a_retry_fails_to_be_sent.cs @@ -8,6 +8,7 @@ using AcceptanceTesting.EndpointTemplates; using Infrastructure; using Microsoft.Extensions.DependencyInjection; + using Microsoft.Extensions.Logging.Abstractions; using NServiceBus; using NServiceBus.AcceptanceTesting; using NServiceBus.Routing; @@ -146,7 +147,7 @@ public class MyContext : ScenarioContext public class MessageThatWillFail : ICommand; public class FakeReturnToSender(IErrorMessageDataStore errorMessageStore, MyContext myContext) - : ReturnToSender(errorMessageStore) + : ReturnToSender(errorMessageStore, NullLogger.Instance) { public override Task HandleMessage(MessageContext message, IMessageDispatcher sender, string errorQueueTransportAddress, CancellationToken cancellationToken = default) { diff --git a/src/ServiceControl.AcceptanceTests/TestSupport/ServiceControlComponentRunner.cs b/src/ServiceControl.AcceptanceTests/TestSupport/ServiceControlComponentRunner.cs index 19bbe6b57a..2a722ecb61 100644 --- a/src/ServiceControl.AcceptanceTests/TestSupport/ServiceControlComponentRunner.cs +++ b/src/ServiceControl.AcceptanceTests/TestSupport/ServiceControlComponentRunner.cs @@ -15,6 +15,7 @@ using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; + using Microsoft.Extensions.Logging.Abstractions; using NLog; using NServiceBus; using NServiceBus.AcceptanceTesting; @@ -102,7 +103,7 @@ async Task InitializeServiceControl(ScenarioContext context) using (new DiagnosticTimer($"Creating infrastructure for {instanceName}")) { - var setupCommand = new SetupCommand(); + var setupCommand = new SetupCommand(NullLogger.Instance); await setupCommand.Execute(new HostArguments([]), settings); } diff --git a/src/ServiceControl.Persistence.Tests/MonitoringDataStoreTests.cs b/src/ServiceControl.Persistence.Tests/MonitoringDataStoreTests.cs index 68b58fe2c0..693832546e 100644 --- a/src/ServiceControl.Persistence.Tests/MonitoringDataStoreTests.cs +++ b/src/ServiceControl.Persistence.Tests/MonitoringDataStoreTests.cs @@ -3,6 +3,7 @@ using System; using System.Linq; using System.Threading.Tasks; + using Microsoft.Extensions.Logging.Abstractions; using NUnit.Framework; using ServiceControl.Monitoring; using ServiceControl.Operations; @@ -13,7 +14,7 @@ class MonitoringDataStoreTests : PersistenceTestBase [Test] public async Task Endpoints_load_from_dataStore_into_monitor() { - var endpointInstanceMonitoring = new EndpointInstanceMonitoring(new FakeDomainEvents()); + var endpointInstanceMonitoring = new EndpointInstanceMonitoring(new FakeDomainEvents(), NullLogger.Instance); var endpoint1 = new EndpointDetails() { HostId = Guid.NewGuid(), Host = "Host1", Name = "Name1" }; await MonitoringDataStore.CreateIfNotExists(endpoint1); @@ -26,7 +27,7 @@ public async Task Endpoints_load_from_dataStore_into_monitor() [Test] public async Task Endpoints_added_more_than_once_are_treated_as_same_endpoint() { - var endpointInstanceMonitoring = new EndpointInstanceMonitoring(new FakeDomainEvents()); + var endpointInstanceMonitoring = new EndpointInstanceMonitoring(new FakeDomainEvents(), NullLogger.Instance); var endpoint1 = new EndpointDetails() { HostId = Guid.NewGuid(), Host = "Host1", Name = "Name1" }; await MonitoringDataStore.CreateIfNotExists(endpoint1); await MonitoringDataStore.CreateIfNotExists(endpoint1); @@ -40,7 +41,7 @@ public async Task Endpoints_added_more_than_once_are_treated_as_same_endpoint() [Test] public async Task Updating_existing_endpoint_does_not_create_new_ones() { - var endpointInstanceMonitoring = new EndpointInstanceMonitoring(new FakeDomainEvents()); + var endpointInstanceMonitoring = new EndpointInstanceMonitoring(new FakeDomainEvents(), NullLogger.Instance); var endpoint1 = new EndpointDetails() { HostId = Guid.NewGuid(), Host = "Host1", Name = "Name1" }; await MonitoringDataStore.CreateIfNotExists(endpoint1); await MonitoringDataStore.CreateOrUpdate(endpoint1, endpointInstanceMonitoring); @@ -54,7 +55,7 @@ public async Task Updating_existing_endpoint_does_not_create_new_ones() [Test] public async Task Endpoint_is_created_if_doesnt_exist() { - var endpointInstanceMonitoring = new EndpointInstanceMonitoring(new FakeDomainEvents()); + var endpointInstanceMonitoring = new EndpointInstanceMonitoring(new FakeDomainEvents(), NullLogger.Instance); var endpoint1 = new EndpointDetails() { HostId = Guid.NewGuid(), Host = "Host1", Name = "Name1" }; var endpoint2 = new EndpointDetails() { HostId = Guid.NewGuid(), Host = "Host2", Name = "Name2" }; await MonitoringDataStore.CreateIfNotExists(endpoint1); @@ -69,7 +70,7 @@ public async Task Endpoint_is_created_if_doesnt_exist() [Test] public async Task Endpoint_is_created_if_doesnt_exist_on_update() { - var endpointInstanceMonitoring = new EndpointInstanceMonitoring(new FakeDomainEvents()); + var endpointInstanceMonitoring = new EndpointInstanceMonitoring(new FakeDomainEvents(), NullLogger.Instance); var endpoint1 = new EndpointDetails() { HostId = Guid.NewGuid(), Host = "Host1", Name = "Name1" }; var endpoint2 = new EndpointDetails() { HostId = Guid.NewGuid(), Host = "Host2", Name = "Name2" }; await MonitoringDataStore.CreateIfNotExists(endpoint1); @@ -84,7 +85,7 @@ public async Task Endpoint_is_created_if_doesnt_exist_on_update() [Test] public async Task Endpoint_is_updated() { - var endpointInstanceMonitoring = new EndpointInstanceMonitoring(new FakeDomainEvents()); + var endpointInstanceMonitoring = new EndpointInstanceMonitoring(new FakeDomainEvents(), NullLogger.Instance); var endpoint1 = new EndpointDetails() { HostId = Guid.NewGuid(), Host = "Host1", Name = "Name1" }; await MonitoringDataStore.CreateIfNotExists(endpoint1); @@ -93,7 +94,7 @@ public async Task Endpoint_is_updated() Assert.That(endpointInstanceMonitoring.IsMonitored(endpointInstanceMonitoring.GetEndpoints()[0].Id), Is.False); await MonitoringDataStore.UpdateEndpointMonitoring(endpoint1, true); - endpointInstanceMonitoring = new EndpointInstanceMonitoring(new FakeDomainEvents()); + endpointInstanceMonitoring = new EndpointInstanceMonitoring(new FakeDomainEvents(), NullLogger.Instance); CompleteDatabaseOperation(); await MonitoringDataStore.WarmupMonitoringFromPersistence(endpointInstanceMonitoring); @@ -104,7 +105,7 @@ public async Task Endpoint_is_updated() [Test] public async Task Endpoint_is_deleted() { - var endpointInstanceMonitoring = new EndpointInstanceMonitoring(new FakeDomainEvents()); + var endpointInstanceMonitoring = new EndpointInstanceMonitoring(new FakeDomainEvents(), NullLogger.Instance); var endpoint1 = new EndpointDetails() { HostId = Guid.NewGuid(), Host = "Host1", Name = "Name1" }; await MonitoringDataStore.CreateIfNotExists(endpoint1); @@ -114,7 +115,7 @@ public async Task Endpoint_is_deleted() await MonitoringDataStore.Delete(endpointInstanceMonitoring.GetEndpoints()[0].Id); - endpointInstanceMonitoring = new EndpointInstanceMonitoring(new FakeDomainEvents()); + endpointInstanceMonitoring = new EndpointInstanceMonitoring(new FakeDomainEvents(), NullLogger.Instance); CompleteDatabaseOperation(); await MonitoringDataStore.WarmupMonitoringFromPersistence(endpointInstanceMonitoring); diff --git a/src/ServiceControl.Persistence.Tests/Recoverability/ReturnToSenderDequeuerTests.cs b/src/ServiceControl.Persistence.Tests/Recoverability/ReturnToSenderDequeuerTests.cs index 6df26ed702..cecd9c9ddc 100644 --- a/src/ServiceControl.Persistence.Tests/Recoverability/ReturnToSenderDequeuerTests.cs +++ b/src/ServiceControl.Persistence.Tests/Recoverability/ReturnToSenderDequeuerTests.cs @@ -10,6 +10,7 @@ using MessageFailures; using MessageFailures.Api; using Microsoft.Extensions.DependencyInjection; + using Microsoft.Extensions.Logging.Abstractions; using NServiceBus.Extensibility; using NServiceBus.Transport; using NUnit.Framework; @@ -47,7 +48,7 @@ public async Task It_removes_staging_id_header() }; var message = CreateMessage(Guid.NewGuid().ToString(), headers); - await new ReturnToSender(null).HandleMessage(message, sender, "error"); + await new ReturnToSender(null, NullLogger.Instance).HandleMessage(message, sender, "error"); Assert.That(sender.Message.Headers.ContainsKey("ServiceControl.Retry.StagingId"), Is.False); } @@ -66,7 +67,7 @@ public async Task It_fetches_the_body_from_storage_if_provided() }; var message = CreateMessage(Guid.NewGuid().ToString(), headers); - await new ReturnToSender(new FakeErrorMessageDataStore()).HandleMessage(message, sender, "error"); + await new ReturnToSender(new FakeErrorMessageDataStore(), NullLogger.Instance).HandleMessage(message, sender, "error"); Assert.That(Encoding.UTF8.GetString(sender.Message.Body.ToArray()), Is.EqualTo("MessageBodyId")); } @@ -84,7 +85,7 @@ public async Task It_uses_retry_to_if_provided() }; var message = CreateMessage(Guid.NewGuid().ToString(), headers); - await new ReturnToSender(null).HandleMessage(message, sender, "error"); + await new ReturnToSender(null, NullLogger.Instance).HandleMessage(message, sender, "error"); Assert.Multiple(() => { @@ -105,7 +106,7 @@ public async Task It_sends_directly_to_target_if_retry_to_is_not_provided() }; var message = CreateMessage(Guid.NewGuid().ToString(), headers); - await new ReturnToSender(null).HandleMessage(message, sender, "error"); + await new ReturnToSender(null, NullLogger.Instance).HandleMessage(message, sender, "error"); Assert.Multiple(() => { @@ -129,7 +130,7 @@ public async Task It_restores_body_id_and_target_addres_after_failure() try { - await new ReturnToSender(null).HandleMessage(message, sender, "error"); + await new ReturnToSender(null, NullLogger.Instance).HandleMessage(message, sender, "error"); } catch (Exception) { diff --git a/src/ServiceControl.Persistence.Tests/RetryStateTests.cs b/src/ServiceControl.Persistence.Tests/RetryStateTests.cs index 3c9f426086..c0c730cf68 100644 --- a/src/ServiceControl.Persistence.Tests/RetryStateTests.cs +++ b/src/ServiceControl.Persistence.Tests/RetryStateTests.cs @@ -7,6 +7,7 @@ using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; + using Microsoft.Extensions.Logging.Abstractions; using NServiceBus.Transport; using NUnit.Framework; using ServiceBus.Management.Infrastructure.Settings; @@ -17,6 +18,7 @@ using ServiceControl.Persistence; using ServiceControl.Recoverability; using ServiceControl.Transports; + using static ServiceControl.Recoverability.RecoverabilityComponent; using QueueAddress = NServiceBus.Transport.QueueAddress; [NonParallelizable] @@ -26,7 +28,7 @@ class RetryStateTests : PersistenceTestBase public async Task When_a_group_is_processed_it_is_set_to_the_Preparing_state() { var domainEvents = new FakeDomainEvents(); - var retryManager = new RetryingManager(domainEvents); + var retryManager = new RetryingManager(domainEvents, NullLogger.Instance); await CreateAFailedMessageAndMarkAsPartOfRetryBatch(retryManager, "Test-group", true, 1); var status = retryManager.GetStatusForRetryOperation("Test-group", RetryType.FailureGroup); @@ -38,13 +40,13 @@ public async Task When_a_group_is_processed_it_is_set_to_the_Preparing_state() public async Task When_a_group_is_prepared_and_SC_is_started_the_group_is_marked_as_failed() { var domainEvents = new FakeDomainEvents(); - var retryManager = new RetryingManager(domainEvents); + var retryManager = new RetryingManager(domainEvents, NullLogger.Instance); await CreateAFailedMessageAndMarkAsPartOfRetryBatch(retryManager, "Test-group", false, 1); var documentManager = new CustomRetryDocumentManager(false, RetryStore, retryManager); - var orphanage = new RecoverabilityComponent.AdoptOrphanBatchesFromPreviousSessionHostedService(documentManager, new AsyncTimer()); + var orphanage = new AdoptOrphanBatchesFromPreviousSessionHostedService(documentManager, new AsyncTimer(), NullLogger.Instance); await orphanage.AdoptOrphanedBatchesAsync(); CompleteDatabaseOperation(); @@ -67,7 +69,7 @@ public async Task When_the_dequeuer_is_created_then_the_error_address_is_cached( var transportCustomization = new TestTransportCustomization { TransportInfrastructure = transportInfrastructure }; - var testReturnToSenderDequeuer = new TestReturnToSenderDequeuer(new ReturnToSender(ErrorStore), ErrorStore, domainEvents, "TestEndpoint", + var testReturnToSenderDequeuer = new TestReturnToSenderDequeuer(new ReturnToSender(ErrorStore, NullLogger.Instance), ErrorStore, domainEvents, "TestEndpoint", errorQueueNameCache, transportCustomization); await testReturnToSenderDequeuer.StartAsync(new CancellationToken()); @@ -79,12 +81,24 @@ public async Task When_the_dequeuer_is_created_then_the_error_address_is_cached( public async Task When_a_group_is_prepared_with_three_batches_and_SC_is_restarted_while_the_first_group_is_being_forwarded_then_the_count_still_matches() { var domainEvents = new FakeDomainEvents(); - var retryManager = new RetryingManager(domainEvents); + var retryManager = new RetryingManager(domainEvents, NullLogger.Instance); await CreateAFailedMessageAndMarkAsPartOfRetryBatch(retryManager, "Test-group", true, 2001); var sender = new TestSender(); - var processor = new RetryProcessor(RetryBatchesStore, domainEvents, new TestReturnToSenderDequeuer(new ReturnToSender(ErrorStore), ErrorStore, domainEvents, "TestEndpoint", new ErrorQueueNameCache(), new TestTransportCustomization()), retryManager, new Lazy(() => sender)); + var processor = new RetryProcessor( + RetryBatchesStore, + domainEvents, + new TestReturnToSenderDequeuer( + new ReturnToSender(ErrorStore, NullLogger.Instance), + ErrorStore, + domainEvents, + "TestEndpoint", + new ErrorQueueNameCache(), + new TestTransportCustomization()), + retryManager, + new Lazy(() => sender), + NullLogger.Instance); // Needs index RetryBatches_ByStatus_ReduceInitialBatchSize CompleteDatabaseOperation(); @@ -92,13 +106,25 @@ public async Task When_a_group_is_prepared_with_three_batches_and_SC_is_restarte await processor.ProcessBatches(); // mark ready // Simulate SC restart - retryManager = new RetryingManager(domainEvents); + retryManager = new RetryingManager(domainEvents, NullLogger.Instance); var documentManager = new CustomRetryDocumentManager(false, RetryStore, retryManager); await documentManager.RebuildRetryOperationState(); - processor = new RetryProcessor(RetryBatchesStore, domainEvents, new TestReturnToSenderDequeuer(new ReturnToSender(ErrorStore), ErrorStore, domainEvents, "TestEndpoint", new ErrorQueueNameCache(), new TestTransportCustomization()), retryManager, new Lazy(() => sender)); + processor = new RetryProcessor( + RetryBatchesStore, + domainEvents, + new TestReturnToSenderDequeuer( + new ReturnToSender(ErrorStore, NullLogger.Instance), + ErrorStore, + domainEvents, + "TestEndpoint", + new ErrorQueueNameCache(), + new TestTransportCustomization()), + retryManager, + new Lazy(() => sender), + NullLogger.Instance); await processor.ProcessBatches(); @@ -110,14 +136,14 @@ public async Task When_a_group_is_prepared_with_three_batches_and_SC_is_restarte public async Task When_a_group_is_forwarded_the_status_is_Completed() { var domainEvents = new FakeDomainEvents(); - var retryManager = new RetryingManager(domainEvents); + var retryManager = new RetryingManager(domainEvents, NullLogger.Instance); await CreateAFailedMessageAndMarkAsPartOfRetryBatch(retryManager, "Test-group", true, 1); var sender = new TestSender(); - var returnToSender = new TestReturnToSenderDequeuer(new ReturnToSender(ErrorStore), ErrorStore, domainEvents, "TestEndpoint", new ErrorQueueNameCache(), new TestTransportCustomization()); - var processor = new RetryProcessor(RetryBatchesStore, domainEvents, returnToSender, retryManager, new Lazy(() => sender)); + var returnToSender = new TestReturnToSenderDequeuer(new ReturnToSender(ErrorStore, NullLogger.Instance), ErrorStore, domainEvents, "TestEndpoint", new ErrorQueueNameCache(), new TestTransportCustomization()); + var processor = new RetryProcessor(RetryBatchesStore, domainEvents, returnToSender, retryManager, new Lazy(() => sender), NullLogger.Instance); await processor.ProcessBatches(); // mark ready await processor.ProcessBatches(); @@ -130,7 +156,7 @@ public async Task When_a_group_is_forwarded_the_status_is_Completed() public async Task When_there_is_one_poison_message_it_is_removed_from_batch_and_the_status_is_Complete() { var domainEvents = new FakeDomainEvents(); - var retryManager = new RetryingManager(domainEvents); + var retryManager = new RetryingManager(domainEvents, NullLogger.Instance); await CreateAFailedMessageAndMarkAsPartOfRetryBatch(retryManager, "Test-group", true, "A", "B", "C"); @@ -146,8 +172,8 @@ public async Task When_there_is_one_poison_message_it_is_removed_from_batch_and_ } }; - var returnToSender = new TestReturnToSenderDequeuer(new ReturnToSender(ErrorStore), ErrorStore, domainEvents, "TestEndpoint", new ErrorQueueNameCache(), new TestTransportCustomization()); - var processor = new RetryProcessor(RetryBatchesStore, domainEvents, returnToSender, retryManager, new Lazy(() => sender)); + var returnToSender = new TestReturnToSenderDequeuer(new ReturnToSender(ErrorStore, NullLogger.Instance), ErrorStore, domainEvents, "TestEndpoint", new ErrorQueueNameCache(), new TestTransportCustomization()); + var processor = new RetryProcessor(RetryBatchesStore, domainEvents, returnToSender, retryManager, new Lazy(() => sender), NullLogger.Instance); bool c; do @@ -179,15 +205,15 @@ public async Task When_there_is_one_poison_message_it_is_removed_from_batch_and_ public async Task When_a_group_has_one_batch_out_of_two_forwarded_the_status_is_Forwarding() { var domainEvents = new FakeDomainEvents(); - var retryManager = new RetryingManager(domainEvents); + var retryManager = new RetryingManager(domainEvents, NullLogger.Instance); await CreateAFailedMessageAndMarkAsPartOfRetryBatch(retryManager, "Test-group", true, 1001); - var returnToSender = new ReturnToSender(ErrorStore); + var returnToSender = new ReturnToSender(ErrorStore, NullLogger.Instance); var sender = new TestSender(); - var processor = new RetryProcessor(RetryBatchesStore, domainEvents, new TestReturnToSenderDequeuer(returnToSender, ErrorStore, domainEvents, "TestEndpoint", new ErrorQueueNameCache(), new TestTransportCustomization()), retryManager, new Lazy(() => sender)); + var processor = new RetryProcessor(RetryBatchesStore, domainEvents, new TestReturnToSenderDequeuer(returnToSender, ErrorStore, domainEvents, "TestEndpoint", new ErrorQueueNameCache(), new TestTransportCustomization()), retryManager, new Lazy(() => sender), NullLogger.Instance); CompleteDatabaseOperation(); @@ -253,7 +279,7 @@ async Task CreateAFailedMessageAndMarkAsPartOfRetryBatch(RetryingManager retryMa class CustomRetriesGateway : RetriesGateway { public CustomRetriesGateway(bool progressToStaged, IRetryDocumentDataStore store, RetryingManager retryManager) - : base(store, retryManager) + : base(store, retryManager, NullLogger.Instance) { this.progressToStaged = progressToStaged; } @@ -274,7 +300,7 @@ protected override Task MoveBatchToStaging(string batchDocumentId) class CustomRetryDocumentManager : RetryDocumentManager { public CustomRetryDocumentManager(bool progressToStaged, IRetryDocumentDataStore retryStore, RetryingManager retryManager) - : base(new FakeApplicationLifetime(), retryStore, retryManager) + : base(new FakeApplicationLifetime(), retryStore, retryManager, NullLogger.Instance) { RetrySessionId = Guid.NewGuid().ToString(); this.progressToStaged = progressToStaged; @@ -307,7 +333,7 @@ class TestReturnToSenderDequeuer : ReturnToSenderDequeuer { public TestReturnToSenderDequeuer(ReturnToSender returnToSender, IErrorMessageDataStore store, IDomainEvents domainEvents, string endpointName, ErrorQueueNameCache cache, ITransportCustomization transportCustomization) - : base(returnToSender, store, domainEvents, transportCustomization, null, new Settings { InstanceName = endpointName }, cache) + : base(returnToSender, store, domainEvents, transportCustomization, null, new Settings { InstanceName = endpointName }, cache, NullLogger.Instance) { } diff --git a/src/ServiceControl.UnitTests/API/APIApprovals.cs b/src/ServiceControl.UnitTests/API/APIApprovals.cs index d9d56c1361..1a75ce026f 100644 --- a/src/ServiceControl.UnitTests/API/APIApprovals.cs +++ b/src/ServiceControl.UnitTests/API/APIApprovals.cs @@ -12,6 +12,7 @@ using Microsoft.AspNetCore.Mvc.Controllers; using Microsoft.AspNetCore.Mvc.Routing; using Microsoft.AspNetCore.Routing; + using Microsoft.Extensions.Logging.Abstractions; using NServiceBus.CustomChecks; using NUnit.Framework; using Particular.Approvals; @@ -30,14 +31,13 @@ public async Task RootPathValue() var httpContext = new DefaultHttpContext { Request = { Scheme = "http", Host = new HostString("localhost") } }; var actionContext = new ActionContext { HttpContext = httpContext, RouteData = new RouteData(), ActionDescriptor = new ControllerActionDescriptor() }; var controllerContext = new ControllerContext(actionContext); + var configurationApi = new ConfigurationApi( + new ActiveLicense(null, NullLogger.Instance) { IsValid = true }, + new Settings(), + null, + new MassTransitConnectorHeartbeatStatus()); - var controller = new RootController(new ConfigurationApi( - new ActiveLicense(null) { IsValid = true }, - new Settings(), - null, - new MassTransitConnectorHeartbeatStatus() - ) - ) + var controller = new RootController(configurationApi) { ControllerContext = controllerContext, Url = new UrlHelper(actionContext) diff --git a/src/ServiceControl.UnitTests/Monitoring/EndpointInstanceMonitoringTests.cs b/src/ServiceControl.UnitTests/Monitoring/EndpointInstanceMonitoringTests.cs index a0662eafa3..9ab5eac338 100644 --- a/src/ServiceControl.UnitTests/Monitoring/EndpointInstanceMonitoringTests.cs +++ b/src/ServiceControl.UnitTests/Monitoring/EndpointInstanceMonitoringTests.cs @@ -3,6 +3,7 @@ using System; using System.Threading; using System.Threading.Tasks; + using Microsoft.Extensions.Logging.Abstractions; using NUnit.Framework; using ServiceControl.Infrastructure.DomainEvents; using ServiceControl.Monitoring; @@ -13,7 +14,7 @@ class EndpointInstanceMonitoringTests [Test] public async Task When_endpoint_removed_should_stay_removed() { - var monitor = new EndpointInstanceMonitoring(new FakeDomainEvents()); + var monitor = new EndpointInstanceMonitoring(new FakeDomainEvents(), NullLogger.Instance); var monitoredEndpoint = new EndpointInstanceId("MonitoredEndpoint", "HostName", Guid.NewGuid()); var lastHeartbeat = DateTime.UtcNow; diff --git a/src/ServiceControl.UnitTests/Recoverability/CorruptedReplyToHeaderStrategyTests.cs b/src/ServiceControl.UnitTests/Recoverability/CorruptedReplyToHeaderStrategyTests.cs index 452a088315..e377045922 100644 --- a/src/ServiceControl.UnitTests/Recoverability/CorruptedReplyToHeaderStrategyTests.cs +++ b/src/ServiceControl.UnitTests/Recoverability/CorruptedReplyToHeaderStrategyTests.cs @@ -1,6 +1,7 @@ namespace ServiceControl.UnitTests.Recoverability { using System.Collections.Generic; + using Microsoft.Extensions.Logging.Abstractions; using NServiceBus; using NUnit.Framework; using ServiceControl.Recoverability; @@ -12,7 +13,7 @@ class CorruptedReplyToHeaderStrategyTests public void Handle_corrupted_header() { // Arrange - var strategy = new CorruptedReplyToHeaderStrategy(ServiceControlMachineName); + var strategy = new CorruptedReplyToHeaderStrategy(ServiceControlMachineName, NullLogger.Instance); var corruptedReplyToAddress = $"SomeEndpoint@{ServiceControlMachineName}"; @@ -34,7 +35,7 @@ public void Handle_corrupted_header() public void Handle_non_corupted_header() { // Arrange - var strategy = new CorruptedReplyToHeaderStrategy(ServiceControlMachineName); + var strategy = new CorruptedReplyToHeaderStrategy(ServiceControlMachineName, NullLogger.Instance); var nonCorruptedReplyToAddress = $"SomeEndpoint@{SendingMachineName}"; @@ -56,7 +57,7 @@ public void Handle_non_corupted_header() public void Handle_no_OriginatingMachine() { // Arrange - var strategy = new CorruptedReplyToHeaderStrategy(ServiceControlMachineName); + var strategy = new CorruptedReplyToHeaderStrategy(ServiceControlMachineName, NullLogger.Instance); var maybeCorruptedReplyToAddress = $"SomeEndpoint@{ServiceControlMachineName}"; @@ -77,7 +78,7 @@ public void Handle_no_OriginatingMachine() public void Handle_no_machine_name_in_header() { // Arrange - var strategy = new CorruptedReplyToHeaderStrategy(ServiceControlMachineName); + var strategy = new CorruptedReplyToHeaderStrategy(ServiceControlMachineName, NullLogger.Instance); var replyToAddressWithNoMachineName = "SomeEndpoint"; diff --git a/src/ServiceControl.UnitTests/Recoverability/RetryOperationTests.cs b/src/ServiceControl.UnitTests/Recoverability/RetryOperationTests.cs index 04bb05beee..0945406a9d 100644 --- a/src/ServiceControl.UnitTests/Recoverability/RetryOperationTests.cs +++ b/src/ServiceControl.UnitTests/Recoverability/RetryOperationTests.cs @@ -2,6 +2,7 @@ { using System; using System.Threading.Tasks; + using Microsoft.Extensions.Logging.Abstractions; using NUnit.Framework; using ServiceControl.Persistence; using ServiceControl.Recoverability; @@ -12,7 +13,7 @@ public class RetryOperationTests [Test] public async Task Wait_should_set_wait_state() { - var summary = new InMemoryRetry("abc123", RetryType.FailureGroup, new FakeDomainEvents()); + var summary = new InMemoryRetry("abc123", RetryType.FailureGroup, new FakeDomainEvents(), NullLogger.Instance); await summary.Wait(DateTime.UtcNow, "FailureGroup1"); Assert.Multiple(() => { @@ -28,7 +29,7 @@ public async Task Wait_should_set_wait_state() [Test] public void Fail_should_set_failed() { - var summary = new InMemoryRetry("abc123", RetryType.FailureGroup, new FakeDomainEvents()); + var summary = new InMemoryRetry("abc123", RetryType.FailureGroup, new FakeDomainEvents(), NullLogger.Instance); summary.Fail(); Assert.That(summary.Failed, Is.True); } @@ -36,7 +37,7 @@ public void Fail_should_set_failed() [Test] public async Task Prepare_should_set_prepare_state() { - var summary = new InMemoryRetry("abc123", RetryType.FailureGroup, new FakeDomainEvents()); + var summary = new InMemoryRetry("abc123", RetryType.FailureGroup, new FakeDomainEvents(), NullLogger.Instance); await summary.Prepare(1000); Assert.Multiple(() => { @@ -49,7 +50,7 @@ public async Task Prepare_should_set_prepare_state() [Test] public async Task Prepared_batch_should_set_prepare_state() { - var summary = new InMemoryRetry("abc123", RetryType.FailureGroup, new FakeDomainEvents()); + var summary = new InMemoryRetry("abc123", RetryType.FailureGroup, new FakeDomainEvents(), NullLogger.Instance); await summary.Prepare(1000); await summary.PrepareBatch(1000); Assert.Multiple(() => @@ -63,7 +64,7 @@ public async Task Prepared_batch_should_set_prepare_state() [Test] public async Task Forwarding_should_set_forwarding_state() { - var summary = new InMemoryRetry("abc123", RetryType.FailureGroup, new FakeDomainEvents()); + var summary = new InMemoryRetry("abc123", RetryType.FailureGroup, new FakeDomainEvents(), NullLogger.Instance); await summary.Prepare(1000); await summary.PrepareBatch(1000); await summary.Forwarding(); @@ -79,7 +80,7 @@ public async Task Forwarding_should_set_forwarding_state() [Test] public async Task Batch_forwarded_should_set_forwarding_state() { - var summary = new InMemoryRetry("abc123", RetryType.FailureGroup, new FakeDomainEvents()); + var summary = new InMemoryRetry("abc123", RetryType.FailureGroup, new FakeDomainEvents(), NullLogger.Instance); await summary.Prepare(1000); await summary.PrepareBatch(1000); await summary.Forwarding(); @@ -97,7 +98,7 @@ public async Task Batch_forwarded_should_set_forwarding_state() public async Task Should_raise_domain_events() { var domainEvents = new FakeDomainEvents(); - var summary = new InMemoryRetry("abc123", RetryType.FailureGroup, domainEvents); + var summary = new InMemoryRetry("abc123", RetryType.FailureGroup, domainEvents, NullLogger.Instance); await summary.Prepare(1000); await summary.PrepareBatch(1000); await summary.Forwarding(); @@ -116,7 +117,7 @@ public async Task Should_raise_domain_events() [Test] public async Task Batch_forwarded_all_forwarded_should_set_completed_state() { - var summary = new InMemoryRetry("abc123", RetryType.FailureGroup, new FakeDomainEvents()); + var summary = new InMemoryRetry("abc123", RetryType.FailureGroup, new FakeDomainEvents(), NullLogger.Instance); await summary.Prepare(1000); await summary.PrepareBatch(1000); await summary.Forwarding(); @@ -133,7 +134,7 @@ public async Task Batch_forwarded_all_forwarded_should_set_completed_state() [Test] public async Task Skip_should_set_update_skipped_messages() { - var summary = new InMemoryRetry("abc123", RetryType.FailureGroup, new FakeDomainEvents()); + var summary = new InMemoryRetry("abc123", RetryType.FailureGroup, new FakeDomainEvents(), NullLogger.Instance); await summary.Wait(DateTime.UtcNow); await summary.Prepare(2000); await summary.PrepareBatch(1000); @@ -149,7 +150,7 @@ public async Task Skip_should_set_update_skipped_messages() [Test] public async Task Skip_should_complete_when_all_skipped() { - var summary = new InMemoryRetry("abc123", RetryType.FailureGroup, new FakeDomainEvents()); + var summary = new InMemoryRetry("abc123", RetryType.FailureGroup, new FakeDomainEvents(), NullLogger.Instance); await summary.Wait(DateTime.UtcNow); await summary.Prepare(1000); await summary.PrepareBatch(1000); @@ -165,7 +166,7 @@ public async Task Skip_should_complete_when_all_skipped() [Test] public async Task Skip_and_forward_combination_should_complete_when_done() { - var summary = new InMemoryRetry("abc123", RetryType.FailureGroup, new FakeDomainEvents()); + var summary = new InMemoryRetry("abc123", RetryType.FailureGroup, new FakeDomainEvents(), NullLogger.Instance); await summary.Wait(DateTime.UtcNow); await summary.Prepare(2000); await summary.PrepareBatch(1000); diff --git a/src/ServiceControl.UnitTests/ScatterGather/MessageView_ScatterGatherTest.cs b/src/ServiceControl.UnitTests/ScatterGather/MessageView_ScatterGatherTest.cs index d74e2cac8c..22eee8c632 100644 --- a/src/ServiceControl.UnitTests/ScatterGather/MessageView_ScatterGatherTest.cs +++ b/src/ServiceControl.UnitTests/ScatterGather/MessageView_ScatterGatherTest.cs @@ -6,6 +6,8 @@ using System.Net.Http; using System.Threading.Tasks; using CompositeViews.Messages; + using Microsoft.Extensions.Logging; + using Microsoft.Extensions.Logging.Abstractions; using NUnit.Framework; using Persistence.Infrastructure; using ServiceBus.Management.Infrastructure.Settings; @@ -15,7 +17,7 @@ abstract class MessageView_ScatterGatherTest [SetUp] public void SetUp() { - var api = new TestApi(null, null, null); + var api = new TestApi(null, null, null, NullLogger.Instance); Results = api.AggregateResults(new ScatterGatherApiMessageViewContext(new PagingInfo(), new SortInfo()), GetData()); } @@ -66,8 +68,8 @@ protected IEnumerable RemoteData() class TestApi : ScatterGatherApiMessageView { - public TestApi(object dataStore, Settings settings, IHttpClientFactory httpClientFactory) - : base(dataStore, settings, httpClientFactory) + public TestApi(object dataStore, Settings settings, IHttpClientFactory httpClientFactory, ILogger logger) + : base(dataStore, settings, httpClientFactory, logger) { } diff --git a/src/ServiceControl/CompositeViews/AuditCounts/GetAuditCountsForEndpointApi.cs b/src/ServiceControl/CompositeViews/AuditCounts/GetAuditCountsForEndpointApi.cs index 278804b90c..b260282a01 100644 --- a/src/ServiceControl/CompositeViews/AuditCounts/GetAuditCountsForEndpointApi.cs +++ b/src/ServiceControl/CompositeViews/AuditCounts/GetAuditCountsForEndpointApi.cs @@ -6,6 +6,7 @@ using System.Threading.Tasks; using Api.Contracts; using Messages; + using Microsoft.Extensions.Logging; using Persistence; using Persistence.Infrastructure; using ServiceBus.Management.Infrastructure.Settings; @@ -19,10 +20,9 @@ public record AuditCountsForEndpointContext(PagingInfo PagingInfo, string Endpoi public class GetAuditCountsForEndpointApi( IErrorMessageDataStore dataStore, Settings settings, - IHttpClientFactory httpClientFactory - ) - : ScatterGatherApi>(dataStore, settings, - httpClientFactory) + IHttpClientFactory httpClientFactory, + ILogger logger) + : ScatterGatherApi>(dataStore, settings, httpClientFactory, logger) { static readonly IList Empty = new List(0).AsReadOnly(); diff --git a/src/ServiceControl/CompositeViews/Messages/GetAllMessagesApi.cs b/src/ServiceControl/CompositeViews/Messages/GetAllMessagesApi.cs index 37d83ac49d..f3affe59e2 100644 --- a/src/ServiceControl/CompositeViews/Messages/GetAllMessagesApi.cs +++ b/src/ServiceControl/CompositeViews/Messages/GetAllMessagesApi.cs @@ -3,14 +3,15 @@ namespace ServiceControl.CompositeViews.Messages using System.Collections.Generic; using System.Net.Http; using System.Threading.Tasks; + using Microsoft.Extensions.Logging; using Persistence; using Persistence.Infrastructure; using ServiceBus.Management.Infrastructure.Settings; public class GetAllMessagesApi : ScatterGatherApiMessageView { - public GetAllMessagesApi(IErrorMessageDataStore dataStore, Settings settings, - IHttpClientFactory httpClientFactory) : base(dataStore, settings, httpClientFactory) + public GetAllMessagesApi(IErrorMessageDataStore dataStore, Settings settings, IHttpClientFactory httpClientFactory, ILogger logger) + : base(dataStore, settings, httpClientFactory, logger) { } diff --git a/src/ServiceControl/CompositeViews/Messages/GetAllMessagesForEndpointApi.cs b/src/ServiceControl/CompositeViews/Messages/GetAllMessagesForEndpointApi.cs index 1fdd327913..20870b9fbf 100644 --- a/src/ServiceControl/CompositeViews/Messages/GetAllMessagesForEndpointApi.cs +++ b/src/ServiceControl/CompositeViews/Messages/GetAllMessagesForEndpointApi.cs @@ -3,6 +3,7 @@ namespace ServiceControl.CompositeViews.Messages using System.Collections.Generic; using System.Net.Http; using System.Threading.Tasks; + using Microsoft.Extensions.Logging; using Persistence; using Persistence.Infrastructure; using ServiceBus.Management.Infrastructure.Settings; @@ -17,8 +18,8 @@ public record AllMessagesForEndpointContext( public class GetAllMessagesForEndpointApi : ScatterGatherApiMessageView { - public GetAllMessagesForEndpointApi(IErrorMessageDataStore dataStore, Settings settings, - IHttpClientFactory httpClientFactory) : base(dataStore, settings, httpClientFactory) + public GetAllMessagesForEndpointApi(IErrorMessageDataStore dataStore, Settings settings, IHttpClientFactory httpClientFactory, ILogger logger) + : base(dataStore, settings, httpClientFactory, logger) { } diff --git a/src/ServiceControl/CompositeViews/Messages/GetMessagesController.cs b/src/ServiceControl/CompositeViews/Messages/GetMessagesController.cs index 95c82bf5ac..f3f657ccd9 100644 --- a/src/ServiceControl/CompositeViews/Messages/GetMessagesController.cs +++ b/src/ServiceControl/CompositeViews/Messages/GetMessagesController.cs @@ -10,7 +10,7 @@ namespace ServiceControl.CompositeViews.Messages using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Extensions; using Microsoft.AspNetCore.Mvc; - using NServiceBus.Logging; + using Microsoft.Extensions.Logging; using Operations.BodyStorage; using Persistence.Infrastructure; using ServiceBus.Management.Infrastructure.Settings; @@ -29,7 +29,8 @@ public class GetMessagesController( GetAllMessagesForEndpointApi allMessagesForEndpointApi, GetAuditCountsForEndpointApi auditCountsForEndpointApi, SearchApi api, - SearchEndpointApi endpointApi) + SearchEndpointApi endpointApi, + ILogger logger) : ControllerBase { [Route("messages")] @@ -106,7 +107,9 @@ public async Task Get(string id, [FromQuery(Name = "instance_id") var forwarderError = await forwarder.SendAsync(HttpContext, remote.BaseAddress, httpMessageInvoker); if (forwarderError != ForwarderError.None && HttpContext.GetForwarderErrorFeature()?.Exception is { } exception) { - logger.Warn($"Failed to forward the request to remote instance at {remote.BaseAddress}{HttpContext.Request.GetEncodedPathAndQuery()}.", exception); + logger.LogWarning(exception, "Failed to forward the request to remote instance at {remoteBaseAddress}{httpPathAndQuery}", + remote.BaseAddress, + HttpContext.Request.GetEncodedPathAndQuery()); } return Empty; @@ -161,6 +164,6 @@ public async Task> SearchByKeyword([FromQuery] PagingInfo pa return result.Results; } - static ILog logger = LogManager.GetLogger(typeof(GetMessagesController)); + readonly ILogger logger = logger; } } \ No newline at end of file diff --git a/src/ServiceControl/CompositeViews/Messages/MessagesByConversationApi.cs b/src/ServiceControl/CompositeViews/Messages/MessagesByConversationApi.cs index 86fba81417..90837d3439 100644 --- a/src/ServiceControl/CompositeViews/Messages/MessagesByConversationApi.cs +++ b/src/ServiceControl/CompositeViews/Messages/MessagesByConversationApi.cs @@ -3,6 +3,7 @@ namespace ServiceControl.CompositeViews.Messages using System.Collections.Generic; using System.Net.Http; using System.Threading.Tasks; + using Microsoft.Extensions.Logging; using Persistence; using Persistence.Infrastructure; using ServiceBus.Management.Infrastructure.Settings; @@ -16,9 +17,8 @@ public record MessagesByConversationContext( public class MessagesByConversationApi : ScatterGatherApiMessageView { - public MessagesByConversationApi(IErrorMessageDataStore dataStore, Settings settings, - IHttpClientFactory httpClientFactory) : base(dataStore, settings, - httpClientFactory) + public MessagesByConversationApi(IErrorMessageDataStore dataStore, Settings settings, IHttpClientFactory httpClientFactory, ILogger logger) + : base(dataStore, settings, httpClientFactory, logger) { } diff --git a/src/ServiceControl/CompositeViews/Messages/ScatterGatherApi.cs b/src/ServiceControl/CompositeViews/Messages/ScatterGatherApi.cs index c55b777db7..cd388ce613 100644 --- a/src/ServiceControl/CompositeViews/Messages/ScatterGatherApi.cs +++ b/src/ServiceControl/CompositeViews/Messages/ScatterGatherApi.cs @@ -7,7 +7,7 @@ namespace ServiceControl.CompositeViews.Messages using System.Net.Http; using System.Threading.Tasks; using Infrastructure.WebApi; - using NServiceBus.Logging; + using Microsoft.Extensions.Logging; using Persistence.Infrastructure; using ServiceBus.Management.Infrastructure.Settings; using JsonSerializer = System.Text.Json.JsonSerializer; @@ -27,12 +27,12 @@ public abstract class ScatterGatherApi : ScatterGatherApi where TIn : ScatterGatherContext where TOut : class { - protected ScatterGatherApi(TDataStore store, Settings settings, IHttpClientFactory httpClientFactory) + protected ScatterGatherApi(TDataStore store, Settings settings, IHttpClientFactory httpClientFactory, ILogger logger) { DataStore = store; Settings = settings; HttpClientFactory = httpClientFactory; - logger = LogManager.GetLogger(GetType()); + this.logger = logger; } protected TDataStore DataStore { get; } @@ -120,19 +120,21 @@ async Task> FetchAndParse(HttpClient httpClient, string pathAn catch (HttpRequestException httpRequestException) { remoteInstanceSetting.TemporarilyUnavailable = true; - logger.Warn( - $"An HttpRequestException occurred when querying remote instance at {remoteInstanceSetting.BaseAddress}. The instance at uri: {remoteInstanceSetting.BaseAddress} will be temporarily disabled.", - httpRequestException); + logger.LogWarning( + httpRequestException, + "An HttpRequestException occurred when querying remote instance at {remoteInstanceSettingBaseAddress}. The instance at uri: {remoteInstanceSettingBaseAddress} will be temporarily disabled", + remoteInstanceSetting.BaseAddress, + remoteInstanceSetting.BaseAddress); return QueryResult.Empty(); } catch (OperationCanceledException) // Intentional, used to gracefully handle timeout { - logger.Warn($"Failed to query remote instance at {remoteInstanceSetting.BaseAddress} due to a timeout"); + logger.LogWarning("Failed to query remote instance at {remoteInstanceSettingBaseAddress} due to a timeout", remoteInstanceSetting.BaseAddress); return QueryResult.Empty(); } catch (Exception exception) { - logger.Warn($"Failed to query remote instance at {remoteInstanceSetting.BaseAddress}.", exception); + logger.LogWarning(exception, "Failed to query remote instance at {remoteInstanceSettingBaseAddress}", remoteInstanceSetting.BaseAddress); return QueryResult.Empty(); } } @@ -162,6 +164,6 @@ static async Task> ParseResult(HttpResponseMessage responseMes return new QueryResult(remoteResults, new QueryStatsInfo(etag, totalCount, isStale: false)); } - readonly ILog logger; + readonly ILogger logger; } } \ No newline at end of file diff --git a/src/ServiceControl/CompositeViews/Messages/ScatterGatherApiMessageView.cs b/src/ServiceControl/CompositeViews/Messages/ScatterGatherApiMessageView.cs index 542ba6daba..667338cb28 100644 --- a/src/ServiceControl/CompositeViews/Messages/ScatterGatherApiMessageView.cs +++ b/src/ServiceControl/CompositeViews/Messages/ScatterGatherApiMessageView.cs @@ -3,6 +3,7 @@ namespace ServiceControl.CompositeViews.Messages using System.Collections.Generic; using System.Linq; using System.Net.Http; + using Microsoft.Extensions.Logging; using Persistence.Infrastructure; using ServiceBus.Management.Infrastructure.Settings; @@ -17,8 +18,8 @@ public record ScatterGatherApiMessageViewContext(PagingInfo PagingInfo, SortInfo public abstract class ScatterGatherApiMessageView : ScatterGatherApi> where TInput : ScatterGatherApiMessageViewContext { - protected ScatterGatherApiMessageView(TDataStore dataStore, Settings settings, - IHttpClientFactory httpClientFactory) : base(dataStore, settings, httpClientFactory) + protected ScatterGatherApiMessageView(TDataStore dataStore, Settings settings, IHttpClientFactory httpClientFactory, ILogger logger) + : base(dataStore, settings, httpClientFactory, logger) { } diff --git a/src/ServiceControl/CompositeViews/Messages/ScatterGatherRemoteOnly.cs b/src/ServiceControl/CompositeViews/Messages/ScatterGatherRemoteOnly.cs index 600e44df2b..3394ceb49e 100644 --- a/src/ServiceControl/CompositeViews/Messages/ScatterGatherRemoteOnly.cs +++ b/src/ServiceControl/CompositeViews/Messages/ScatterGatherRemoteOnly.cs @@ -2,11 +2,12 @@ namespace ServiceControl.CompositeViews.Messages { using System.Net.Http; using System.Threading.Tasks; + using Microsoft.Extensions.Logging; using Persistence.Infrastructure; using ServiceBus.Management.Infrastructure.Settings; - public abstract class ScatterGatherRemoteOnly(Settings settings, IHttpClientFactory httpClientFactory) - : ScatterGatherApi(NoOpStore.Instance, settings, httpClientFactory) + public abstract class ScatterGatherRemoteOnly(Settings settings, IHttpClientFactory httpClientFactory, ILogger logger) + : ScatterGatherApi(NoOpStore.Instance, settings, httpClientFactory, logger) where TIn : ScatterGatherContext where TOut : class { diff --git a/src/ServiceControl/CompositeViews/Messages/SearchApi.cs b/src/ServiceControl/CompositeViews/Messages/SearchApi.cs index dd6ba8afb3..462879cfa5 100644 --- a/src/ServiceControl/CompositeViews/Messages/SearchApi.cs +++ b/src/ServiceControl/CompositeViews/Messages/SearchApi.cs @@ -3,6 +3,7 @@ namespace ServiceControl.CompositeViews.Messages using System.Collections.Generic; using System.Net.Http; using System.Threading.Tasks; + using Microsoft.Extensions.Logging; using Persistence; using Persistence.Infrastructure; using ServiceBus.Management.Infrastructure.Settings; @@ -16,8 +17,8 @@ public record SearchApiContext( public class SearchApi : ScatterGatherApiMessageView { - public SearchApi(IErrorMessageDataStore dataStore, Settings settings, IHttpClientFactory httpClientFactory) : - base(dataStore, settings, httpClientFactory) + public SearchApi(IErrorMessageDataStore dataStore, Settings settings, IHttpClientFactory httpClientFactory, ILogger logger) + : base(dataStore, settings, httpClientFactory, logger) { } diff --git a/src/ServiceControl/CompositeViews/Messages/SearchEndpointApi.cs b/src/ServiceControl/CompositeViews/Messages/SearchEndpointApi.cs index 990beae427..11444b8734 100644 --- a/src/ServiceControl/CompositeViews/Messages/SearchEndpointApi.cs +++ b/src/ServiceControl/CompositeViews/Messages/SearchEndpointApi.cs @@ -3,6 +3,7 @@ namespace ServiceControl.CompositeViews.Messages using System.Collections.Generic; using System.Net.Http; using System.Threading.Tasks; + using Microsoft.Extensions.Logging; using Persistence; using Persistence.Infrastructure; using ServiceBus.Management.Infrastructure.Settings; @@ -17,8 +18,8 @@ public record SearchEndpointContext( public class SearchEndpointApi : ScatterGatherApiMessageView { - public SearchEndpointApi(IErrorMessageDataStore dataStore, Settings settings, - IHttpClientFactory httpClientFactory) : base(dataStore, settings, httpClientFactory) + public SearchEndpointApi(IErrorMessageDataStore dataStore, Settings settings, IHttpClientFactory httpClientFactory, ILogger logger) + : base(dataStore, settings, httpClientFactory, logger) { } diff --git a/src/ServiceControl/Connection/RemotePlatformConnectionDetailsProvider.cs b/src/ServiceControl/Connection/RemotePlatformConnectionDetailsProvider.cs index f5235d6a0a..999a3cb2fe 100644 --- a/src/ServiceControl/Connection/RemotePlatformConnectionDetailsProvider.cs +++ b/src/ServiceControl/Connection/RemotePlatformConnectionDetailsProvider.cs @@ -5,10 +5,10 @@ using System.Net.Http; using System.Text.Json; using System.Threading.Tasks; - using NServiceBus.Logging; + using Microsoft.Extensions.Logging; using ServiceBus.Management.Infrastructure.Settings; - class RemotePlatformConnectionDetailsProvider(Settings settings, IHttpClientFactory clientFactory) + class RemotePlatformConnectionDetailsProvider(Settings settings, IHttpClientFactory clientFactory, ILogger logger) : IProvidePlatformConnectionDetails { public Task ProvideConnectionDetails(PlatformConnectionDetails connection) => @@ -36,10 +36,8 @@ async Task UpdateFromRemote(RemoteInstanceSetting remote, PlatformConnectionDeta connection.Errors.Add(message); - Log.Error(message, ex); + logger.LogError(ex, "Unable to get connection details from ServiceControl Audit instance at {remoteConnectionUri}", remoteConnectionUri); } } - - static readonly ILog Log = LogManager.GetLogger(); } } \ No newline at end of file diff --git a/src/ServiceControl/CustomChecks/CustomCheckResultProcessor.cs b/src/ServiceControl/CustomChecks/CustomCheckResultProcessor.cs index 7cff349e67..1e7a3d6727 100644 --- a/src/ServiceControl/CustomChecks/CustomCheckResultProcessor.cs +++ b/src/ServiceControl/CustomChecks/CustomCheckResultProcessor.cs @@ -4,15 +4,16 @@ namespace ServiceControl.CustomChecks using System.Threading.Tasks; using Contracts.CustomChecks; using Infrastructure.DomainEvents; - using NServiceBus.Logging; + using Microsoft.Extensions.Logging; using ServiceControl.Persistence; class CustomCheckResultProcessor { - public CustomCheckResultProcessor(IDomainEvents domainEvents, ICustomChecksDataStore store) + public CustomCheckResultProcessor(IDomainEvents domainEvents, ICustomChecksDataStore store, ILogger logger) { this.domainEvents = domainEvents; this.store = store; + this.logger = logger; } public async Task ProcessResult(CustomCheckDetail checkDetail) @@ -37,7 +38,7 @@ await domainEvents.Raise(new CustomChecksUpdated } catch (Exception ex) { - Logger.Warn("Failed to update periodic check status.", ex); + logger.LogWarning(ex, "Failed to update periodic check status"); } } @@ -75,9 +76,8 @@ await domainEvents.Raise(new CustomCheckSucceeded readonly IDomainEvents domainEvents; readonly ICustomChecksDataStore store; - int lastCount; - static ILog Logger = LogManager.GetLogger(); + readonly ILogger logger; } } \ No newline at end of file diff --git a/src/ServiceControl/CustomChecks/FailedErrorImportCustomCheck.cs b/src/ServiceControl/CustomChecks/FailedErrorImportCustomCheck.cs index 4e895d9089..e8000d18f4 100644 --- a/src/ServiceControl/CustomChecks/FailedErrorImportCustomCheck.cs +++ b/src/ServiceControl/CustomChecks/FailedErrorImportCustomCheck.cs @@ -3,16 +3,17 @@ using System; using System.Threading; using System.Threading.Tasks; + using Microsoft.Extensions.Logging; using NServiceBus.CustomChecks; - using NServiceBus.Logging; using Persistence; class FailedErrorImportCustomCheck : CustomCheck { - public FailedErrorImportCustomCheck(IFailedErrorImportDataStore store) + public FailedErrorImportCustomCheck(IFailedErrorImportDataStore store, ILogger logger) : base("Error Message Ingestion", "ServiceControl Health", TimeSpan.FromHours(1)) { this.store = store; + this.logger = logger; } public override async Task PerformCheck(CancellationToken cancellationToken = default) @@ -21,7 +22,7 @@ public override async Task PerformCheck(CancellationToken cancellat if (hasFailedImports) { - Logger.Warn(Message); + logger.LogWarning(Message); return CheckResult.Failed(Message); } @@ -29,10 +30,9 @@ public override async Task PerformCheck(CancellationToken cancellat } readonly IFailedErrorImportDataStore store; - const string Message = @"One or more error messages have failed to import properly into ServiceControl and have been stored in the ServiceControl database. The import of these messages could have failed for a number of reasons and ServiceControl is not able to automatically reimport them. For guidance on how to resolve this see https://docs.particular.net/servicecontrol/import-failed-messages"; - static readonly ILog Logger = LogManager.GetLogger(typeof(FailedErrorImportCustomCheck)); + readonly ILogger logger; } } \ No newline at end of file diff --git a/src/ServiceControl/CustomChecks/InternalCustomChecks/InternalCustomCheckManager.cs b/src/ServiceControl/CustomChecks/InternalCustomChecks/InternalCustomCheckManager.cs index e3443cd2e0..5b24076ea1 100644 --- a/src/ServiceControl/CustomChecks/InternalCustomChecks/InternalCustomCheckManager.cs +++ b/src/ServiceControl/CustomChecks/InternalCustomChecks/InternalCustomCheckManager.cs @@ -4,8 +4,8 @@ using System.Threading; using System.Threading.Tasks; using Infrastructure.BackgroundTasks; + using Microsoft.Extensions.Logging; using NServiceBus.CustomChecks; - using NServiceBus.Logging; using ServiceControl.Contracts.CustomChecks; using ServiceControl.Operations; @@ -15,12 +15,14 @@ public InternalCustomCheckManager( ICustomCheck check, EndpointDetails localEndpointDetails, IAsyncTimer scheduler, - CustomCheckResultProcessor checkResultProcessor) + CustomCheckResultProcessor checkResultProcessor, + ILogger logger) { this.check = check; this.localEndpointDetails = localEndpointDetails; this.scheduler = scheduler; this.checkResultProcessor = checkResultProcessor; + this.logger = logger; } public void Start() @@ -42,13 +44,14 @@ async Task Run(CancellationToken cancellationToken) } catch (OperationCanceledException e) when (cancellationToken.IsCancellationRequested) { - Logger.Info("Cancelled", e); + logger.LogInformation(e, "Cancelled"); } catch (Exception ex) { - var reason = $"`{check.GetType()}` implementation failed to run."; + var customCheckType = check.GetType(); + var reason = $"`{customCheckType}` implementation failed to run."; result = CheckResult.Failed(reason); - Logger.Error(reason, ex); + logger.LogError(ex, "`{customCheckType}` implementation failed to run", customCheckType); } var detail = new CustomCheckDetail @@ -74,7 +77,6 @@ async Task Run(CancellationToken cancellationToken) readonly EndpointDetails localEndpointDetails; readonly IAsyncTimer scheduler; readonly CustomCheckResultProcessor checkResultProcessor; - - static ILog Logger = LogManager.GetLogger(); + readonly ILogger logger; } } \ No newline at end of file diff --git a/src/ServiceControl/CustomChecks/InternalCustomChecks/InternalCustomChecks.cs b/src/ServiceControl/CustomChecks/InternalCustomChecks/InternalCustomChecks.cs index 1a02710541..cc840c6e76 100644 --- a/src/ServiceControl/CustomChecks/InternalCustomChecks/InternalCustomChecks.cs +++ b/src/ServiceControl/CustomChecks/InternalCustomChecks/InternalCustomChecks.cs @@ -4,6 +4,7 @@ using Infrastructure.BackgroundTasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; + using Microsoft.Extensions.Logging; using NServiceBus.CustomChecks; using NServiceBus.Hosting; using Operations; @@ -24,7 +25,8 @@ public static IHostApplicationBuilder AddInternalCustomChecks(this IHostApplicat provider.GetRequiredService(), provider.GetRequiredService(), provider.GetRequiredService(), - provider.GetRequiredService().InstanceName)); + provider.GetRequiredService().InstanceName, + provider.GetRequiredService>())); return hostBuilder; } } diff --git a/src/ServiceControl/CustomChecks/InternalCustomChecks/InternalCustomChecksHostedService.cs b/src/ServiceControl/CustomChecks/InternalCustomChecks/InternalCustomChecksHostedService.cs index e33b68e3a5..b75804e2d1 100644 --- a/src/ServiceControl/CustomChecks/InternalCustomChecks/InternalCustomChecksHostedService.cs +++ b/src/ServiceControl/CustomChecks/InternalCustomChecks/InternalCustomChecksHostedService.cs @@ -6,6 +6,7 @@ using System.Threading.Tasks; using Infrastructure.BackgroundTasks; using Microsoft.Extensions.Hosting; + using Microsoft.Extensions.Logging; using NServiceBus.CustomChecks; using NServiceBus.Hosting; using ServiceControl.Operations; @@ -15,14 +16,15 @@ class InternalCustomChecksHostedService( HostInformation hostInfo, IAsyncTimer scheduler, CustomCheckResultProcessor checkResultProcessor, - string endpointName) + string endpointName, + ILogger logger) : IHostedService { public Task StartAsync(CancellationToken cancellationToken) { foreach (var check in customChecks) { - var checkManager = new InternalCustomCheckManager(check, localEndpointDetails, scheduler, checkResultProcessor); + var checkManager = new InternalCustomCheckManager(check, localEndpointDetails, scheduler, checkResultProcessor, logger); checkManager.Start(); managers.Add(checkManager); diff --git a/src/ServiceControl/ExternalIntegrations/EventDispatcherHostedService.cs b/src/ServiceControl/ExternalIntegrations/EventDispatcherHostedService.cs index 10678284f7..ad6b91141c 100644 --- a/src/ServiceControl/ExternalIntegrations/EventDispatcherHostedService.cs +++ b/src/ServiceControl/ExternalIntegrations/EventDispatcherHostedService.cs @@ -6,8 +6,8 @@ using System.Threading.Tasks; using Infrastructure.DomainEvents; using Microsoft.Extensions.Hosting; + using Microsoft.Extensions.Logging; using NServiceBus; - using NServiceBus.Logging; using Persistence; class EventDispatcherHostedService : IHostedService @@ -16,13 +16,14 @@ public EventDispatcherHostedService( IExternalIntegrationRequestsDataStore store, IDomainEvents domainEvents, IEnumerable eventPublishers, - IMessageSession messageSession - ) + IMessageSession messageSession, + ILogger logger) { this.store = store; this.eventPublishers = eventPublishers; this.domainEvents = domainEvents; this.messageSession = messageSession; + this.logger = logger; } public Task StartAsync(CancellationToken cancellationToken) @@ -43,10 +44,7 @@ async Task TryDispatchEventBatch(object[] allContexts) foreach (var eventToBePublished in eventsToBePublished) { - if (Logger.IsDebugEnabled) - { - Logger.Debug("Publishing external event on the bus."); - } + logger.LogDebug("Publishing external event on the bus."); try { @@ -54,7 +52,7 @@ async Task TryDispatchEventBatch(object[] allContexts) } catch (Exception e) { - Logger.Error("Failed dispatching external integration event.", e); + logger.LogError(e, "Failed dispatching external integration event."); var m = new ExternalIntegrationEventFailedToBePublished { @@ -79,11 +77,11 @@ public Task StopAsync(CancellationToken cancellationToken) return store.StopAsync(cancellationToken); } - IMessageSession messageSession; - IEnumerable eventPublishers; - IExternalIntegrationRequestsDataStore store; - IDomainEvents domainEvents; + readonly IMessageSession messageSession; + readonly IEnumerable eventPublishers; + readonly IExternalIntegrationRequestsDataStore store; + readonly IDomainEvents domainEvents; - static ILog Logger = LogManager.GetLogger(typeof(EventDispatcherHostedService)); + readonly ILogger logger; } } \ No newline at end of file diff --git a/src/ServiceControl/ExternalIntegrations/IntegrationEventWriter.cs b/src/ServiceControl/ExternalIntegrations/IntegrationEventWriter.cs index e4af301c7c..26881dd36f 100644 --- a/src/ServiceControl/ExternalIntegrations/IntegrationEventWriter.cs +++ b/src/ServiceControl/ExternalIntegrations/IntegrationEventWriter.cs @@ -5,15 +5,19 @@ using System.Threading; using System.Threading.Tasks; using Infrastructure.DomainEvents; - using NServiceBus.Logging; + using Microsoft.Extensions.Logging; using ServiceControl.Persistence; class IntegrationEventWriter : IDomainHandler { - public IntegrationEventWriter(IExternalIntegrationRequestsDataStore store, IEnumerable eventPublishers) + public IntegrationEventWriter( + IExternalIntegrationRequestsDataStore store, + IEnumerable eventPublishers, + ILogger logger) { this.store = store; this.eventPublishers = eventPublishers; + this.logger = logger; } public async Task Handle(IDomainEvent message, CancellationToken cancellationToken) @@ -28,23 +32,18 @@ public async Task Handle(IDomainEvent message, CancellationToken cancellationTok return; } - if (Logger.IsDebugEnabled) - { - Logger.Debug("Storing dispatch requests"); - } + logger.LogDebug("Storing dispatch requests"); var dispatchRequests = dispatchContexts.Select(dispatchContext => new ExternalIntegrationDispatchRequest { DispatchContext = dispatchContext }).ToList(); - await store.StoreDispatchRequest(dispatchRequests); } readonly IExternalIntegrationRequestsDataStore store; readonly IEnumerable eventPublishers; - - static readonly ILog Logger = LogManager.GetLogger(typeof(IntegrationEventWriter)); + readonly ILogger logger; } } \ No newline at end of file diff --git a/src/ServiceControl/ExternalIntegrations/RepeatedFailuresOverTimeCircuitBreaker.cs b/src/ServiceControl/ExternalIntegrations/RepeatedFailuresOverTimeCircuitBreaker.cs index ad14c5c97e..44ee562de3 100644 --- a/src/ServiceControl/ExternalIntegrations/RepeatedFailuresOverTimeCircuitBreaker.cs +++ b/src/ServiceControl/ExternalIntegrations/RepeatedFailuresOverTimeCircuitBreaker.cs @@ -3,16 +3,22 @@ namespace NServiceBus using System; using System.Threading; using System.Threading.Tasks; - using Logging; + using Microsoft.Extensions.Logging; class RepeatedFailuresOverTimeCircuitBreaker : IDisposable { - public RepeatedFailuresOverTimeCircuitBreaker(string name, TimeSpan timeToWaitBeforeTriggering, Action triggerAction, TimeSpan delayAfterFailure) + public RepeatedFailuresOverTimeCircuitBreaker( + string name, + TimeSpan timeToWaitBeforeTriggering, + Action triggerAction, + TimeSpan delayAfterFailure, + ILogger logger) { - this.delayAfterFailure = delayAfterFailure; this.name = name; - this.triggerAction = triggerAction; this.timeToWaitBeforeTriggering = timeToWaitBeforeTriggering; + this.triggerAction = triggerAction; + this.delayAfterFailure = delayAfterFailure; + this.logger = logger; timer = new Timer(CircuitBreakerTriggered); } @@ -32,8 +38,14 @@ public void Success() return; } - timer.Change(System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite); - Logger.InfoFormat("The circuit breaker for {0} is now disarmed", name); + if (timer.Change(Timeout.Infinite, Timeout.Infinite)) + { + logger.LogInformation("The circuit breaker for {circuitBreakerName} is now disarmed", name); + } + else + { + logger.LogError("Attempted to disarm circuit breaker for {circuitBreakerName} but failed", name); + } } public Task Failure(Exception exception) @@ -43,8 +55,14 @@ public Task Failure(Exception exception) if (newValue == 1) { - timer.Change(timeToWaitBeforeTriggering, NoPeriodicTriggering); - Logger.WarnFormat("The circuit breaker for {0} is now in the armed state", name); + if (timer.Change(timeToWaitBeforeTriggering, NoPeriodicTriggering)) + { + logger.LogWarning("The circuit breaker for {circuitBreakerName} is now in the armed state", name); + } + else + { + logger.LogError("Attempted to arm circuit breaker for {circuitBreakerName} but failed", name); + } } return Task.Delay(delayAfterFailure); @@ -54,13 +72,12 @@ void CircuitBreakerTriggered(object state) { if (Interlocked.Read(ref failureCount) > 0) { - Logger.WarnFormat("The circuit breaker for {0} will now be triggered", name); + logger.LogWarning("The circuit breaker for {circuitBreakerName} will now be triggered", name); triggerAction(lastException); } } readonly TimeSpan delayAfterFailure; - long failureCount; Exception lastException; @@ -70,6 +87,6 @@ void CircuitBreakerTriggered(object state) readonly Action triggerAction; static readonly TimeSpan NoPeriodicTriggering = TimeSpan.FromMilliseconds(-1); - static readonly ILog Logger = LogManager.GetLogger(); + readonly ILogger logger; } } \ No newline at end of file diff --git a/src/ServiceControl/HostApplicationBuilderExtensions.cs b/src/ServiceControl/HostApplicationBuilderExtensions.cs index 50d0733fb9..39d550f3e6 100644 --- a/src/ServiceControl/HostApplicationBuilderExtensions.cs +++ b/src/ServiceControl/HostApplicationBuilderExtensions.cs @@ -6,6 +6,7 @@ namespace Particular.ServiceControl using global::ServiceControl.CustomChecks; using global::ServiceControl.ExternalIntegrations; using global::ServiceControl.Hosting; + using global::ServiceControl.Infrastructure; using global::ServiceControl.Infrastructure.BackgroundTasks; using global::ServiceControl.Infrastructure.DomainEvents; using global::ServiceControl.Infrastructure.Metrics; @@ -23,7 +24,6 @@ namespace Particular.ServiceControl using NLog.Extensions.Logging; using NServiceBus; using NServiceBus.Configuration.AdvancedExtensibility; - using NServiceBus.Logging; using NServiceBus.Transport; using ServiceBus.Management.Infrastructure; using ServiceBus.Management.Infrastructure.Installers; @@ -127,8 +127,8 @@ Audit Retention Period (optional): {settings.AuditRetentionPeriod} Selected Transport Customization: {settings.TransportType} -------------------------------------------------------------"; - var logger = LogManager.GetLogger(typeof(HostApplicationBuilderExtensions)); - logger.Info(startupMessage); + var logger = LoggerUtil.CreateStaticLogger(typeof(HostApplicationBuilderExtensions), settings.LoggingSettings.ToHostLogLevel()); + logger.LogInformation(startupMessage); endpointConfiguration.GetSettings().AddStartupDiagnosticsSection("Startup", new { Settings = settings, diff --git a/src/ServiceControl/Hosting/Commands/ImportFailedErrorsCommand.cs b/src/ServiceControl/Hosting/Commands/ImportFailedErrorsCommand.cs index e9b89213e0..55923b0111 100644 --- a/src/ServiceControl/Hosting/Commands/ImportFailedErrorsCommand.cs +++ b/src/ServiceControl/Hosting/Commands/ImportFailedErrorsCommand.cs @@ -6,17 +6,15 @@ using Infrastructure.WebApi; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; + using Microsoft.Extensions.Logging; using NServiceBus; - using NServiceBus.Logging; using Operations; using Particular.ServiceControl; using Particular.ServiceControl.Hosting; using ServiceBus.Management.Infrastructure.Settings; - class ImportFailedErrorsCommand : AbstractCommand + class ImportFailedErrorsCommand(ILogger logger) : AbstractCommand { - readonly ILog Log = LogManager.GetLogger(); - public override async Task Execute(HostArguments args, Settings settings) { settings.IngestErrorMessages = false; @@ -43,7 +41,7 @@ public override async Task Execute(HostArguments args, Settings settings) } catch (OperationCanceledException e) when (tokenSource.IsCancellationRequested) { - Log.Info("Cancelled", e); + logger.LogInformation(e, "Cancelled"); } finally { diff --git a/src/ServiceControl/Hosting/Commands/SetupCommand.cs b/src/ServiceControl/Hosting/Commands/SetupCommand.cs index 41ef355fd4..eec1a515e8 100644 --- a/src/ServiceControl/Hosting/Commands/SetupCommand.cs +++ b/src/ServiceControl/Hosting/Commands/SetupCommand.cs @@ -3,14 +3,14 @@ using System.Runtime.InteropServices; using System.Threading.Tasks; using Microsoft.Extensions.Hosting; - using NServiceBus.Logging; + using Microsoft.Extensions.Logging; using Particular.ServiceControl; using Particular.ServiceControl.Hosting; using ServiceBus.Management.Infrastructure.Installers; using ServiceBus.Management.Infrastructure.Settings; using Transports; - class SetupCommand : AbstractCommand + class SetupCommand(ILogger logger) : AbstractCommand { public override async Task Execute(HostArguments args, Settings settings) { @@ -35,7 +35,7 @@ public override async Task Execute(HostArguments args, Settings settings) if (args.SkipQueueCreation) { - Logger.Info("Skipping queue creation"); + logger.LogInformation("Skipping queue creation"); } else { @@ -48,7 +48,5 @@ public override async Task Execute(HostArguments args, Settings settings) await host.StopAsync(); } - - static readonly ILog Logger = LogManager.GetLogger(); } } \ No newline at end of file diff --git a/src/ServiceControl/Infrastructure/Metrics/MetricsReporterHostedService.cs b/src/ServiceControl/Infrastructure/Metrics/MetricsReporterHostedService.cs index bf886d712f..5992b7c0fe 100644 --- a/src/ServiceControl/Infrastructure/Metrics/MetricsReporterHostedService.cs +++ b/src/ServiceControl/Infrastructure/Metrics/MetricsReporterHostedService.cs @@ -4,20 +4,24 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Hosting; - using NServiceBus.Logging; + using Microsoft.Extensions.Logging; class MetricsReporterHostedService : IHostedService { readonly Metrics metrics; + readonly ILogger logger; + MetricsReporter reporter; - public MetricsReporterHostedService(Metrics metrics) => this.metrics = metrics; + public MetricsReporterHostedService(Metrics metrics, ILogger logger) + { + this.metrics = metrics; + this.logger = logger; + } public Task StartAsync(CancellationToken cancellationToken) { - var metricsLog = LogManager.GetLogger("Metrics"); - - reporter = new MetricsReporter(metrics, x => metricsLog.Info(x), TimeSpan.FromSeconds(5)); + reporter = new MetricsReporter(metrics, x => logger.LogInformation(x), TimeSpan.FromSeconds(5)); reporter.Start(); diff --git a/src/ServiceControl/Infrastructure/Settings/Settings.cs b/src/ServiceControl/Infrastructure/Settings/Settings.cs index cf6dbeffe7..35a2433323 100644 --- a/src/ServiceControl/Infrastructure/Settings/Settings.cs +++ b/src/ServiceControl/Infrastructure/Settings/Settings.cs @@ -6,8 +6,8 @@ namespace ServiceBus.Management.Infrastructure.Settings using System.Linq; using System.Runtime.Loader; using System.Text.Json.Serialization; + using Microsoft.Extensions.Logging; using NLog.Common; - using NServiceBus.Logging; using NServiceBus.Transport; using ServiceControl.Configuration; using ServiceControl.Infrastructure; @@ -145,7 +145,7 @@ public TimeSpan HeartbeatGracePeriod } catch (Exception ex) { - logger.Error($"HeartbeatGracePeriod settings invalid - {ex}. Defaulting HeartbeatGracePeriod to '00:00:40'"); + logger.LogError(ex, "HeartbeatGracePeriod settings invalid. Defaulting HeartbeatGracePeriod to '00:00:40'"); return TimeSpan.FromSeconds(40); } } @@ -234,15 +234,15 @@ TimeSpan GetEventRetentionPeriod() string message; if (ValidateConfiguration && result < TimeSpan.FromHours(1)) { - message = "EventRetentionPeriod settings is invalid, value should be minimum 1 hour."; - logger.Fatal(message); + message = "EventRetentionPeriod settings is invalid, value should be minimum 1 hour"; + logger.LogCritical(message); throw new Exception(message); } if (ValidateConfiguration && result > TimeSpan.FromDays(200)) { - message = "EventRetentionPeriod settings is invalid, value should be maximum 200 days."; - logger.Fatal(message); + message = "EventRetentionPeriod settings is invalid, value should be maximum 200 days"; + logger.LogCritical(message); throw new Exception(message); } @@ -259,8 +259,8 @@ TimeSpan GetErrorRetentionPeriod() var valueRead = SettingsReader.Read(SettingsRootNamespace, "ErrorRetentionPeriod"); if (valueRead == null) { - message = "ErrorRetentionPeriod settings is missing, please make sure it is included."; - logger.Fatal(message); + message = "ErrorRetentionPeriod settings is missing, please make sure it is included"; + logger.LogCritical(message); throw new Exception(message); } @@ -268,22 +268,22 @@ TimeSpan GetErrorRetentionPeriod() { if (ValidateConfiguration && result < TimeSpan.FromDays(5)) { - message = "ErrorRetentionPeriod settings is invalid, value should be minimum 5 days."; - logger.Fatal(message); + message = "ErrorRetentionPeriod settings is invalid, value should be minimum 5 days"; + logger.LogCritical(message); throw new Exception(message); } if (ValidateConfiguration && result > TimeSpan.FromDays(45)) { - message = "ErrorRetentionPeriod settings is invalid, value should be maximum 45 days."; - logger.Fatal(message); + message = "ErrorRetentionPeriod settings is invalid, value should be maximum 45 days"; + logger.LogCritical(message); throw new Exception(message); } } else { - message = "ErrorRetentionPeriod settings is invalid, please make sure it is a TimeSpan."; - logger.Fatal(message); + message = "ErrorRetentionPeriod settings is invalid, please make sure it is a TimeSpan"; + logger.LogCritical(message); throw new Exception(message); } @@ -402,20 +402,20 @@ void LoadErrorIngestionSettings() if (!IngestErrorMessages) { - logger.Info("Error ingestion disabled."); + logger.LogInformation("Error ingestion disabled."); } ErrorLogQueue = SettingsReader.Read(serviceBusRootNamespace, "ErrorLogQueue", null); if (ErrorLogQueue == null) { - logger.Info("No settings found for error log queue to import, default name will be used"); + logger.LogInformation("No settings found for error log queue to import, default name will be used"); ErrorLogQueue = Subscope(ErrorQueue); } } // logger is intentionally not static to prevent it from being initialized before LoggingConfigurator.ConfigureLogging has been called - readonly ILog logger = LogManager.GetLogger(typeof(Settings)); + readonly ILogger logger = LoggerUtil.CreateStaticLogger(); public const string DEFAULT_INSTANCE_NAME = "Particular.ServiceControl"; public static readonly SettingsRootNamespace SettingsRootNamespace = new("ServiceControl"); diff --git a/src/ServiceControl/Infrastructure/SignalR/MessageStreamerHub.cs b/src/ServiceControl/Infrastructure/SignalR/MessageStreamerHub.cs index 7f398e35dd..21aee94189 100644 --- a/src/ServiceControl/Infrastructure/SignalR/MessageStreamerHub.cs +++ b/src/ServiceControl/Infrastructure/SignalR/MessageStreamerHub.cs @@ -7,24 +7,28 @@ using System.Text.Json.Nodes; using System.Threading.Tasks; using Microsoft.AspNetCore.SignalR; + using Microsoft.Extensions.Logging; using NServiceBus; - using NServiceBus.Logging; using NServiceBus.Routing; using NServiceBus.Settings; using NServiceBus.Transport; class MessageStreamerHub : Hub { - public MessageStreamerHub(IMessageDispatcher sender, IReadOnlySettings settings, ReceiveAddresses receiveAddresses) + public MessageStreamerHub( + IMessageDispatcher sender, + IReadOnlySettings settings, + ReceiveAddresses receiveAddresses, + ILogger logger) { var conventions = settings.Get(); this.sender = sender; - messageTypes = settings.GetAvailableTypes() .Where(conventions.IsMessageType) .GroupBy(x => x.Name) .ToDictionary(x => x.Key, x => x.FirstOrDefault().AssemblyQualifiedName); localAddress = receiveAddresses.MainReceiveAddress; + this.logger = logger; } public async Task SendMessage(string data) @@ -47,7 +51,7 @@ public async Task SendMessage(string data) } catch (Exception ex) { - Log.Error($"Failed to process SignalR message. AuditMessage={data}", ex); + logger.LogError(ex, "Failed to process SignalR message. AuditMessage={auditMessage}", data); throw; } } @@ -56,6 +60,6 @@ public async Task SendMessage(string data) readonly IMessageDispatcher sender; string localAddress; - static readonly ILog Log = LogManager.GetLogger(typeof(MessageStreamerHub)); + readonly ILogger logger; } } \ No newline at end of file diff --git a/src/ServiceControl/Licensing/ActiveLicense.cs b/src/ServiceControl/Licensing/ActiveLicense.cs index d50a5bdb38..6dff02574f 100644 --- a/src/ServiceControl/Licensing/ActiveLicense.cs +++ b/src/ServiceControl/Licensing/ActiveLicense.cs @@ -5,9 +5,9 @@ using System.Threading.Tasks; using global::ServiceControl.LicenseManagement; using global::ServiceControl.Persistence; - using NServiceBus.Logging; + using Microsoft.Extensions.Logging; - public class ActiveLicense(ITrialLicenseDataProvider trialLicenseDataProvider) + public class ActiveLicense(ITrialLicenseDataProvider trialLicenseDataProvider, ILogger logger) { public bool IsValid { get; set; } public bool IsEvaluation { get; set; } @@ -16,7 +16,7 @@ public class ActiveLicense(ITrialLicenseDataProvider trialLicenseDataProvider) public async Task Refresh(CancellationToken cancellationToken) { - Logger.Debug("Refreshing ActiveLicense"); + logger.LogDebug("Refreshing ActiveLicense"); var detectedLicense = LicenseManager.FindLicense(); @@ -59,6 +59,6 @@ internal static async Task ValidateTrialLicense(LicenseDetails l } static readonly int MaxTrialPeriodInDays = 14; - static readonly ILog Logger = LogManager.GetLogger(typeof(ActiveLicense)); + readonly ILogger logger = logger; } } \ No newline at end of file diff --git a/src/ServiceControl/Licensing/LicenseCheckHostedService.cs b/src/ServiceControl/Licensing/LicenseCheckHostedService.cs index 3afcc3c2ba..52a7b41a5a 100644 --- a/src/ServiceControl/Licensing/LicenseCheckHostedService.cs +++ b/src/ServiceControl/Licensing/LicenseCheckHostedService.cs @@ -5,9 +5,9 @@ using System.Threading.Tasks; using global::ServiceControl.Infrastructure.BackgroundTasks; using Microsoft.Extensions.Hosting; - using NServiceBus.Logging; + using Microsoft.Extensions.Logging; - class LicenseCheckHostedService(ActiveLicense activeLicense, IAsyncTimer scheduler) : IHostedService + class LicenseCheckHostedService(ActiveLicense activeLicense, IAsyncTimer scheduler, ILogger logger) : IHostedService { public Task StartAsync(CancellationToken cancellationToken) { @@ -17,14 +17,12 @@ public Task StartAsync(CancellationToken cancellationToken) await activeLicense.Refresh(cancellationToken); return TimerJobExecutionResult.ScheduleNextExecution; - }, TimeSpan.FromTicks(0), due, ex => Logger.Error("Unhandled error while refreshing the license.", ex)); + }, TimeSpan.FromTicks(0), due, ex => logger.LogError(ex, "Unhandled error while refreshing the license")); return Task.CompletedTask; } public Task StopAsync(CancellationToken cancellationToken) => timer.Stop(cancellationToken); TimerJob timer; - - static readonly ILog Logger = LogManager.GetLogger(); } } \ No newline at end of file diff --git a/src/ServiceControl/MessageFailures/Api/EditFailedMessagesController.cs b/src/ServiceControl/MessageFailures/Api/EditFailedMessagesController.cs index f4c797390f..428be7f0ae 100644 --- a/src/ServiceControl/MessageFailures/Api/EditFailedMessagesController.cs +++ b/src/ServiceControl/MessageFailures/Api/EditFailedMessagesController.cs @@ -6,8 +6,8 @@ using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; + using Microsoft.Extensions.Logging; using NServiceBus; - using NServiceBus.Logging; using Persistence; using Recoverability; using ServiceBus.Management.Infrastructure.Settings; @@ -17,7 +17,8 @@ public class EditFailedMessagesController( Settings settings, IErrorMessageDataStore store, - IMessageSession session) + IMessageSession session, + ILogger logger) : ControllerBase { [Route("edit/config")] @@ -30,7 +31,7 @@ public async Task Edit(string failedMessageId, [FromBody] EditMes { if (!settings.AllowMessageEditing) { - Log.Info("Message edit-retry has not been enabled."); + logger.LogInformation("Message edit-retry has not been enabled"); return NotFound(); } @@ -38,7 +39,7 @@ public async Task Edit(string failedMessageId, [FromBody] EditMes if (failedMessage == null) { - Log.WarnFormat("The original failed message could not be loaded for id={0}", failedMessageId); + logger.LogWarning("The original failed message could not be loaded for id={failedMessageId}", failedMessageId); return BadRequest(); } @@ -54,13 +55,13 @@ public async Task Edit(string failedMessageId, [FromBody] EditMes if (LockedHeaderModificationValidator.Check(GetEditConfiguration().LockedHeaders, edit.MessageHeaders, failedMessage.ProcessingAttempts.Last().Headers)) { - Log.WarnFormat("Locked headers have been modified on the edit-retry for MessageID {0}.", failedMessageId); + logger.LogWarning("Locked headers have been modified on the edit-retry for MessageID {failedMessageId}", failedMessageId); return BadRequest(); } if (string.IsNullOrWhiteSpace(edit.MessageBody) || edit.MessageHeaders == null) { - Log.WarnFormat("There is no message body on the edit-retry for MessageID {0}.", failedMessageId); + logger.LogWarning("There is no message body on the edit-retry for MessageID {failedMessageId}", failedMessageId); return BadRequest(); } @@ -122,7 +123,7 @@ EditConfigurationModel GetEditConfiguration() => } }; - static readonly ILog Log = LogManager.GetLogger(typeof(EditFailedMessagesController)); + readonly ILogger logger = logger; } public class EditConfigurationModel diff --git a/src/ServiceControl/MessageFailures/Api/RetryMessagesController.cs b/src/ServiceControl/MessageFailures/Api/RetryMessagesController.cs index 3a55b27db2..8f98d422f9 100644 --- a/src/ServiceControl/MessageFailures/Api/RetryMessagesController.cs +++ b/src/ServiceControl/MessageFailures/Api/RetryMessagesController.cs @@ -8,15 +8,20 @@ using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Extensions; using Microsoft.AspNetCore.Mvc; + using Microsoft.Extensions.Logging; using NServiceBus; - using NServiceBus.Logging; using Recoverability; using ServiceBus.Management.Infrastructure.Settings; using Yarp.ReverseProxy.Forwarder; [ApiController] [Route("api")] - public class RetryMessagesController(Settings settings, HttpMessageInvoker httpMessageInvoker, IHttpForwarder forwarder, IMessageSession messageSession) : ControllerBase + public class RetryMessagesController( + Settings settings, + HttpMessageInvoker httpMessageInvoker, + IHttpForwarder forwarder, + IMessageSession messageSession, + ILogger logger) : ControllerBase { [Route("errors/{failedMessageId:required:minlength(1)}/retry")] [HttpPost] @@ -38,7 +43,7 @@ public async Task RetryMessageBy([FromQuery(Name = "instance_id") var forwarderError = await forwarder.SendAsync(HttpContext, remote.BaseAddress, httpMessageInvoker); if (forwarderError != ForwarderError.None && HttpContext.GetForwarderErrorFeature()?.Exception is { } exception) { - logger.Warn($"Failed to forward the request ot remote instance at {remote.BaseAddress + HttpContext.Request.GetEncodedPathAndQuery()}.", exception); + logger.LogWarning(exception, "Failed to forward the request ot remote instance at {remoteInstanceUrl}", remote.BaseAddress + HttpContext.Request.GetEncodedPathAndQuery()); } return Empty; @@ -88,7 +93,5 @@ public async Task RetryAllByEndpoint(string endpointName) return Accepted(); } - - static ILog logger = LogManager.GetLogger(typeof(RetryMessagesController)); } } \ No newline at end of file diff --git a/src/ServiceControl/Monitoring/EndpointInstanceMonitor.cs b/src/ServiceControl/Monitoring/EndpointInstanceMonitor.cs index 7a375746ed..c50bae3dc8 100644 --- a/src/ServiceControl/Monitoring/EndpointInstanceMonitor.cs +++ b/src/ServiceControl/Monitoring/EndpointInstanceMonitor.cs @@ -5,17 +5,18 @@ namespace ServiceControl.Monitoring using Contracts.HeartbeatMonitoring; using EndpointControl.Contracts; using Infrastructure.DomainEvents; - using NServiceBus.Logging; + using Microsoft.Extensions.Logging; using ServiceControl.Operations; using ServiceControl.Persistence; class EndpointInstanceMonitor { - public EndpointInstanceMonitor(EndpointInstanceId endpointInstanceId, bool monitored, IDomainEvents domainEvents) + public EndpointInstanceMonitor(EndpointInstanceId endpointInstanceId, bool monitored, IDomainEvents domainEvents, ILogger logger) { Id = endpointInstanceId; Monitored = monitored; this.domainEvents = domainEvents; + this.logger = logger; } public EndpointInstanceId Id { get; } @@ -39,7 +40,7 @@ public async Task UpdateStatus(HeartbeatStatus newStatus, DateTime? latestTimest if (newStatus != status) { await RaiseStateChangeEvents(newStatus, latestTimestamp); - Log.DebugFormat("Endpoint {0} status updated from {1} to {2}", Id.LogicalName, status, newStatus); + logger.LogDebug("Endpoint {logicalEndpointName} status updated from {oldHeartbeatStatus} to {newHeartbeatStatus}", Id.LogicalName, status, newStatus); } lastSeen = latestTimestamp; @@ -134,7 +135,7 @@ public KnownEndpointsView GetKnownView() }; } - static readonly ILog Log = LogManager.GetLogger(); + readonly ILogger logger; IDomainEvents domainEvents; DateTime? lastSeen; diff --git a/src/ServiceControl/Monitoring/EndpointInstanceMonitoring.cs b/src/ServiceControl/Monitoring/EndpointInstanceMonitoring.cs index 0829135c43..39319fc6d3 100644 --- a/src/ServiceControl/Monitoring/EndpointInstanceMonitoring.cs +++ b/src/ServiceControl/Monitoring/EndpointInstanceMonitoring.cs @@ -8,19 +8,22 @@ namespace ServiceControl.Monitoring using Contracts.EndpointControl; using Contracts.HeartbeatMonitoring; using Infrastructure.DomainEvents; + using Microsoft.Extensions.Logging; using Operations; using Persistence; class EndpointInstanceMonitoring : IEndpointInstanceMonitoring { readonly IDomainEvents domainEvents; + readonly ILogger monitorLogger; readonly ConcurrentDictionary endpoints = new(); readonly ConcurrentDictionary heartbeats = new(); EndpointMonitoringStats previousStats; - public EndpointInstanceMonitoring(IDomainEvents domainEvents) + public EndpointInstanceMonitoring(IDomainEvents domainEvents, ILogger monitorLogger) { this.domainEvents = domainEvents; + this.monitorLogger = monitorLogger; } public void RecordHeartbeat(EndpointInstanceId endpointInstanceId, DateTime timestamp) => heartbeats.GetOrAdd(endpointInstanceId, id => new HeartbeatMonitor()).MarkAlive(timestamp); @@ -32,7 +35,7 @@ public async Task CheckEndpoints(DateTime threshold) var recordedHeartbeat = entry.Value.MarkDeadIfOlderThan(threshold); var endpointInstanceId = entry.Key; - var monitor = endpoints.GetOrAdd(endpointInstanceId.UniqueId, id => new EndpointInstanceMonitor(endpointInstanceId, true, domainEvents)); + var monitor = endpoints.GetOrAdd(endpointInstanceId.UniqueId, id => new EndpointInstanceMonitor(endpointInstanceId, true, domainEvents, monitorLogger)); await monitor.UpdateStatus(recordedHeartbeat.Status, recordedHeartbeat.Timestamp); } @@ -45,13 +48,13 @@ public bool IsNewInstance(EndpointDetails newEndpointDetails) { var endpointInstanceId = newEndpointDetails.ToInstanceId(); - return endpoints.TryAdd(endpointInstanceId.UniqueId, new EndpointInstanceMonitor(endpointInstanceId, false, domainEvents)); + return endpoints.TryAdd(endpointInstanceId.UniqueId, new EndpointInstanceMonitor(endpointInstanceId, false, domainEvents, monitorLogger)); } public async Task EndpointDetected(EndpointDetails newEndpointDetails) { var endpointInstanceId = newEndpointDetails.ToInstanceId(); - if (endpoints.TryAdd(endpointInstanceId.UniqueId, new EndpointInstanceMonitor(endpointInstanceId, false, domainEvents))) + if (endpoints.TryAdd(endpointInstanceId.UniqueId, new EndpointInstanceMonitor(endpointInstanceId, false, domainEvents, monitorLogger))) { await domainEvents.Raise(new EndpointDetected { @@ -64,7 +67,7 @@ await domainEvents.Raise(new EndpointDetected public async Task DetectEndpointFromHeartbeatStartup(EndpointDetails newEndpointDetails, DateTime startedAt) { var endpointInstanceId = newEndpointDetails.ToInstanceId(); - endpoints.GetOrAdd(endpointInstanceId.UniqueId, id => new EndpointInstanceMonitor(endpointInstanceId, true, domainEvents)); + endpoints.GetOrAdd(endpointInstanceId.UniqueId, id => new EndpointInstanceMonitor(endpointInstanceId, true, domainEvents, monitorLogger)); await domainEvents.Raise(new EndpointStarted { @@ -76,7 +79,7 @@ await domainEvents.Raise(new EndpointStarted public void DetectEndpointFromPersistentStore(EndpointDetails endpointDetails, bool monitored) { var endpointInstanceId = new EndpointInstanceId(endpointDetails.Name, endpointDetails.Host, endpointDetails.HostId); - endpoints.GetOrAdd(endpointInstanceId.UniqueId, id => new EndpointInstanceMonitor(endpointInstanceId, monitored, domainEvents)); + endpoints.GetOrAdd(endpointInstanceId.UniqueId, id => new EndpointInstanceMonitor(endpointInstanceId, monitored, domainEvents, monitorLogger)); } async Task Update(EndpointMonitoringStats stats) diff --git a/src/ServiceControl/Monitoring/HeartbeatMonitoringHostedService.cs b/src/ServiceControl/Monitoring/HeartbeatMonitoringHostedService.cs index 1f9d6edaa5..a84dff5a81 100644 --- a/src/ServiceControl/Monitoring/HeartbeatMonitoringHostedService.cs +++ b/src/ServiceControl/Monitoring/HeartbeatMonitoringHostedService.cs @@ -5,23 +5,24 @@ using System.Threading.Tasks; using Infrastructure.BackgroundTasks; using Microsoft.Extensions.Hosting; - using NServiceBus.Logging; + using Microsoft.Extensions.Logging; using ServiceBus.Management.Infrastructure.Settings; using ServiceControl.Persistence; class HeartbeatMonitoringHostedService : IHostedService { - public HeartbeatMonitoringHostedService(IEndpointInstanceMonitoring monitor, IMonitoringDataStore persistence, IAsyncTimer scheduler, Settings settings) + public HeartbeatMonitoringHostedService(IEndpointInstanceMonitoring monitor, IMonitoringDataStore persistence, IAsyncTimer scheduler, Settings settings, ILogger logger) { this.monitor = monitor; this.persistence = persistence; this.scheduler = scheduler; + this.logger = logger; gracePeriod = settings.HeartbeatGracePeriod; } public async Task StartAsync(CancellationToken cancellationToken) { await persistence.WarmupMonitoringFromPersistence(monitor); - timer = scheduler.Schedule(_ => CheckEndpoints(), TimeSpan.Zero, TimeSpan.FromSeconds(5), e => { log.Error("Exception occurred when monitoring endpoint instances", e); }); + timer = scheduler.Schedule(_ => CheckEndpoints(), TimeSpan.Zero, TimeSpan.FromSeconds(5), e => logger.LogError(e, "Exception occurred when monitoring endpoint instances")); } public Task StopAsync(CancellationToken cancellationToken) => timer.Stop(cancellationToken); @@ -29,10 +30,8 @@ public async Task StartAsync(CancellationToken cancellationToken) async Task CheckEndpoints() { var inactivityThreshold = DateTime.UtcNow - gracePeriod; - if (log.IsDebugEnabled) - { - log.Debug($"Monitoring Endpoint Instances. Inactivity Threshold = {inactivityThreshold}"); - } + + logger.LogDebug("Monitoring Endpoint Instances. Inactivity Threshold = {inactivityThreshold}", inactivityThreshold); await monitor.CheckEndpoints(inactivityThreshold); return TimerJobExecutionResult.ScheduleNextExecution; @@ -44,6 +43,6 @@ async Task CheckEndpoints() TimerJob timer; TimeSpan gracePeriod; - static ILog log = LogManager.GetLogger(); + readonly ILogger logger; } } \ No newline at end of file diff --git a/src/ServiceControl/Monitoring/Web/GetKnownEndpointsApi.cs b/src/ServiceControl/Monitoring/Web/GetKnownEndpointsApi.cs index f54afa862e..1beea8d85f 100644 --- a/src/ServiceControl/Monitoring/Web/GetKnownEndpointsApi.cs +++ b/src/ServiceControl/Monitoring/Web/GetKnownEndpointsApi.cs @@ -5,6 +5,7 @@ using System.Net.Http; using System.Threading.Tasks; using CompositeViews.Messages; + using Microsoft.Extensions.Logging; using Persistence; using Persistence.Infrastructure; using ServiceBus.Management.Infrastructure.Settings; @@ -12,9 +13,9 @@ public class GetKnownEndpointsApi( IEndpointInstanceMonitoring store, Settings settings, - IHttpClientFactory httpClientFactory) - : ScatterGatherApi>(store, - settings, httpClientFactory) + IHttpClientFactory httpClientFactory, + ILogger logger) + : ScatterGatherApi>(store, settings, httpClientFactory, logger) { protected override Task>> LocalQuery(ScatterGatherContext input) { diff --git a/src/ServiceControl/Notifications/Api/NotificationsController.cs b/src/ServiceControl/Notifications/Api/NotificationsController.cs index f422e27a32..af5f90cfe0 100644 --- a/src/ServiceControl/Notifications/Api/NotificationsController.cs +++ b/src/ServiceControl/Notifications/Api/NotificationsController.cs @@ -10,7 +10,7 @@ [ApiController] [Route("api")] - public class NotificationsController(IErrorMessageDataStore store, Settings settings) : ControllerBase + public class NotificationsController(IErrorMessageDataStore store, Settings settings, EmailSender emailSender) : ControllerBase { [Route("notifications/email")] [HttpGet] @@ -69,7 +69,7 @@ public async Task SendTestEmail() try { - await EmailSender.Send( + await emailSender.Send( notificationsSettings.Email, $"[{settings.InstanceName}] health check notification check successful", $"[{settings.InstanceName}] health check notification check successful."); diff --git a/src/ServiceControl/Notifications/Email/CustomChecksMailNotification.cs b/src/ServiceControl/Notifications/Email/CustomChecksMailNotification.cs index 5368119fbb..bbdaff35db 100644 --- a/src/ServiceControl/Notifications/Email/CustomChecksMailNotification.cs +++ b/src/ServiceControl/Notifications/Email/CustomChecksMailNotification.cs @@ -6,8 +6,8 @@ using System.Threading.Tasks; using Contracts.CustomChecks; using Infrastructure.DomainEvents; + using Microsoft.Extensions.Logging; using NServiceBus; - using NServiceBus.Logging; using ServiceBus.Management.Infrastructure.Settings; class CustomChecksMailNotification : IDomainHandler, IDomainHandler @@ -29,11 +29,11 @@ class CustomChecksMailNotification : IDomainHandler, IDomainH "Error Message Ingestion" }; - public CustomChecksMailNotification(IMessageSession messageSession, Settings settings, EmailThrottlingState throttlingState) + public CustomChecksMailNotification(IMessageSession messageSession, Settings settings, EmailThrottlingState throttlingState, ILogger logger) { this.messageSession = messageSession; this.throttlingState = throttlingState; - + this.logger = logger; instanceName = settings.InstanceName; instanceAddress = settings.ApiUrl; @@ -49,7 +49,7 @@ public Task Handle(CustomCheckFailed domainEvent, CancellationToken cancellation { if (throttlingState.IsThrottling()) { - log.Warn("Email notification throttled"); + logger.LogWarning("Email notification throttled"); return Task.CompletedTask; } @@ -74,7 +74,7 @@ public Task Handle(CustomCheckSucceeded domainEvent, CancellationToken cancellat { if (throttlingState.IsThrottling()) { - log.Warn("Email notification throttled"); + logger.LogWarning("Email notification throttled"); return Task.CompletedTask; } @@ -93,6 +93,6 @@ public Task Handle(CustomCheckSucceeded domainEvent, CancellationToken cancellat bool IsHealthCheck(string checkId) => serviceControlHealthCustomCheckIds.Any(id => string.Equals(id, checkId, StringComparison.InvariantCultureIgnoreCase)); - static ILog log = LogManager.GetLogger(); + readonly ILogger logger; } } diff --git a/src/ServiceControl/Notifications/Email/EmailSender.cs b/src/ServiceControl/Notifications/Email/EmailSender.cs index 5201183b6e..257b3044bc 100644 --- a/src/ServiceControl/Notifications/Email/EmailSender.cs +++ b/src/ServiceControl/Notifications/Email/EmailSender.cs @@ -4,11 +4,11 @@ using System.Net; using System.Net.Mail; using System.Threading.Tasks; - using NServiceBus.Logging; + using Microsoft.Extensions.Logging; - class EmailSender + public class EmailSender(ILogger logger) { - public static async Task Send(EmailNotifications settings, string subject, string body, string emailDropFolder = null) + public async Task Send(EmailNotifications settings, string subject, string body, string emailDropFolder = null) { try { @@ -20,7 +20,7 @@ public static async Task Send(EmailNotifications settings, string subject, strin } catch (Exception e) { - log.Warn("Failure sending email.", e); + logger.LogWarning(e, "Failure sending email."); throw; } } @@ -50,7 +50,6 @@ static SmtpClient CreateSmtpClient(EmailNotifications settings, string emailDrop return smtpClient; } - static ILog log = LogManager.GetLogger(); static int defaultTimeout = (int)TimeSpan.FromSeconds(10).TotalMilliseconds; } } \ No newline at end of file diff --git a/src/ServiceControl/Notifications/Email/SendEmailNotificationHandler.cs b/src/ServiceControl/Notifications/Email/SendEmailNotificationHandler.cs index d7510fa68c..26f4ac0036 100644 --- a/src/ServiceControl/Notifications/Email/SendEmailNotificationHandler.cs +++ b/src/ServiceControl/Notifications/Email/SendEmailNotificationHandler.cs @@ -2,22 +2,24 @@ { using System; using System.Threading.Tasks; + using Microsoft.Extensions.Logging; using NServiceBus; - using NServiceBus.Logging; using NServiceBus.Transport; using Persistence; using ServiceBus.Management.Infrastructure.Settings; - public class SendEmailNotificationHandler : IHandleMessages + class SendEmailNotificationHandler : IHandleMessages { readonly IErrorMessageDataStore store; readonly EmailThrottlingState throttlingState; + readonly EmailSender emailSender; - public SendEmailNotificationHandler(IErrorMessageDataStore store, Settings settings, EmailThrottlingState throttlingState) + public SendEmailNotificationHandler(IErrorMessageDataStore store, Settings settings, EmailThrottlingState throttlingState, EmailSender emailSender, ILogger logger) { this.store = store; this.throttlingState = throttlingState; - + this.emailSender = emailSender; + this.logger = logger; emailDropFolder = settings.EmailDropFolder; } @@ -32,7 +34,7 @@ public async Task Handle(SendEmailNotification message, IMessageHandlerContext c if (notifications == null || !notifications.Email.Enabled) { - log.Info("Skipping email sending. Notifications turned-off."); + logger.LogInformation("Skipping email sending. Notifications turned-off"); return; } @@ -46,7 +48,7 @@ public async Task Handle(SendEmailNotification message, IMessageHandlerContext c { if (throttlingState.IsThrottling()) { - log.Warn("Email notification throttled"); + logger.LogWarning("Email notification throttled"); return; } @@ -59,7 +61,7 @@ public async Task Handle(SendEmailNotification message, IMessageHandlerContext c "\n\nWARNING: Your SMTP server was temporarily unavailable. Make sure to check ServicePulse for a full list of health check notifications."; } - await EmailSender.Send(notifications.Email, message.Subject, message.Body, emailDropFolder); + await emailSender.Send(notifications.Email, message.Subject, message.Body, emailDropFolder); } catch (Exception e) when (e is not OperationCanceledException) { @@ -77,7 +79,7 @@ public async Task Handle(SendEmailNotification message, IMessageHandlerContext c } else { - log.Warn("Success notification skipped due to throttling."); + logger.LogWarning("Success notification skipped due to throttling"); } } finally @@ -91,7 +93,7 @@ public async Task Handle(SendEmailNotification message, IMessageHandlerContext c string emailDropFolder; - static ILog log = LogManager.GetLogger(); + readonly ILogger logger; static TimeSpan spinDelay = TimeSpan.FromSeconds(1); static TimeSpan throttlingDelay = TimeSpan.FromSeconds(30); static TimeSpan cacheTimeout = TimeSpan.FromMinutes(5); diff --git a/src/ServiceControl/Operations/ErrorIngestion.cs b/src/ServiceControl/Operations/ErrorIngestion.cs index f4ee49693b..ec04de2e72 100644 --- a/src/ServiceControl/Operations/ErrorIngestion.cs +++ b/src/ServiceControl/Operations/ErrorIngestion.cs @@ -9,8 +9,8 @@ using Infrastructure; using Infrastructure.Metrics; using Microsoft.Extensions.Hosting; + using Microsoft.Extensions.Logging; using NServiceBus; - using NServiceBus.Logging; using NServiceBus.Transport; using Persistence; using Persistence.UnitOfWork; @@ -30,7 +30,8 @@ public ErrorIngestion( ErrorIngestionCustomCheck.State ingestionState, ErrorIngestor ingestor, IIngestionUnitOfWorkFactory unitOfWorkFactory, - IHostApplicationLifetime applicationLifetime) + IHostApplicationLifetime applicationLifetime, + ILogger logger) { this.settings = settings; this.transportCustomization = transportCustomization; @@ -39,7 +40,7 @@ public ErrorIngestion( this.ingestor = ingestor; this.unitOfWorkFactory = unitOfWorkFactory; this.applicationLifetime = applicationLifetime; - + this.logger = logger; receivedMeter = metrics.GetCounter("Error ingestion - received"); batchSizeMeter = metrics.GetMeter("Error ingestion - batch size"); batchDurationMeter = metrics.GetMeter("Error ingestion - batch processing duration", FrequencyInMilliseconds); @@ -57,7 +58,7 @@ public ErrorIngestion( FullMode = BoundedChannelFullMode.Wait }); - errorHandlingPolicy = new ErrorIngestionFaultPolicy(dataStore, settings.LoggingSettings, OnCriticalError); + errorHandlingPolicy = new ErrorIngestionFaultPolicy(dataStore, settings.LoggingSettings, OnCriticalError, logger); watchdog = new Watchdog( "failed message ingestion", @@ -66,8 +67,7 @@ public ErrorIngestion( ingestionState.ReportError, ingestionState.Clear, settings.TimeToRestartErrorIngestionAfterFailure, - //TODO replace when converting this class to ILogger Logger - LoggerUtil.CreateStaticLogger() + logger ); } @@ -110,11 +110,11 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken) if (e is OperationCanceledException && stoppingToken.IsCancellationRequested) { - Logger.Info("Batch cancelled", e); + logger.LogInformation(e, "Batch cancelled"); break; } - Logger.Info("Ingesting messages failed", e); + logger.LogInformation(e, "Ingesting messages failed"); } finally { @@ -147,7 +147,7 @@ public override async Task StopAsync(CancellationToken cancellationToken) } catch (OperationCanceledException e) when (cancellationToken.IsCancellationRequested) { - Logger.Info("Shutdown cancelled", e); + logger.LogInformation(e, "Shutdown cancelled"); } } } @@ -161,7 +161,7 @@ async Task EnsureStarted(CancellationToken cancellationToken = default) var canIngest = unitOfWorkFactory.CanIngestMore(); - Logger.DebugFormat("Ensure started {0}", canIngest); + logger.LogDebug("Ensure started {CanIngest}", canIngest); if (canIngest) { @@ -195,13 +195,13 @@ async Task SetUpAndStartInfrastructure(CancellationToken cancellationToken) { if (messageReceiver != null) { - Logger.Debug("Infrastructure already Started"); + logger.LogDebug("Infrastructure already Started"); return; } try { - Logger.Info("Starting infrastructure"); + logger.LogInformation("Starting infrastructure"); transportInfrastructure = await transportCustomization.CreateTransportInfrastructure( errorQueue, transportSettings, @@ -220,11 +220,11 @@ async Task SetUpAndStartInfrastructure(CancellationToken cancellationToken) await messageReceiver.StartReceive(cancellationToken); - Logger.Info(LogMessages.StartedInfrastructure); + logger.LogInformation(LogMessages.StartedInfrastructure); } catch (Exception e) { - Logger.Error("Failed to start infrastructure", e); + logger.LogError(e, "Failed to start infrastructure"); throw; } } @@ -232,12 +232,12 @@ async Task StopAndTeardownInfrastructure(CancellationToken cancellationToken) { if (transportInfrastructure == null) { - Logger.Debug("Infrastructure already Stopped"); + logger.LogDebug("Infrastructure already Stopped"); return; } try { - Logger.Info("Stopping infrastructure"); + logger.LogInformation("Stopping infrastructure"); try { if (messageReceiver != null) @@ -253,11 +253,11 @@ async Task StopAndTeardownInfrastructure(CancellationToken cancellationToken) messageReceiver = null; transportInfrastructure = null; - Logger.Info(LogMessages.StoppedInfrastructure); + logger.LogInformation(LogMessages.StoppedInfrastructure); } catch (Exception e) { - Logger.Error("Failed to stop infrastructure", e); + logger.LogError(e, "Failed to stop infrastructure"); throw; } } @@ -285,7 +285,7 @@ async Task OnMessage(MessageContext messageContext, CancellationToken cancellati Task OnCriticalError(string failure, Exception exception) { - Logger.Fatal($"OnCriticalError. '{failure}'", exception); + logger.LogCritical(exception, "OnCriticalError. '{FailureMessage}'", failure); return watchdog.OnFailure(failure); } @@ -323,7 +323,7 @@ async Task EnsureStopped(CancellationToken cancellationToken = default) readonly IIngestionUnitOfWorkFactory unitOfWorkFactory; readonly IHostApplicationLifetime applicationLifetime; - static readonly ILog Logger = LogManager.GetLogger(); + readonly ILogger logger; internal static class LogMessages { diff --git a/src/ServiceControl/Operations/ErrorIngestionFaultPolicy.cs b/src/ServiceControl/Operations/ErrorIngestionFaultPolicy.cs index 107fd831d8..6562e2e22f 100644 --- a/src/ServiceControl/Operations/ErrorIngestionFaultPolicy.cs +++ b/src/ServiceControl/Operations/ErrorIngestionFaultPolicy.cs @@ -9,7 +9,7 @@ using System.Threading.Tasks; using Configuration; using Infrastructure; - using NServiceBus.Logging; + using Microsoft.Extensions.Logging; using NServiceBus.Transport; using Persistence; using ServiceBus.Management.Infrastructure.Installers; @@ -21,9 +21,10 @@ class ErrorIngestionFaultPolicy ImportFailureCircuitBreaker failureCircuitBreaker; - public ErrorIngestionFaultPolicy(IErrorMessageDataStore store, LoggingSettings loggingSettings, Func onCriticalError) + public ErrorIngestionFaultPolicy(IErrorMessageDataStore store, LoggingSettings loggingSettings, Func onCriticalError, ILogger logger) { this.store = store; + this.logger = logger; failureCircuitBreaker = new ImportFailureCircuitBreaker(onCriticalError); if (!AppEnvironment.RunningInContainer) @@ -71,7 +72,7 @@ async Task Handle(ErrorContext errorContext, CancellationToken cancellationToken async Task DoLogging(Exception exception, FailedErrorImport failure, CancellationToken cancellationToken) { - log.Error("Failed importing error message", exception); + logger.LogError(exception, "Failed importing error message"); // Write to data store await store.StoreFailedErrorImport(failure); @@ -98,6 +99,6 @@ static void WriteToEventLog(string message) EventLog.WriteEntry(EventSourceCreator.SourceName, message, EventLogEntryType.Error); } - static readonly ILog log = LogManager.GetLogger(); + readonly ILogger logger; } } \ No newline at end of file diff --git a/src/ServiceControl/Operations/ErrorIngestor.cs b/src/ServiceControl/Operations/ErrorIngestor.cs index 660dcafbb1..820e62758c 100644 --- a/src/ServiceControl/Operations/ErrorIngestor.cs +++ b/src/ServiceControl/Operations/ErrorIngestor.cs @@ -9,7 +9,7 @@ using Contracts.Operations; using Infrastructure.DomainEvents; using Infrastructure.Metrics; - using NServiceBus.Logging; + using Microsoft.Extensions.Logging; using NServiceBus.Routing; using NServiceBus.Transport; using Recoverability; @@ -28,12 +28,13 @@ public ErrorIngestor(Metrics metrics, IIngestionUnitOfWorkFactory unitOfWorkFactory, Lazy messageDispatcher, ITransportCustomization transportCustomization, - Settings settings) + Settings settings, + ILogger logger) { this.unitOfWorkFactory = unitOfWorkFactory; this.messageDispatcher = messageDispatcher; this.settings = settings; - + this.logger = logger; bulkInsertDurationMeter = metrics.GetMeter("Error ingestion - bulk insert duration", FrequencyInMilliseconds); var ingestedMeter = metrics.GetCounter("Error ingestion - ingested"); @@ -45,7 +46,7 @@ public ErrorIngestor(Metrics metrics, }.Concat(errorEnrichers).ToArray(); - errorProcessor = new ErrorProcessor(enrichers, failedMessageEnrichers.ToArray(), domainEvents, ingestedMeter); + errorProcessor = new ErrorProcessor(enrichers, failedMessageEnrichers.ToArray(), domainEvents, ingestedMeter, logger); retryConfirmationProcessor = new RetryConfirmationProcessor(domainEvents); logQueueAddress = new UnicastAddressTag(transportCustomization.ToTransportQualifiedQueueName(this.settings.ErrorLogQueue)); } @@ -86,15 +87,11 @@ public async Task Ingest(List contexts, CancellationToken cancel if (settings.ForwardErrorMessages) { - if (Logger.IsDebugEnabled) - { - Logger.Debug($"Forwarding {storedFailed.Count} messages"); - } + logger.LogDebug("Forwarding {failedMessageCount} messages", storedFailed.Count); + await Forward(storedFailed, cancellationToken); - if (Logger.IsDebugEnabled) - { - Logger.Debug("Forwarded messages"); - } + + logger.LogDebug("Forwarded messages"); } foreach (var context in contexts) @@ -104,10 +101,7 @@ public async Task Ingest(List contexts, CancellationToken cancel } catch (Exception e) { - if (Logger.IsWarnEnabled) - { - Logger.Warn("Forwarding messages failed", e); - } + logger.LogWarning(e, "Forwarding messages failed"); // making sure to rethrow so that all messages get marked as failed throw; @@ -118,10 +112,7 @@ async Task> PersistFailedMessages(List> PersistFailedMessages(List> PersistFailedMessages(List(); + readonly ILogger logger; } } \ No newline at end of file diff --git a/src/ServiceControl/Operations/ErrorProcessor.cs b/src/ServiceControl/Operations/ErrorProcessor.cs index 6ac04c8edd..3eba034851 100644 --- a/src/ServiceControl/Operations/ErrorProcessor.cs +++ b/src/ServiceControl/Operations/ErrorProcessor.cs @@ -8,8 +8,8 @@ using Infrastructure; using Infrastructure.DomainEvents; using Infrastructure.Metrics; + using Microsoft.Extensions.Logging; using NServiceBus; - using NServiceBus.Logging; using NServiceBus.Transport; using Recoverability; using ServiceControl.Persistence; @@ -17,12 +17,17 @@ class ErrorProcessor { - public ErrorProcessor(IEnrichImportedErrorMessages[] enrichers, IFailedMessageEnricher[] failedMessageEnrichers, IDomainEvents domainEvents, - Counter ingestedCounter) + public ErrorProcessor( + IEnrichImportedErrorMessages[] enrichers, + IFailedMessageEnricher[] failedMessageEnrichers, + IDomainEvents domainEvents, + Counter ingestedCounter, + ILogger logger) { this.enrichers = enrichers; this.domainEvents = domainEvents; this.ingestedCounter = ingestedCounter; + this.logger = logger; failedMessageFactory = new FailedMessageFactory(failedMessageEnrichers); } @@ -58,10 +63,7 @@ public async Task> Process(IReadOnlyList(); + readonly ILogger logger; } } \ No newline at end of file diff --git a/src/ServiceControl/Program.cs b/src/ServiceControl/Program.cs index 7c746ff60c..7465bb127b 100644 --- a/src/ServiceControl/Program.cs +++ b/src/ServiceControl/Program.cs @@ -1,15 +1,17 @@ using System; using System.Reflection; -using NServiceBus.Logging; +using Microsoft.Extensions.Logging; using Particular.ServiceControl.Hosting; using ServiceBus.Management.Infrastructure.Settings; using ServiceControl.Configuration; using ServiceControl.Hosting.Commands; using ServiceControl.Infrastructure; +var logger = LoggerUtil.CreateStaticLogger(typeof(Program)); + try { - AppDomain.CurrentDomain.UnhandledException += (s, e) => LogManager.GetLogger(typeof(Program)).Error("Unhandled exception was caught.", e.ExceptionObject as Exception); + AppDomain.CurrentDomain.UnhandledException += (s, e) => logger.LogError(e.ExceptionObject as Exception, "Unhandled exception was caught."); // Hack: See https://github.com/Particular/ServiceControl/issues/4392 var exitCode = await IntegratedSetup.Run(); @@ -40,12 +42,12 @@ } catch (Exception ex) { - NLog.LogManager.GetCurrentClassLogger().Fatal(ex, "Unrecoverable error"); + logger.LogCritical(ex, "Unrecoverable error"); throw; } finally { // The following log statement is meant to leave a trail in the logs to determine if the process was killed - NLog.LogManager.GetCurrentClassLogger().Info("Shutdown complete"); + logger.LogInformation("Shutdown complete"); NLog.LogManager.Shutdown(); } \ No newline at end of file diff --git a/src/ServiceControl/Recoverability/Archiving/ArchiveAllInGroupHandler.cs b/src/ServiceControl/Recoverability/Archiving/ArchiveAllInGroupHandler.cs index c695e220c1..fe8b4ba4d4 100644 --- a/src/ServiceControl/Recoverability/Archiving/ArchiveAllInGroupHandler.cs +++ b/src/ServiceControl/Recoverability/Archiving/ArchiveAllInGroupHandler.cs @@ -1,23 +1,24 @@ namespace ServiceControl.Recoverability { using System.Threading.Tasks; + using Microsoft.Extensions.Logging; using NServiceBus; - using NServiceBus.Logging; using ServiceControl.Persistence.Recoverability; class ArchiveAllInGroupHandler : IHandleMessages { - public ArchiveAllInGroupHandler(IArchiveMessages archiver, RetryingManager retryingManager) + public ArchiveAllInGroupHandler(IArchiveMessages archiver, RetryingManager retryingManager, ILogger logger) { this.archiver = archiver; this.retryingManager = retryingManager; + this.logger = logger; } public async Task Handle(ArchiveAllInGroup message, IMessageHandlerContext context) { if (retryingManager.IsRetryInProgressFor(message.GroupId)) { - Log.Warn($"Attempt to archive a group ({message.GroupId}) which is currently in the process of being retried"); + logger.LogWarning("Attempt to archive a group ({messageGroupId}) which is currently in the process of being retried", message.GroupId); return; } @@ -26,7 +27,6 @@ public async Task Handle(ArchiveAllInGroup message, IMessageHandlerContext conte readonly IArchiveMessages archiver; readonly RetryingManager retryingManager; - - static ILog Log = LogManager.GetLogger(); + readonly ILogger logger; } } diff --git a/src/ServiceControl/Recoverability/Archiving/UnArchiveAllInGroupHandler.cs b/src/ServiceControl/Recoverability/Archiving/UnArchiveAllInGroupHandler.cs index 44eeebd731..82078c1e00 100644 --- a/src/ServiceControl/Recoverability/Archiving/UnArchiveAllInGroupHandler.cs +++ b/src/ServiceControl/Recoverability/Archiving/UnArchiveAllInGroupHandler.cs @@ -1,23 +1,24 @@ namespace ServiceControl.Recoverability { using System.Threading.Tasks; + using Microsoft.Extensions.Logging; using NServiceBus; - using NServiceBus.Logging; using ServiceControl.Persistence.Recoverability; class UnarchiveAllInGroupHandler : IHandleMessages { - public UnarchiveAllInGroupHandler(IArchiveMessages archiver, RetryingManager retryingManager) + public UnarchiveAllInGroupHandler(IArchiveMessages archiver, RetryingManager retryingManager, ILogger logger) { this.archiver = archiver; this.retryingManager = retryingManager; + this.logger = logger; } public async Task Handle(UnarchiveAllInGroup message, IMessageHandlerContext context) { if (retryingManager.IsRetryInProgressFor(message.GroupId)) { - logger.Warn($"Attempt to unarchive a group ({message.GroupId}) which is currently in the process of being retried"); + logger.LogWarning("Attempt to unarchive a group ({messageGroupId}) which is currently in the process of being retried", message.GroupId); return; } @@ -26,7 +27,6 @@ public async Task Handle(UnarchiveAllInGroup message, IMessageHandlerContext con IArchiveMessages archiver; RetryingManager retryingManager; - - static ILog logger = LogManager.GetLogger(); + readonly ILogger logger; } } \ No newline at end of file diff --git a/src/ServiceControl/Recoverability/Editing/EditHandler.cs b/src/ServiceControl/Recoverability/Editing/EditHandler.cs index d1e6bc4685..8a0c97caae 100644 --- a/src/ServiceControl/Recoverability/Editing/EditHandler.cs +++ b/src/ServiceControl/Recoverability/Editing/EditHandler.cs @@ -4,8 +4,8 @@ using System.Linq; using System.Threading.Tasks; using MessageFailures; + using Microsoft.Extensions.Logging; using NServiceBus; - using NServiceBus.Logging; using NServiceBus.Routing; using NServiceBus.Support; using NServiceBus.Transport; @@ -14,13 +14,14 @@ class EditHandler : IHandleMessages { - public EditHandler(IErrorMessageDataStore store, IMessageRedirectsDataStore redirectsStore, IMessageDispatcher dispatcher, ErrorQueueNameCache errorQueueNameCache) + public EditHandler(IErrorMessageDataStore store, IMessageRedirectsDataStore redirectsStore, IMessageDispatcher dispatcher, ErrorQueueNameCache errorQueueNameCache, ILogger logger) { this.store = store; this.redirectsStore = redirectsStore; this.dispatcher = dispatcher; this.errorQueueNameCache = errorQueueNameCache; - corruptedReplyToHeaderStrategy = new CorruptedReplyToHeaderStrategy(RuntimeEnvironment.MachineName); + this.logger = logger; + corruptedReplyToHeaderStrategy = new CorruptedReplyToHeaderStrategy(RuntimeEnvironment.MachineName, logger); } @@ -33,7 +34,7 @@ public async Task Handle(EditAndSend message, IMessageHandlerContext context) if (failedMessage == null) { - log.WarnFormat("Discarding edit {0} because no message failure for id {1} has been found.", context.MessageId, message.FailedMessageId); + logger.LogWarning("Discarding edit {messageId} because no message failure for id {failedMessageId} has been found", context.MessageId, message.FailedMessageId); return; } @@ -42,7 +43,7 @@ public async Task Handle(EditAndSend message, IMessageHandlerContext context) { if (failedMessage.Status != FailedMessageStatus.Unresolved) { - log.WarnFormat("Discarding edit {0} because message failure {1} doesn't have state 'Unresolved'.", context.MessageId, message.FailedMessageId); + logger.LogWarning("Discarding edit {messageId} because message failure {failedMessageId} doesn't have state 'Unresolved'", context.MessageId, message.FailedMessageId); return; } @@ -51,7 +52,7 @@ public async Task Handle(EditAndSend message, IMessageHandlerContext context) } else if (editId != context.MessageId) { - log.WarnFormat($"Discarding edit & retry request because the failed message id {message.FailedMessageId} has already been edited by Message ID {editId}"); + logger.LogWarning("Discarding edit & retry request because the failed message id {failedMessageId} has already been edited by Message ID {editedMessageId}", message.FailedMessageId, editId); return; } @@ -120,6 +121,6 @@ Task DispatchEditedMessage(OutgoingMessage editedMessage, string address, IMessa readonly IMessageRedirectsDataStore redirectsStore; readonly IMessageDispatcher dispatcher; readonly ErrorQueueNameCache errorQueueNameCache; - static readonly ILog log = LogManager.GetLogger(); + readonly ILogger logger; } } \ No newline at end of file diff --git a/src/ServiceControl/Recoverability/RecoverabilityComponent.cs b/src/ServiceControl/Recoverability/RecoverabilityComponent.cs index 875619d35e..8c52e4577b 100644 --- a/src/ServiceControl/Recoverability/RecoverabilityComponent.cs +++ b/src/ServiceControl/Recoverability/RecoverabilityComponent.cs @@ -13,7 +13,7 @@ using Infrastructure.DomainEvents; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; - using NServiceBus.Logging; + using Microsoft.Extensions.Logging; using Operations; using Particular.ServiceControl; using Persistence; @@ -159,17 +159,18 @@ public Task StopAsync(CancellationToken cancellationToken) class BulkRetryBatchCreationHostedService : IHostedService { - public BulkRetryBatchCreationHostedService(RetriesGateway retries, IAsyncTimer scheduler) + public BulkRetryBatchCreationHostedService(RetriesGateway retries, IAsyncTimer scheduler, ILogger logger) { this.retries = retries; this.scheduler = scheduler; + this.logger = logger; } public Task StartAsync(CancellationToken cancellationToken) { if (retries != null) { - timer = scheduler.Schedule(_ => ProcessRequestedBulkRetryOperations(), interval, interval, e => { log.Error("Unhandled exception while processing bulk retry operations", e); }); + timer = scheduler.Schedule(_ => ProcessRequestedBulkRetryOperations(), interval, interval, e => logger.LogError(e, "Unhandled exception while processing bulk retry operations")); } return Task.CompletedTask; @@ -187,7 +188,7 @@ async Task ProcessRequestedBulkRetryOperations() IAsyncTimer scheduler; TimerJob timer; static TimeSpan interval = TimeSpan.FromSeconds(5); - static ILog log = LogManager.GetLogger(); + readonly ILogger logger; } class RebuildRetryGroupStatusesHostedService : IHostedService @@ -212,10 +213,11 @@ public Task StopAsync(CancellationToken cancellationToken) internal class AdoptOrphanBatchesFromPreviousSessionHostedService : IHostedService { - public AdoptOrphanBatchesFromPreviousSessionHostedService(RetryDocumentManager retryDocumentManager, IAsyncTimer scheduler) + public AdoptOrphanBatchesFromPreviousSessionHostedService(RetryDocumentManager retryDocumentManager, IAsyncTimer scheduler, ILogger logger) { this.retryDocumentManager = retryDocumentManager; this.scheduler = scheduler; + this.logger = logger; } internal async Task AdoptOrphanedBatchesAsync() @@ -231,7 +233,7 @@ public Task StartAsync(CancellationToken cancellationToken) { var hasMoreWork = await AdoptOrphanedBatchesAsync(); return hasMoreWork ? TimerJobExecutionResult.ScheduleNextExecution : TimerJobExecutionResult.DoNotContinueExecuting; - }, TimeSpan.Zero, TimeSpan.FromMinutes(2), e => { log.Error("Unhandled exception while trying to adopt orphaned batches", e); }); + }, TimeSpan.Zero, TimeSpan.FromMinutes(2), e => logger.LogError(e, "Unhandled exception while trying to adopt orphaned batches")); return Task.CompletedTask; } @@ -240,7 +242,7 @@ public Task StartAsync(CancellationToken cancellationToken) TimerJob timer; readonly IAsyncTimer scheduler; readonly RetryDocumentManager retryDocumentManager; - static readonly ILog log = LogManager.GetLogger(); + readonly ILogger logger; } class ProcessRetryBatchesHostedService : IHostedService @@ -248,16 +250,18 @@ class ProcessRetryBatchesHostedService : IHostedService public ProcessRetryBatchesHostedService( RetryProcessor processor, Settings settings, - IAsyncTimer scheduler) + IAsyncTimer scheduler, + ILogger logger) { this.processor = processor; this.settings = settings; this.scheduler = scheduler; + this.logger = logger; } public Task StartAsync(CancellationToken cancellationToken) { - timer = scheduler.Schedule(Process, TimeSpan.Zero, settings.ProcessRetryBatchesFrequency, e => { log.Error("Unhandled exception while processing retry batches", e); }); + timer = scheduler.Schedule(Process, TimeSpan.Zero, settings.ProcessRetryBatchesFrequency, e => logger.LogError(e, "Unhandled exception while processing retry batches")); return Task.CompletedTask; } @@ -274,7 +278,7 @@ async Task Process(CancellationToken cancellationToken) TimerJob timer; RetryProcessor processor; - static ILog log = LogManager.GetLogger(typeof(ProcessRetryBatchesHostedService)); + readonly ILogger logger; } } } \ No newline at end of file diff --git a/src/ServiceControl/Recoverability/Retrying/CorruptedReplyToHeaderStrategy.cs b/src/ServiceControl/Recoverability/Retrying/CorruptedReplyToHeaderStrategy.cs index 44a42a0c8e..f11b61efb7 100644 --- a/src/ServiceControl/Recoverability/Retrying/CorruptedReplyToHeaderStrategy.cs +++ b/src/ServiceControl/Recoverability/Retrying/CorruptedReplyToHeaderStrategy.cs @@ -1,14 +1,15 @@ namespace ServiceControl.Recoverability { using System.Collections.Generic; + using Microsoft.Extensions.Logging; using NServiceBus; - using NServiceBus.Logging; class CorruptedReplyToHeaderStrategy { - public CorruptedReplyToHeaderStrategy(string localMachineName) + public CorruptedReplyToHeaderStrategy(string localMachineName, ILogger logger) { this.localMachineName = localMachineName; + this.logger = logger; } public void FixCorruptedReplyToHeader(IDictionary headers) @@ -35,14 +36,13 @@ public void FixCorruptedReplyToHeader(IDictionary headers) if (machineName == localMachineName && machineName != originatingMachine) { var fixedReplyToAddress = $"{queueName}@{originatingMachine}"; - log.Info($"Detected corrupted ReplyToAddress `{replyToAddress}`. Correcting to `{fixedReplyToAddress}`."); + logger.LogInformation("Detected corrupted ReplyToAddress `{replyToAddress}`. Correcting to `{fixedReplyToAddress}`", replyToAddress, fixedReplyToAddress); headers["ServiceControl.OldReplyToAddress"] = replyToAddress; headers[Headers.ReplyToAddress] = fixedReplyToAddress; } } string localMachineName; - - static ILog log = LogManager.GetLogger(typeof(RetryProcessor)); + readonly ILogger logger; } } \ No newline at end of file diff --git a/src/ServiceControl/Recoverability/Retrying/Handlers/RetryAllInGroupHandler.cs b/src/ServiceControl/Recoverability/Retrying/Handlers/RetryAllInGroupHandler.cs index 4e753fff00..fe3d0b2003 100644 --- a/src/ServiceControl/Recoverability/Retrying/Handlers/RetryAllInGroupHandler.cs +++ b/src/ServiceControl/Recoverability/Retrying/Handlers/RetryAllInGroupHandler.cs @@ -2,8 +2,8 @@ namespace ServiceControl.Recoverability { using System; using System.Threading.Tasks; + using Microsoft.Extensions.Logging; using NServiceBus; - using NServiceBus.Logging; using ServiceControl.Persistence; using ServiceControl.Persistence.Recoverability; @@ -13,13 +13,13 @@ public async Task Handle(RetryAllInGroup message, IMessageHandlerContext context { if (retries == null) { - Log.Warn($"Attempt to retry a group ({message.GroupId}) when retries are disabled"); + logger.LogWarning("Attempt to retry a group ({messageGroupId}) when retries are disabled", message.GroupId); return; } if (archiver.IsArchiveInProgressFor(message.GroupId)) { - Log.Warn($"Attempt to retry a group ({message.GroupId}) which is currently in the process of being archived"); + logger.LogWarning("Attempt to retry a group ({messageGroupId}) which is currently in the process of being archived", message.GroupId); return; } @@ -43,18 +43,19 @@ public async Task Handle(RetryAllInGroup message, IMessageHandlerContext context )); } - public RetryAllInGroupHandler(RetriesGateway retries, RetryingManager retryingManager, IArchiveMessages archiver, IRetryDocumentDataStore dataStore) + public RetryAllInGroupHandler(RetriesGateway retries, RetryingManager retryingManager, IArchiveMessages archiver, IRetryDocumentDataStore dataStore, ILogger logger) { this.retries = retries; this.retryingManager = retryingManager; this.archiver = archiver; this.dataStore = dataStore; + this.logger = logger; } readonly RetriesGateway retries; readonly RetryingManager retryingManager; readonly IArchiveMessages archiver; readonly IRetryDocumentDataStore dataStore; - static readonly ILog Log = LogManager.GetLogger(typeof(RetryAllInGroupHandler)); + readonly ILogger logger; } } \ No newline at end of file diff --git a/src/ServiceControl/Recoverability/Retrying/InMemoryRetry.cs b/src/ServiceControl/Recoverability/Retrying/InMemoryRetry.cs index e234661a2d..980884abd5 100644 --- a/src/ServiceControl/Recoverability/Retrying/InMemoryRetry.cs +++ b/src/ServiceControl/Recoverability/Retrying/InMemoryRetry.cs @@ -3,16 +3,17 @@ using System; using System.Threading.Tasks; using Infrastructure.DomainEvents; - using NServiceBus.Logging; + using Microsoft.Extensions.Logging; using ServiceControl.Persistence; public class InMemoryRetry { - public InMemoryRetry(string requestId, RetryType retryType, IDomainEvents domainEvents) + public InMemoryRetry(string requestId, RetryType retryType, IDomainEvents domainEvents, ILogger logger) { RequestId = requestId; this.retryType = retryType; this.domainEvents = domainEvents; + this.logger = logger; } public string RequestId { get; } @@ -177,7 +178,11 @@ await domainEvents.Raise(new MessagesSubmittedForRetry }); } - Log.Info($"Retry operation {RequestId} completed. {NumberOfMessagesSkipped} messages skipped, {NumberOfMessagesForwarded} forwarded. Total {TotalNumberOfMessages}."); + logger.LogInformation("Retry operation {requestId} completed. {numberOfMessagesSkipped} messages skipped, {numberOfMessagesForwarded} forwarded. Total {totalNumberOfMessages}", + RequestId, + NumberOfMessagesSkipped, + NumberOfMessagesForwarded, + TotalNumberOfMessages); } public RetryProgress GetProgress() @@ -203,6 +208,6 @@ public bool IsInProgress() readonly RetryType retryType; IDomainEvents domainEvents; - static readonly ILog Log = LogManager.GetLogger(typeof(InMemoryRetry)); + readonly ILogger logger; } } \ No newline at end of file diff --git a/src/ServiceControl/Recoverability/Retrying/Infrastructure/ReturnToSender.cs b/src/ServiceControl/Recoverability/Retrying/Infrastructure/ReturnToSender.cs index cacbdbd420..04a9163da2 100644 --- a/src/ServiceControl/Recoverability/Retrying/Infrastructure/ReturnToSender.cs +++ b/src/ServiceControl/Recoverability/Retrying/Infrastructure/ReturnToSender.cs @@ -4,12 +4,12 @@ namespace ServiceControl.Recoverability using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; - using NServiceBus.Logging; + using Microsoft.Extensions.Logging; using NServiceBus.Routing; using NServiceBus.Transport; using ServiceControl.Persistence; - class ReturnToSender(IErrorMessageDataStore errorMessageStore) + class ReturnToSender(IErrorMessageDataStore errorMessageStore, ILogger logger) { public virtual async Task HandleMessage(MessageContext message, IMessageDispatcher sender, string errorQueueTransportAddress, CancellationToken cancellationToken = default) { @@ -20,10 +20,8 @@ public virtual async Task HandleMessage(MessageContext message, IMessageDispatch byte[] body = null; var messageId = message.NativeMessageId; - if (Log.IsDebugEnabled) - { - Log.DebugFormat("{0}: Retrieving message body", messageId); - } + + logger.LogDebug("{messageId}: Retrieving message body", messageId); if (outgoingHeaders.TryGetValue("ServiceControl.Retry.Attempt.MessageId", out var attemptMessageId)) { @@ -32,16 +30,14 @@ public virtual async Task HandleMessage(MessageContext message, IMessageDispatch } else { - Log.WarnFormat("{0}: Can't find message body. Missing header ServiceControl.Retry.Attempt.MessageId", messageId); + logger.LogWarning("{messageId}: Can't find message body. Missing header ServiceControl.Retry.Attempt.MessageId", messageId); } var outgoingMessage = new OutgoingMessage(messageId, outgoingHeaders, body ?? EmptyBody); var destination = outgoingHeaders["ServiceControl.TargetEndpointAddress"]; - if (Log.IsDebugEnabled) - { - Log.DebugFormat("{0}: Forwarding message to {1}", messageId, destination); - } + + logger.LogDebug("{messageId}: Forwarding message to {destination}", messageId, destination); if (!outgoingHeaders.TryGetValue("ServiceControl.RetryTo", out var retryTo)) { @@ -50,20 +46,14 @@ public virtual async Task HandleMessage(MessageContext message, IMessageDispatch } else { - if (Log.IsDebugEnabled) - { - Log.DebugFormat("{0}: Found ServiceControl.RetryTo header. Rerouting to {1}", messageId, retryTo); - } + logger.LogDebug("{messageId}: Found ServiceControl.RetryTo header. Rerouting to {retryTo}", messageId, retryTo); } var transportOp = new TransportOperation(outgoingMessage, new UnicastAddressTag(retryTo)); await sender.Dispatch(new TransportOperations(transportOp), message.TransportTransaction, cancellationToken); - if (Log.IsDebugEnabled) - { - Log.DebugFormat("{0}: Forwarded message to {1}", messageId, retryTo); - } + logger.LogDebug("{messageId}: Forwarded message to {retryTo}", messageId, retryTo); } async Task FetchFromFailedMessage(Dictionary outgoingHeaders, string messageId, string attemptMessageId) @@ -73,17 +63,17 @@ async Task FetchFromFailedMessage(Dictionary outgoingHea if (body == null) { - Log.WarnFormat("{0}: Message Body not found in failed message with unique id {1} for attempt Id {1}", messageId, uniqueMessageId, attemptMessageId); + logger.LogWarning("{messageId}: Message Body not found in failed message with unique id {uniqueMessageId} for attempt Id {attemptMessageId}", messageId, uniqueMessageId, attemptMessageId); } - else if (Log.IsDebugEnabled) + else { - Log.DebugFormat("{0}: Body size: {1} bytes retrieved from failed message attachment", messageId, body.LongLength); + logger.LogDebug("{messageId}: Body size: {messageLength} bytes retrieved from failed message attachment", messageId, body.LongLength); } return body; } static readonly byte[] EmptyBody = Array.Empty(); - static readonly ILog Log = LogManager.GetLogger(typeof(ReturnToSender)); + readonly ILogger logger = logger; } } diff --git a/src/ServiceControl/Recoverability/Retrying/Infrastructure/ReturnToSenderDequeuer.cs b/src/ServiceControl/Recoverability/Retrying/Infrastructure/ReturnToSenderDequeuer.cs index 81ef5562f3..fcbd9b9ced 100644 --- a/src/ServiceControl/Recoverability/Retrying/Infrastructure/ReturnToSenderDequeuer.cs +++ b/src/ServiceControl/Recoverability/Retrying/Infrastructure/ReturnToSenderDequeuer.cs @@ -5,8 +5,8 @@ namespace ServiceControl.Recoverability; using System.Threading.Tasks; using Infrastructure.DomainEvents; using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; using NServiceBus; -using NServiceBus.Logging; using NServiceBus.Transport; using Persistence; using ServiceBus.Management.Infrastructure.Settings; @@ -21,7 +21,8 @@ public ReturnToSenderDequeuer( ITransportCustomization transportCustomization, TransportSettings transportSettings, Settings settings, - ErrorQueueNameCache errorQueueNameCache + ErrorQueueNameCache errorQueueNameCache, + ILogger logger ) { InputAddress = transportCustomization.ToTransportQualifiedQueueName(settings.StagingQueue); @@ -30,8 +31,8 @@ ErrorQueueNameCache errorQueueNameCache this.transportCustomization = transportCustomization; this.transportSettings = transportSettings; this.errorQueueNameCache = errorQueueNameCache; - - faultManager = new CaptureIfMessageSendingFails(dataStore, domainEvents, IncrementCounterOrProlongTimer); + this.logger = logger; + faultManager = new CaptureIfMessageSendingFails(dataStore, domainEvents, IncrementCounterOrProlongTimer, logger); timer = new Timer(state => StopInternal().GetAwaiter().GetResult()); } @@ -59,11 +60,8 @@ public async Task StopAsync(CancellationToken cancellationToken) async Task Handle(MessageContext message, CancellationToken cancellationToken) { - if (Log.IsDebugEnabled) - { - var stagingId = message.Headers["ServiceControl.Retry.StagingId"]; - Log.DebugFormat("Handling message with id {0} and staging id {1} in input queue {2}", message.NativeMessageId, stagingId, InputAddress); - } + var stagingId = message.Headers["ServiceControl.Retry.StagingId"]; + logger.LogDebug("Handling message with id {nativeMessageId} and staging id {stagingId} in input queue {inputAddress}", message.NativeMessageId, stagingId, InputAddress); if (shouldProcess(message)) { @@ -72,7 +70,7 @@ async Task Handle(MessageContext message, CancellationToken cancellationToken) } else { - Log.WarnFormat("Rejecting message from staging queue as it's not part of a fully staged batch: {0}", message.NativeMessageId); + logger.LogWarning("Rejecting message from staging queue as it's not part of a fully staged batch: {nativeMessageId}", message.NativeMessageId); } } @@ -84,10 +82,7 @@ void IncrementCounterOrProlongTimer() } else { - if (Log.IsDebugEnabled) - { - Log.Debug("Resetting timer"); - } + logger.LogDebug("Resetting timer"); timer.Change(TimeSpan.FromSeconds(45), Timeout.InfiniteTimeSpan); } @@ -96,17 +91,12 @@ void IncrementCounterOrProlongTimer() void CountMessageAndStopIfReachedTarget() { var currentMessageCount = Interlocked.Increment(ref actualMessageCount); - if (Log.IsDebugEnabled) - { - Log.Debug($"Forwarding message {currentMessageCount} of {targetMessageCount}."); - } + + logger.LogDebug("Forwarding message {currentMessageCount} of {targetMessageCount}", currentMessageCount, targetMessageCount); if (currentMessageCount >= targetMessageCount.GetValueOrDefault()) { - if (Log.IsDebugEnabled) - { - Log.DebugFormat("Target count reached. Shutting down forwarder"); - } + logger.LogDebug("Target count reached. Shutting down forwarder"); // NOTE: This needs to run on a different thread or a deadlock will happen trying to shut down the receiver _ = Task.Run(StopInternal); @@ -122,10 +112,7 @@ public virtual async Task Run(string forwardingBatchId, Predicate(TaskCreationOptions.RunContinuationsAsynchronously); stopCompletionSource = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); @@ -133,30 +120,24 @@ public virtual async Task Run(string forwardingBatchId, Predicate logger; class CaptureIfMessageSendingFails { - public CaptureIfMessageSendingFails(IErrorMessageDataStore dataStore, IDomainEvents domainEvents, Action executeOnFailure) + public CaptureIfMessageSendingFails(IErrorMessageDataStore dataStore, IDomainEvents domainEvents, Action executeOnFailure, ILogger logger) { this.dataStore = dataStore; this.executeOnFailure = executeOnFailure; + this.logger = logger; this.domainEvents = domainEvents; } @@ -223,7 +200,7 @@ public async Task OnError(ErrorContext errorContext, Cancella var message = errorContext.Message; var destination = message.Headers["ServiceControl.TargetEndpointAddress"]; var messageUniqueId = message.Headers["ServiceControl.Retry.UniqueMessageId"]; - Log.Warn($"Failed to send '{messageUniqueId}' message to '{destination}' for retry. Attempting to revert message status to unresolved so it can be tried again.", errorContext.Exception); + logger.LogWarning(errorContext.Exception, "Failed to send '{messageUniqueId}' message to '{destination}' for retry. Attempting to revert message status to unresolved so it can be tried again", messageUniqueId, destination); await dataStore.RevertRetry(messageUniqueId); @@ -247,7 +224,7 @@ await domainEvents.Raise(new MessagesSubmittedForRetryFailed catch (Exception ex) { // If something goes wrong here we just ignore, not the end of the world! - Log.Error("A failure occurred when trying to handle a retry failure.", ex); + logger.LogError(ex, "A failure occurred when trying to handle a retry failure"); } finally { @@ -260,7 +237,6 @@ await domainEvents.Raise(new MessagesSubmittedForRetryFailed readonly Action executeOnFailure; readonly IErrorMessageDataStore dataStore; readonly IDomainEvents domainEvents; - static readonly ILog Log = LogManager.GetLogger(typeof(CaptureIfMessageSendingFails)); + readonly ILogger logger; } - } diff --git a/src/ServiceControl/Recoverability/Retrying/RetriesGateway.cs b/src/ServiceControl/Recoverability/Retrying/RetriesGateway.cs index c1ddb84baf..f2de937d36 100644 --- a/src/ServiceControl/Recoverability/Retrying/RetriesGateway.cs +++ b/src/ServiceControl/Recoverability/Retrying/RetriesGateway.cs @@ -7,20 +7,21 @@ namespace ServiceControl.Recoverability using System.Threading.Tasks; using Infrastructure; using MessageFailures; - using NServiceBus.Logging; + using Microsoft.Extensions.Logging; using ServiceControl.Persistence; class RetriesGateway { - public RetriesGateway(IRetryDocumentDataStore store, RetryingManager operationManager) + public RetriesGateway(IRetryDocumentDataStore store, RetryingManager operationManager, ILogger logger) { this.store = store; this.operationManager = operationManager; + this.logger = logger; } public async Task StartRetryForSingleMessage(string uniqueMessageId) { - Log.Info($"Retrying a single message {uniqueMessageId}"); + logger.LogInformation("Retrying a single message {uniqueMessageId}", uniqueMessageId); var requestId = uniqueMessageId; var retryType = RetryType.SingleMessage; @@ -33,7 +34,7 @@ public async Task StartRetryForSingleMessage(string uniqueMessageId) public async Task StartRetryForMessageSelection(string[] uniqueMessageIds) { - Log.Info($"Retrying a selection of {uniqueMessageIds.Length} messages"); + logger.LogInformation("Retrying a selection of {messageCount} messages", uniqueMessageIds.Length); var requestId = DeterministicGuid.MakeId(string.Join(string.Empty, uniqueMessageIds)).ToString(); var retryType = RetryType.MultipleMessages; @@ -48,7 +49,7 @@ async Task StageRetryByUniqueMessageIds(string requestId, RetryType retryType, s { if (messageIds == null || !messageIds.Any()) { - Log.Info($"Batch '{batchName}' contains no messages"); + logger.LogInformation("Batch '{batchName}' contains no messages", batchName); return; } @@ -56,13 +57,13 @@ async Task StageRetryByUniqueMessageIds(string requestId, RetryType retryType, s var batchDocumentId = await store.CreateBatchDocument(RetryDocumentManager.RetrySessionId, requestId, retryType, failedMessageRetryIds, originator, startTime, last, batchName, classifier); - Log.Info($"Created Batch '{batchDocumentId}' with {messageIds.Length} messages for '{batchName}'."); + logger.LogInformation("Created Batch '{batchDocumentId}' with {batchMessageCount} messages for '{batchName}'.", batchDocumentId, messageIds.Length, batchName); await store.StageRetryByUniqueMessageIds(batchDocumentId, messageIds); await MoveBatchToStaging(batchDocumentId); - Log.Info($"Moved Batch '{batchDocumentId}' to Staging"); + logger.LogInformation("Moved Batch '{batchDocumentId}' to Staging", batchDocumentId); } // Needs to be overridable by a test @@ -114,27 +115,27 @@ static string GetBatchName(int pageNum, int totalPages, string context) public void StartRetryForAllMessages() { var item = new RetryForAllMessages(); - Log.Info($"Enqueuing index based bulk retry '{item}'"); + logger.LogInformation("Enqueuing index based bulk retry '{item}'", item); bulkRequests.Enqueue(item); } public void StartRetryForEndpoint(string endpoint) { var item = new RetryForEndpoint(endpoint); - Log.Info($"Enqueuing index based bulk retry '{item}'"); + logger.LogInformation("Enqueuing index based bulk retry '{item}'", item); bulkRequests.Enqueue(item); } public void StartRetryForFailedQueueAddress(string failedQueueAddress, FailedMessageStatus status) { var item = new RetryForFailedQueueAddress(failedQueueAddress, status); - Log.Info($"Enqueuing index based bulk retry '{item}'"); + logger.LogInformation("Enqueuing index based bulk retry '{item}'", item); bulkRequests.Enqueue(item); } public void EnqueueRetryForFailureGroup(RetryForFailureGroup item) { - Log.Info($"Enqueuing index based bulk retry '{item}'"); + logger.LogInformation("Enqueuing index based bulk retry '{item}'", item); bulkRequests.Enqueue(item); } @@ -143,7 +144,7 @@ public void EnqueueRetryForFailureGroup(RetryForFailureGroup item) readonly ConcurrentQueue bulkRequests = new ConcurrentQueue(); const int BatchSize = 1000; - static readonly ILog Log = LogManager.GetLogger(typeof(RetriesGateway)); + readonly ILogger logger; public abstract class BulkRetryRequest { diff --git a/src/ServiceControl/Recoverability/Retrying/RetryDocumentManager.cs b/src/ServiceControl/Recoverability/Retrying/RetryDocumentManager.cs index a94d9d3e76..165c71f369 100644 --- a/src/ServiceControl/Recoverability/Retrying/RetryDocumentManager.cs +++ b/src/ServiceControl/Recoverability/Retrying/RetryDocumentManager.cs @@ -4,28 +4,29 @@ namespace ServiceControl.Recoverability using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Hosting; - using NServiceBus.Logging; + using Microsoft.Extensions.Logging; using ServiceControl.Persistence; class RetryDocumentManager { - public RetryDocumentManager(IHostApplicationLifetime applicationLifetime, IRetryDocumentDataStore store, RetryingManager operationManager) + public RetryDocumentManager(IHostApplicationLifetime applicationLifetime, IRetryDocumentDataStore store, RetryingManager operationManager, ILogger logger) { this.store = store; applicationLifetime?.ApplicationStopping.Register(() => { abort = true; }); this.operationManager = operationManager; + this.logger = logger; } public async Task AdoptOrphanedBatches() { var orphanedBatches = await store.QueryOrphanedBatches(RetrySessionId); - log.Info($"Found {orphanedBatches.Results.Count} orphaned retry batches from previous sessions."); + logger.LogInformation("Found {orphanedBatchCount} orphaned retry batches from previous sessions", orphanedBatches.Results.Count); // let's leave Task.Run for now due to sync sends await Task.WhenAll(orphanedBatches.Results.Select(b => Task.Run(async () => { - log.Info($"Adopting retry batch {b.Id} with {b.FailureRetries.Count} messages."); + logger.LogInformation("Adopting retry batch {b.Id} with {b.FailureRetries.Count} messages", b.Id, b.FailureRetries.Count); await MoveBatchToStaging(b.Id); }))); @@ -55,10 +56,7 @@ public async Task RebuildRetryOperationState() { if (!string.IsNullOrWhiteSpace(group.RequestId)) { - if (log.IsDebugEnabled) - { - log.DebugFormat("Rebuilt retry operation status for {0}/{1}. Aggregated batchsize: {2}", group.RetryType, group.RequestId, group.InitialBatchSize); - } + logger.LogDebug("Rebuilt retry operation status for {retryType}/{retryRequestId}. Aggregated batchsize: {retryBatchSize}", group.RetryType, group.RequestId, group.InitialBatchSize); await operationManager.PreparedAdoptedBatch(group.RequestId, group.RetryType, group.InitialBatchSize, group.InitialBatchSize, group.Originator, group.Classifier, group.StartTime, group.Last); } @@ -70,6 +68,6 @@ public async Task RebuildRetryOperationState() bool abort; public static string RetrySessionId = Guid.NewGuid().ToString(); - static readonly ILog log = LogManager.GetLogger(typeof(RetryDocumentManager)); + readonly ILogger logger; } } \ No newline at end of file diff --git a/src/ServiceControl/Recoverability/Retrying/RetryProcessor.cs b/src/ServiceControl/Recoverability/Retrying/RetryProcessor.cs index b5868e1532..6ee73cdadb 100644 --- a/src/ServiceControl/Recoverability/Retrying/RetryProcessor.cs +++ b/src/ServiceControl/Recoverability/Retrying/RetryProcessor.cs @@ -7,7 +7,7 @@ namespace ServiceControl.Recoverability using System.Threading.Tasks; using Infrastructure.DomainEvents; using MessageFailures; - using NServiceBus.Logging; + using Microsoft.Extensions.Logging; using NServiceBus.Routing; using NServiceBus.Support; using NServiceBus.Transport; @@ -16,14 +16,21 @@ namespace ServiceControl.Recoverability class RetryProcessor { - public RetryProcessor(IRetryBatchesDataStore store, IDomainEvents domainEvents, ReturnToSenderDequeuer returnToSender, RetryingManager retryingManager, Lazy messageDispatcher) + public RetryProcessor( + IRetryBatchesDataStore store, + IDomainEvents domainEvents, + ReturnToSenderDequeuer returnToSender, + RetryingManager retryingManager, + Lazy messageDispatcher, + ILogger logger) { this.store = store; this.returnToSender = returnToSender; this.retryingManager = retryingManager; this.domainEvents = domainEvents; this.messageDispatcher = messageDispatcher; - corruptedReplyToHeaderStrategy = new CorruptedReplyToHeaderStrategy(RuntimeEnvironment.MachineName); + this.logger = logger; + corruptedReplyToHeaderStrategy = new CorruptedReplyToHeaderStrategy(RuntimeEnvironment.MachineName, logger); } Task Enqueue(TransportOperations outgoingMessages) @@ -47,10 +54,7 @@ async Task MoveStagedBatchesToForwardingBatch(IRetryBatchesManager manager { try { - if (Logger.IsDebugEnabled) - { - Logger.Debug("Looking for batch to stage."); - } + logger.LogDebug("Looking for batch to stage"); isRecoveringFromPrematureShutdown = false; @@ -58,7 +62,7 @@ async Task MoveStagedBatchesToForwardingBatch(IRetryBatchesManager manager if (stagingBatch != null) { - Logger.Info($"Staging batch {stagingBatch.Id}."); + logger.LogInformation("Staging batch {stagingBatchId}", stagingBatch.Id); redirects = await manager.GetOrCreateMessageRedirectsCollection(); var stagedMessages = await Stage(stagingBatch, manager); var skippedMessages = stagingBatch.InitialBatchSize - stagedMessages; @@ -66,7 +70,7 @@ async Task MoveStagedBatchesToForwardingBatch(IRetryBatchesManager manager if (stagedMessages > 0) { - Logger.Info($"Batch {stagingBatch.Id} with {stagedMessages} messages staged and {skippedMessages} skipped ready to be forwarded."); + logger.LogInformation("Batch {stagingBatchId} with {stagedMessages} messages staged and {skippedMessages} skipped ready to be forwarded", stagingBatch.Id, stagedMessages, skippedMessages); await manager.Store(new RetryBatchNowForwarding { RetryBatchId = stagingBatch.Id @@ -76,7 +80,7 @@ await manager.Store(new RetryBatchNowForwarding return true; } - Logger.Debug("No batch found to stage."); + logger.LogDebug("No batch found to stage"); return false; } catch (RetryStagingException) @@ -87,51 +91,36 @@ await manager.Store(new RetryBatchNowForwarding async Task ForwardCurrentBatch(IRetryBatchesManager manager, CancellationToken cancellationToken) { - if (Logger.IsDebugEnabled) - { - Logger.Debug("Looking for batch to forward."); - } + logger.LogDebug("Looking for batch to forward"); var nowForwarding = await manager.GetRetryBatchNowForwarding(); if (nowForwarding != null) { - if (Logger.IsDebugEnabled) - { - Logger.Debug($"Loading batch {nowForwarding.RetryBatchId} for forwarding."); - } + logger.LogDebug("Loading batch {retryBatchId} for forwarding", nowForwarding.RetryBatchId); var forwardingBatch = await manager.GetRetryBatch(nowForwarding.RetryBatchId, cancellationToken); if (forwardingBatch != null) { - if (Logger.IsDebugEnabled) - { - Logger.Info($"Forwarding batch {forwardingBatch.Id}."); - } + logger.LogInformation("Forwarding batch {retryBatchId}", forwardingBatch.Id); await Forward(forwardingBatch, manager, cancellationToken); - if (Logger.IsDebugEnabled) - { - Logger.DebugFormat("Retry batch {0} forwarded.", forwardingBatch.Id); - } + logger.LogDebug("Retry batch {retryBatchId} forwarded", forwardingBatch.Id); } else { - Logger.Warn($"Could not find retry batch {nowForwarding.RetryBatchId} to forward."); + logger.LogWarning("Could not find retry batch {retryBatchId} to forward", nowForwarding.RetryBatchId); } - if (Logger.IsDebugEnabled) - { - Logger.Debug("Removing forwarding document."); - } + logger.LogDebug("Removing forwarding document"); manager.Delete(nowForwarding); return true; } - Logger.Debug("No batch found to forward."); + logger.LogDebug("No batch found to forward"); return false; } @@ -143,7 +132,7 @@ async Task Forward(RetryBatch forwardingBatch, IRetryBatchesManager manager, Can if (isRecoveringFromPrematureShutdown) { - Logger.Warn($"Recovering from premature shutdown. Starting forwarder for batch {forwardingBatch.Id} in timeout mode."); + logger.LogWarning("Recovering from premature shutdown. Starting forwarder for batch {forwardingBatchId} in timeout mode", forwardingBatch.Id); await returnToSender.Run(forwardingBatch.Id, IsPartOfStagedBatch(forwardingBatch.StagingId), null, cancellationToken); await retryingManager.ForwardedBatch(forwardingBatch.RequestId, forwardingBatch.RetryType, forwardingBatch.InitialBatchSize); } @@ -151,11 +140,11 @@ async Task Forward(RetryBatch forwardingBatch, IRetryBatchesManager manager, Can { if (messageCount == 0) { - Logger.Info($"Skipping forwarding of batch {forwardingBatch.Id}: no messages to forward."); + logger.LogInformation("Skipping forwarding of batch {forwardingBatchId}: no messages to forward", forwardingBatch.Id); } else { - Logger.Info($"Starting forwarder for batch {forwardingBatch.Id} with {messageCount} messages in counting mode."); + logger.LogInformation("Starting forwarder for batch {forwardingBatchId} with {messageCount} messages in counting mode", forwardingBatch.Id, messageCount); await returnToSender.Run(forwardingBatch.Id, IsPartOfStagedBatch(forwardingBatch.StagingId), messageCount, cancellationToken); } @@ -164,7 +153,7 @@ async Task Forward(RetryBatch forwardingBatch, IRetryBatchesManager manager, Can manager.Delete(forwardingBatch); - Logger.Info($"Done forwarding batch {forwardingBatch.Id}."); + logger.LogInformation("Done forwarding batch {forwardingBatchId}", forwardingBatch.Id); } static Predicate IsPartOfStagedBatch(string stagingId) @@ -197,7 +186,7 @@ async Task Stage(RetryBatch stagingBatch, IRetryBatchesManager manager) if (failedMessageRetriesById.Count == 0) { - Logger.Info($"Retry batch {stagingBatch.Id} cancelled as all matching unresolved messages are already marked for retry as part of another batch."); + logger.LogInformation("Retry batch {retryBatchId} cancelled as all matching unresolved messages are already marked for retry as part of another batch", stagingBatch.Id); manager.Delete(stagingBatch); return 0; } @@ -205,7 +194,7 @@ async Task Stage(RetryBatch stagingBatch, IRetryBatchesManager manager) var failedMessagesDocs = await manager.GetFailedMessages(failedMessageRetriesById.Keys); var messages = failedMessagesDocs.Where(m => m != null).ToArray(); - Logger.Info($"Staging {messages.Length} messages for retry batch {stagingBatch.Id} with staging attempt Id {stagingId}."); + logger.LogInformation("Staging {messageCount} messages for retry batch {retryBatchId} with staging attempt Id {stagingId}", messages.Length, stagingBatch.Id, stagingId); var previousAttemptFailed = false; var transportOperations = new TransportOperation[messages.Length]; @@ -242,7 +231,7 @@ await domainEvents.Raise(new MessagesSubmittedForRetry stagingBatch.Status = RetryBatchStatus.Forwarding; stagingBatch.StagingId = stagingId; stagingBatch.FailureRetries = failedMessageRetriesById.Values.Where(x => msgLookup[x.FailedMessageId].Any()).Select(x => x.Id).ToArray(); - Logger.Info($"Retry batch {stagingBatch.Id} staged with Staging Id {stagingBatch.StagingId} and {stagingBatch.FailureRetries.Count} matching failure retries"); + logger.LogInformation("Retry batch {retryBatchId} staged with Staging Id {stagingId} and {retryFailureCount} matching failure retries", stagingBatch.Id, stagingBatch.StagingId, stagingBatch.FailureRetries.Count); return messages.Length; } @@ -292,13 +281,13 @@ async Task TryStageMessage(TransportOperation transportOperation, FailedMessageR if (incrementedAttempts < MaxStagingAttempts) { - Logger.Warn($"Attempt {incrementedAttempts} of {MaxStagingAttempts} to stage a retry message {uniqueMessageId} failed", e); + logger.LogWarning(e, "Attempt {stagingRetryAttempt} of {stagingRetryLimit} to stage a retry message {retryMessageId} failed", incrementedAttempts, MaxStagingAttempts, uniqueMessageId); await store.IncrementAttemptCounter(failedMessageRetry); } else { - Logger.Error($"Retry message {uniqueMessageId} reached its staging retry limit ({MaxStagingAttempts}) and is going to be removed from the batch.", e); + logger.LogError(e, "Retry message {retryMessageId} reached its staging retry limit ({stagingRetryLimit}) and is going to be removed from the batch", uniqueMessageId, MaxStagingAttempts); await store.DeleteFailedMessageRetry(uniqueMessageId); @@ -343,12 +332,11 @@ TransportOperation ToTransportOperation(FailedMessage message, string stagingId) readonly ReturnToSenderDequeuer returnToSender; readonly RetryingManager retryingManager; readonly Lazy messageDispatcher; - MessageRedirectsCollection redirects; bool isRecoveringFromPrematureShutdown = true; CorruptedReplyToHeaderStrategy corruptedReplyToHeaderStrategy; protected internal const int MaxStagingAttempts = 5; - static readonly ILog Logger = LogManager.GetLogger(typeof(RetryProcessor)); + readonly ILogger logger; } } \ No newline at end of file diff --git a/src/ServiceControl/Recoverability/Retrying/RetryingManager.cs b/src/ServiceControl/Recoverability/Retrying/RetryingManager.cs index 8f01ae56f0..95af86ae8f 100644 --- a/src/ServiceControl/Recoverability/Retrying/RetryingManager.cs +++ b/src/ServiceControl/Recoverability/Retrying/RetryingManager.cs @@ -5,13 +5,15 @@ using System.Linq; using System.Threading.Tasks; using Infrastructure.DomainEvents; + using Microsoft.Extensions.Logging; using ServiceControl.Persistence; public class RetryingManager { - public RetryingManager(IDomainEvents domainEvents) + public RetryingManager(IDomainEvents domainEvents, ILogger logger) { this.domainEvents = domainEvents; + this.logger = logger; } public Task Wait(string requestId, RetryType retryType, DateTime started, string originator = null, string classifier = null, DateTime? last = null) @@ -128,7 +130,7 @@ public async Task Skip(string requestId, RetryType retryType, int numberOfMessag InMemoryRetry GetOrCreate(RetryType retryType, string requestId) { var key = InMemoryRetry.MakeOperationId(requestId, retryType); - return retryOperations.GetOrAdd(key, _ => new InMemoryRetry(requestId, retryType, domainEvents)); + return retryOperations.GetOrAdd(key, _ => new InMemoryRetry(requestId, retryType, domainEvents, logger)); } public InMemoryRetry GetStatusForRetryOperation(string requestId, RetryType retryType) @@ -139,6 +141,7 @@ public InMemoryRetry GetStatusForRetryOperation(string requestId, RetryType retr } IDomainEvents domainEvents; + readonly ILogger logger; ConcurrentDictionary retryOperations = new ConcurrentDictionary(); } } \ No newline at end of file diff --git a/src/ServiceControl/SagaAudit/GetSagaByIdApi.cs b/src/ServiceControl/SagaAudit/GetSagaByIdApi.cs index 8d6d3eda9c..61dfaef988 100644 --- a/src/ServiceControl/SagaAudit/GetSagaByIdApi.cs +++ b/src/ServiceControl/SagaAudit/GetSagaByIdApi.cs @@ -4,13 +4,14 @@ namespace ServiceControl.SagaAudit using System.Linq; using System.Net.Http; using CompositeViews.Messages; + using Microsoft.Extensions.Logging; using Persistence.Infrastructure; using ServiceBus.Management.Infrastructure.Settings; public record SagaByIdContext(PagingInfo PagingInfo, Guid SagaId) : ScatterGatherContext(PagingInfo); - public class GetSagaByIdApi(Settings settings, IHttpClientFactory httpClientFactory) - : ScatterGatherRemoteOnly(settings, httpClientFactory) + public class GetSagaByIdApi(Settings settings, IHttpClientFactory httpClientFactory, ILogger logger) + : ScatterGatherRemoteOnly(settings, httpClientFactory, logger) { protected override SagaHistory ProcessResults(SagaByIdContext input, QueryResult[] results) { diff --git a/src/ServiceControl/SagaAudit/SagaUpdatedHandler.cs b/src/ServiceControl/SagaAudit/SagaUpdatedHandler.cs index d8d0bb36f9..f67f95002a 100644 --- a/src/ServiceControl/SagaAudit/SagaUpdatedHandler.cs +++ b/src/ServiceControl/SagaAudit/SagaUpdatedHandler.cs @@ -5,12 +5,12 @@ using System.Threading; using System.Threading.Tasks; using EndpointPlugin.Messages.SagaState; + using Microsoft.Extensions.Logging; using NServiceBus; - using NServiceBus.Logging; using ServiceControl.Connection; using ServiceControl.Infrastructure; - class SagaUpdatedHandler(IPlatformConnectionBuilder connectionBuilder) + class SagaUpdatedHandler(IPlatformConnectionBuilder connectionBuilder, ILogger logger) : IHandleMessages { public async Task Handle(SagaUpdatedMessage message, IMessageHandlerContext context) @@ -28,7 +28,9 @@ public async Task Handle(SagaUpdatedMessage message, IMessageHandlerContext cont } var endpointName = context.MessageHeaders.TryGetValue(Headers.ReplyToAddress, out var val) ? val : "(Unknown Endpoint)"; - log.ErrorFormat($"Received a saga audit message in the ServiceControl queue that should have been sent to the audit queue. This indicates that the endpoint '{endpointName}' using the SagaAudit plugin is misconfigured and should be changed to use the system's audit queue instead. The message has been forwarded to the audit queue, but this may not be possible in a future version of ServiceControl."); + logger.LogError("Received a saga audit message in the ServiceControl queue that should have been sent to the audit queue. " + + "This indicates that the endpoint '{endpointName}' using the SagaAudit plugin is misconfigured and should be changed to use the system's audit queue instead. " + + "The message has been forwarded to the audit queue, but this may not be possible in a future version of ServiceControl.", endpointName); await context.ForwardCurrentMessageTo(auditQueueName); } @@ -55,12 +57,12 @@ async Task RefreshAuditQueue() // Pick any audit queue, assume all instance are based on competing consumer auditQueueName = sagaAudit.GetProperty("SagaAuditQueue").GetString(); nextAuditQueueNameRefresh = DateTime.UtcNow.AddMinutes(5); - log.InfoFormat("Refreshed audit queue name '{0}' from ServiceControl Audit instance. Will continue to use this value for forwarding saga update messages for the next 5 minutes.", auditQueueName); + logger.LogInformation("Refreshed audit queue name '{auditQueueName}' from ServiceControl Audit instance. Will continue to use this value for forwarding saga update messages for the next 5 minutes.", auditQueueName); } } catch (Exception x) { - log.WarnFormat("Unable to refresh audit queue name from ServiceControl Audit instance. Will continue to check at most every 15 seconds. Exception message: {0}", x.Message); + logger.LogWarning("Unable to refresh audit queue name from ServiceControl Audit instance. Will continue to check at most every 15 seconds. Exception message: {exceptionMessage}", x.Message); nextAuditQueueNameRefresh = DateTime.UtcNow.AddSeconds(15); } finally @@ -72,6 +74,6 @@ async Task RefreshAuditQueue() static string auditQueueName; static DateTime nextAuditQueueNameRefresh; static readonly SemaphoreSlim semaphore = new(1); - static readonly ILog log = LogManager.GetLogger(); + readonly ILogger logger = logger; } } From 89ee38f0e90222fb6e05ecea0f4bba2f9f2f29d3 Mon Sep 17 00:00:00 2001 From: Andreas Bednarz Date: Mon, 16 Jun 2025 15:58:07 +1000 Subject: [PATCH 2/5] Register EmailSender in DI container since dependents now expect it to be injected --- .../Email/EmailNotificationHostBuilderExtensions.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/ServiceControl/Notifications/Email/EmailNotificationHostBuilderExtensions.cs b/src/ServiceControl/Notifications/Email/EmailNotificationHostBuilderExtensions.cs index c4672a7437..a72bf6a17e 100644 --- a/src/ServiceControl/Notifications/Email/EmailNotificationHostBuilderExtensions.cs +++ b/src/ServiceControl/Notifications/Email/EmailNotificationHostBuilderExtensions.cs @@ -10,6 +10,7 @@ public static IHostApplicationBuilder AddEmailNotifications(this IHostApplicatio { var services = hostBuilder.Services; services.AddSingleton(); + services.AddSingleton(); services.AddDomainEventHandler(); services.AddHostedService(); return hostBuilder; From 7840facae8441877fe136ea016afb2e3c1d99f2c Mon Sep 17 00:00:00 2001 From: Andreas Bednarz Date: Tue, 17 Jun 2025 10:43:36 +1000 Subject: [PATCH 3/5] Use CreateStaticLogger for command loggers --- .../StartupModeTests.cs | 2 +- .../TestSupport/ServiceControlComponentRunner.cs | 2 +- .../Hosting/Commands/ImportFailedAuditsCommand.cs | 5 +++-- .../Infrastructure/Hosting/Commands/SetupCommand.cs | 2 +- .../Hosting/Commands/ImportFailedErrorsCommand.cs | 5 +++-- src/ServiceControl/Hosting/Commands/SetupCommand.cs | 5 +++-- 6 files changed, 12 insertions(+), 9 deletions(-) diff --git a/src/ServiceControl.AcceptanceTests.RavenDB/StartupModeTests.cs b/src/ServiceControl.AcceptanceTests.RavenDB/StartupModeTests.cs index 3e568ebc46..02f868009a 100644 --- a/src/ServiceControl.AcceptanceTests.RavenDB/StartupModeTests.cs +++ b/src/ServiceControl.AcceptanceTests.RavenDB/StartupModeTests.cs @@ -58,7 +58,7 @@ public async Task CanRunMaintenanceMode() public async Task CanRunImportFailedMessagesMode() => await new TestableImportFailedErrorsCommand().Execute(new HostArguments(Array.Empty()), settings); - class TestableImportFailedErrorsCommand() : ImportFailedErrorsCommand(NullLogger.Instance) + class TestableImportFailedErrorsCommand() : ImportFailedErrorsCommand() { protected override EndpointConfiguration CreateEndpointConfiguration(Settings settings) { diff --git a/src/ServiceControl.AcceptanceTests/TestSupport/ServiceControlComponentRunner.cs b/src/ServiceControl.AcceptanceTests/TestSupport/ServiceControlComponentRunner.cs index 2a722ecb61..1b6cd03449 100644 --- a/src/ServiceControl.AcceptanceTests/TestSupport/ServiceControlComponentRunner.cs +++ b/src/ServiceControl.AcceptanceTests/TestSupport/ServiceControlComponentRunner.cs @@ -103,7 +103,7 @@ async Task InitializeServiceControl(ScenarioContext context) using (new DiagnosticTimer($"Creating infrastructure for {instanceName}")) { - var setupCommand = new SetupCommand(NullLogger.Instance); + var setupCommand = new SetupCommand(); await setupCommand.Execute(new HostArguments([]), settings); } diff --git a/src/ServiceControl.Audit/Infrastructure/Hosting/Commands/ImportFailedAuditsCommand.cs b/src/ServiceControl.Audit/Infrastructure/Hosting/Commands/ImportFailedAuditsCommand.cs index a4d65b2c85..c2b5926d58 100644 --- a/src/ServiceControl.Audit/Infrastructure/Hosting/Commands/ImportFailedAuditsCommand.cs +++ b/src/ServiceControl.Audit/Infrastructure/Hosting/Commands/ImportFailedAuditsCommand.cs @@ -8,9 +8,10 @@ using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using NServiceBus; + using ServiceControl.Infrastructure; using Settings; - class ImportFailedAuditsCommand(ILogger logger) : AbstractCommand + class ImportFailedAuditsCommand : AbstractCommand { public override async Task Execute(HostArguments args, Settings settings) { @@ -40,7 +41,7 @@ public override async Task Execute(HostArguments args, Settings settings) } catch (OperationCanceledException e) when (tokenSource.IsCancellationRequested) { - logger.LogInformation(e, "Cancelled"); + LoggerUtil.CreateStaticLogger().LogInformation(e, "Cancelled"); } finally { diff --git a/src/ServiceControl.Audit/Infrastructure/Hosting/Commands/SetupCommand.cs b/src/ServiceControl.Audit/Infrastructure/Hosting/Commands/SetupCommand.cs index 7837fbd684..73480e72e2 100644 --- a/src/ServiceControl.Audit/Infrastructure/Hosting/Commands/SetupCommand.cs +++ b/src/ServiceControl.Audit/Infrastructure/Hosting/Commands/SetupCommand.cs @@ -9,7 +9,7 @@ using Settings; using Transports; - class SetupCommand() : AbstractCommand + class SetupCommand : AbstractCommand { public override async Task Execute(HostArguments args, Settings settings) { diff --git a/src/ServiceControl/Hosting/Commands/ImportFailedErrorsCommand.cs b/src/ServiceControl/Hosting/Commands/ImportFailedErrorsCommand.cs index 55923b0111..4adafa724f 100644 --- a/src/ServiceControl/Hosting/Commands/ImportFailedErrorsCommand.cs +++ b/src/ServiceControl/Hosting/Commands/ImportFailedErrorsCommand.cs @@ -12,8 +12,9 @@ using Particular.ServiceControl; using Particular.ServiceControl.Hosting; using ServiceBus.Management.Infrastructure.Settings; + using ServiceControl.Infrastructure; - class ImportFailedErrorsCommand(ILogger logger) : AbstractCommand + class ImportFailedErrorsCommand : AbstractCommand { public override async Task Execute(HostArguments args, Settings settings) { @@ -41,7 +42,7 @@ public override async Task Execute(HostArguments args, Settings settings) } catch (OperationCanceledException e) when (tokenSource.IsCancellationRequested) { - logger.LogInformation(e, "Cancelled"); + LoggerUtil.CreateStaticLogger().LogInformation(e, "Cancelled"); } finally { diff --git a/src/ServiceControl/Hosting/Commands/SetupCommand.cs b/src/ServiceControl/Hosting/Commands/SetupCommand.cs index eec1a515e8..3fdc2e7e11 100644 --- a/src/ServiceControl/Hosting/Commands/SetupCommand.cs +++ b/src/ServiceControl/Hosting/Commands/SetupCommand.cs @@ -8,9 +8,10 @@ using Particular.ServiceControl.Hosting; using ServiceBus.Management.Infrastructure.Installers; using ServiceBus.Management.Infrastructure.Settings; + using ServiceControl.Infrastructure; using Transports; - class SetupCommand(ILogger logger) : AbstractCommand + class SetupCommand : AbstractCommand { public override async Task Execute(HostArguments args, Settings settings) { @@ -35,7 +36,7 @@ public override async Task Execute(HostArguments args, Settings settings) if (args.SkipQueueCreation) { - logger.LogInformation("Skipping queue creation"); + LoggerUtil.CreateStaticLogger().LogInformation("Skipping queue creation"); } else { From baa1585df56c12f96da763e4126ee78304a3abb0 Mon Sep 17 00:00:00 2001 From: Andreas Bednarz Date: Tue, 17 Jun 2025 12:35:30 +1000 Subject: [PATCH 4/5] Logging parameters converted to Pascal case --- .../AuditThroughputCollectorHostedService.cs | 12 ++++---- .../BrokerThroughputCollectorHostedService.cs | 6 ++-- .../MonitoringThroughputHostedService.cs | 4 +-- .../Messages/GetMessagesController.cs | 5 ++-- .../Messages/ScatterGatherApi.cs | 6 ++-- ...RemotePlatformConnectionDetailsProvider.cs | 6 ++-- .../InternalCustomCheckManager.cs | 2 +- .../RepeatedFailuresOverTimeCircuitBreaker.cs | 10 +++---- .../Infrastructure/Settings/Settings.cs | 2 +- .../SignalR/MessageStreamerHub.cs | 2 +- .../Api/EditFailedMessagesController.cs | 6 ++-- .../Api/RetryMessagesController.cs | 2 +- .../Monitoring/EndpointInstanceMonitor.cs | 2 +- ...rtbeatEndpointSettingsSyncHostedService.cs | 14 ++++----- .../HeartbeatMonitoringHostedService.cs | 2 +- .../Notifications/Email/EmailSender.cs | 2 +- .../Operations/ErrorIngestor.cs | 6 ++-- .../Operations/ErrorProcessor.cs | 6 ++-- src/ServiceControl/Program.cs | 2 +- .../Archiving/ArchiveAllInGroupHandler.cs | 2 +- .../Archiving/UnArchiveAllInGroupHandler.cs | 2 +- .../Recoverability/Editing/EditHandler.cs | 6 ++-- .../CorruptedReplyToHeaderStrategy.cs | 2 +- .../Handlers/RetryAllInGroupHandler.cs | 4 +-- .../Recoverability/Retrying/InMemoryRetry.cs | 2 +- .../Retrying/Infrastructure/ReturnToSender.cs | 14 ++++----- .../Infrastructure/ReturnToSenderDequeuer.cs | 14 ++++----- .../Recoverability/Retrying/RetriesGateway.cs | 18 +++++------ .../Retrying/RetryDocumentManager.cs | 6 ++-- .../Recoverability/Retrying/RetryProcessor.cs | 30 +++++++++---------- .../SagaAudit/SagaUpdatedHandler.cs | 6 ++-- 31 files changed, 100 insertions(+), 103 deletions(-) diff --git a/src/Particular.LicensingComponent/AuditThroughput/AuditThroughputCollectorHostedService.cs b/src/Particular.LicensingComponent/AuditThroughput/AuditThroughputCollectorHostedService.cs index e60a4531db..fed7540ac6 100644 --- a/src/Particular.LicensingComponent/AuditThroughput/AuditThroughputCollectorHostedService.cs +++ b/src/Particular.LicensingComponent/AuditThroughput/AuditThroughputCollectorHostedService.cs @@ -20,7 +20,7 @@ public class AuditThroughputCollectorHostedService( protected override async Task ExecuteAsync(CancellationToken cancellationToken) { - logger.LogInformation($"Starting {nameof(AuditThroughputCollectorHostedService)}"); + logger.LogInformation("Starting {ServiceName}", nameof(AuditThroughputCollectorHostedService)); try { @@ -42,14 +42,14 @@ protected override async Task ExecuteAsync(CancellationToken cancellationToken) } catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { - logger.LogInformation($"Stopping {nameof(AuditThroughputCollectorHostedService)}"); + logger.LogInformation("Stopping {ServiceName}", nameof(AuditThroughputCollectorHostedService)); } } async Task GatherThroughput(CancellationToken cancellationToken) { var utcYesterday = DateOnly.FromDateTime(timeProvider.GetUtcNow().DateTime).AddDays(-1); - logger.LogInformation($"Gathering throughput from audit for {utcYesterday.ToShortDateString()}"); + logger.LogInformation("Gathering throughput from audit for {AuditDate}", utcYesterday.ToShortDateString()); await VerifyAuditInstances(cancellationToken); @@ -115,18 +115,18 @@ async Task VerifyAuditInstances(CancellationToken cancellationToken) { if (remote.Status == "online" || remote.SemanticVersion is not null) { - logger.LogInformation($"ServiceControl Audit instance at {remote.ApiUri} detected running version {remote.SemanticVersion}"); + logger.LogInformation("ServiceControl Audit instance at {RemoteApiUri} detected running version {RemoteSemanticVersion}", remote.ApiUri, remote.SemanticVersion); } else { - logger.LogWarning($"Unable to determine the version of one or more ServiceControl Audit instances. For the instance with URI {remote.ApiUri}, the status was '{remote.Status}' and the version string returned was '{remote.VersionString}'."); + logger.LogWarning("Unable to determine the version of one or more ServiceControl Audit instances. For the instance with URI {RemoteApiUri}, the status was '{RemoteStatus}' and the version string returned was '{RemoteVersionString}'.", remote.ApiUri, remote.Status, remote.VersionString); } } var allHaveAuditCounts = remotesInfo.All(auditQuery.ValidRemoteInstances); if (!allHaveAuditCounts) { - logger.LogWarning($"At least one ServiceControl Audit instance is either not running the required version ({auditQuery.MinAuditCountsVersion}) or is not configured for at least 2 days of retention. Audit throughput will not be available."); + logger.LogWarning("At least one ServiceControl Audit instance is either not running the required version ({RequiredAuditVersion}) or is not configured for at least 2 days of retention. Audit throughput will not be available.", auditQuery.MinAuditCountsVersion); } } diff --git a/src/Particular.LicensingComponent/BrokerThroughput/BrokerThroughputCollectorHostedService.cs b/src/Particular.LicensingComponent/BrokerThroughput/BrokerThroughputCollectorHostedService.cs index 8bb88190fe..497f7eb2f3 100644 --- a/src/Particular.LicensingComponent/BrokerThroughput/BrokerThroughputCollectorHostedService.cs +++ b/src/Particular.LicensingComponent/BrokerThroughput/BrokerThroughputCollectorHostedService.cs @@ -29,11 +29,11 @@ static ReadOnlyDictionary LoadBrokerSettingValues(IEnumerable LoadBrokerSettingValues(IEnumerable Task.FromResult(ErrorHandleResult.Handled), (_, __) => Task.CompletedTask); await transportInfrastructure.Receivers[ServiceControlSettings.ServiceControlThroughputDataQueue].StartReceive(cancellationToken); @@ -32,7 +32,7 @@ public async Task StartAsync(CancellationToken cancellationToken) public async Task StopAsync(CancellationToken cancellationToken) { - logger.LogInformation($"Stopping {nameof(MonitoringThroughputHostedService)}"); + logger.LogInformation("Stopping {ServiceName}", nameof(MonitoringThroughputHostedService)); if (transportInfrastructure != null) { diff --git a/src/ServiceControl/CompositeViews/Messages/GetMessagesController.cs b/src/ServiceControl/CompositeViews/Messages/GetMessagesController.cs index f3f657ccd9..d29837891a 100644 --- a/src/ServiceControl/CompositeViews/Messages/GetMessagesController.cs +++ b/src/ServiceControl/CompositeViews/Messages/GetMessagesController.cs @@ -107,9 +107,8 @@ public async Task Get(string id, [FromQuery(Name = "instance_id") var forwarderError = await forwarder.SendAsync(HttpContext, remote.BaseAddress, httpMessageInvoker); if (forwarderError != ForwarderError.None && HttpContext.GetForwarderErrorFeature()?.Exception is { } exception) { - logger.LogWarning(exception, "Failed to forward the request to remote instance at {remoteBaseAddress}{httpPathAndQuery}", - remote.BaseAddress, - HttpContext.Request.GetEncodedPathAndQuery()); + logger.LogWarning(exception, "Failed to forward the request to remote instance at {RemoteInstanceUrl}", + remote.BaseAddress + HttpContext.Request.GetEncodedPathAndQuery()); } return Empty; diff --git a/src/ServiceControl/CompositeViews/Messages/ScatterGatherApi.cs b/src/ServiceControl/CompositeViews/Messages/ScatterGatherApi.cs index cd388ce613..d9fc9cb535 100644 --- a/src/ServiceControl/CompositeViews/Messages/ScatterGatherApi.cs +++ b/src/ServiceControl/CompositeViews/Messages/ScatterGatherApi.cs @@ -122,19 +122,19 @@ async Task> FetchAndParse(HttpClient httpClient, string pathAn remoteInstanceSetting.TemporarilyUnavailable = true; logger.LogWarning( httpRequestException, - "An HttpRequestException occurred when querying remote instance at {remoteInstanceSettingBaseAddress}. The instance at uri: {remoteInstanceSettingBaseAddress} will be temporarily disabled", + "An HttpRequestException occurred when querying remote instance at {RemoteInstanceBaseAddress}. The instance at uri: {RemoteInstanceBaseAddress} will be temporarily disabled", remoteInstanceSetting.BaseAddress, remoteInstanceSetting.BaseAddress); return QueryResult.Empty(); } catch (OperationCanceledException) // Intentional, used to gracefully handle timeout { - logger.LogWarning("Failed to query remote instance at {remoteInstanceSettingBaseAddress} due to a timeout", remoteInstanceSetting.BaseAddress); + logger.LogWarning("Failed to query remote instance at {RemoteInstanceBaseAddress} due to a timeout", remoteInstanceSetting.BaseAddress); return QueryResult.Empty(); } catch (Exception exception) { - logger.LogWarning(exception, "Failed to query remote instance at {remoteInstanceSettingBaseAddress}", remoteInstanceSetting.BaseAddress); + logger.LogWarning(exception, "Failed to query remote instance at {RemoteInstanceBaseAddress}", remoteInstanceSetting.BaseAddress); return QueryResult.Empty(); } } diff --git a/src/ServiceControl/Connection/RemotePlatformConnectionDetailsProvider.cs b/src/ServiceControl/Connection/RemotePlatformConnectionDetailsProvider.cs index 999a3cb2fe..a0b8df6089 100644 --- a/src/ServiceControl/Connection/RemotePlatformConnectionDetailsProvider.cs +++ b/src/ServiceControl/Connection/RemotePlatformConnectionDetailsProvider.cs @@ -32,11 +32,9 @@ async Task UpdateFromRemote(RemoteInstanceSetting remote, PlatformConnectionDeta catch (Exception ex) { var remoteConnectionUri = $"{remote.BaseAddress.TrimEnd('/')}/connection"; - var message = $"Unable to get connection details from ServiceControl Audit instance at {remoteConnectionUri}."; - connection.Errors.Add(message); - - logger.LogError(ex, "Unable to get connection details from ServiceControl Audit instance at {remoteConnectionUri}", remoteConnectionUri); + connection.Errors.Add($"Unable to get connection details from ServiceControl Audit instance at {remoteConnectionUri}."); + logger.LogError(ex, "Unable to get connection details from ServiceControl Audit instance at {RemoteInstanceUrl}", remoteConnectionUri); } } } diff --git a/src/ServiceControl/CustomChecks/InternalCustomChecks/InternalCustomCheckManager.cs b/src/ServiceControl/CustomChecks/InternalCustomChecks/InternalCustomCheckManager.cs index 5b24076ea1..a2442771f6 100644 --- a/src/ServiceControl/CustomChecks/InternalCustomChecks/InternalCustomCheckManager.cs +++ b/src/ServiceControl/CustomChecks/InternalCustomChecks/InternalCustomCheckManager.cs @@ -51,7 +51,7 @@ async Task Run(CancellationToken cancellationToken) var customCheckType = check.GetType(); var reason = $"`{customCheckType}` implementation failed to run."; result = CheckResult.Failed(reason); - logger.LogError(ex, "`{customCheckType}` implementation failed to run", customCheckType); + logger.LogError(ex, "`{CustomCheckType}` implementation failed to run", customCheckType); } var detail = new CustomCheckDetail diff --git a/src/ServiceControl/ExternalIntegrations/RepeatedFailuresOverTimeCircuitBreaker.cs b/src/ServiceControl/ExternalIntegrations/RepeatedFailuresOverTimeCircuitBreaker.cs index 44ee562de3..3977af150b 100644 --- a/src/ServiceControl/ExternalIntegrations/RepeatedFailuresOverTimeCircuitBreaker.cs +++ b/src/ServiceControl/ExternalIntegrations/RepeatedFailuresOverTimeCircuitBreaker.cs @@ -40,11 +40,11 @@ public void Success() if (timer.Change(Timeout.Infinite, Timeout.Infinite)) { - logger.LogInformation("The circuit breaker for {circuitBreakerName} is now disarmed", name); + logger.LogInformation("The circuit breaker for {CircuitBreakerName} is now disarmed", name); } else { - logger.LogError("Attempted to disarm circuit breaker for {circuitBreakerName} but failed", name); + logger.LogError("Attempted to disarm circuit breaker for {CircuitBreakerName} but failed", name); } } @@ -57,11 +57,11 @@ public Task Failure(Exception exception) { if (timer.Change(timeToWaitBeforeTriggering, NoPeriodicTriggering)) { - logger.LogWarning("The circuit breaker for {circuitBreakerName} is now in the armed state", name); + logger.LogWarning("The circuit breaker for {CircuitBreakerName} is now in the armed state", name); } else { - logger.LogError("Attempted to arm circuit breaker for {circuitBreakerName} but failed", name); + logger.LogError("Attempted to arm circuit breaker for {CircuitBreakerName} but failed", name); } } @@ -72,7 +72,7 @@ void CircuitBreakerTriggered(object state) { if (Interlocked.Read(ref failureCount) > 0) { - logger.LogWarning("The circuit breaker for {circuitBreakerName} will now be triggered", name); + logger.LogWarning("The circuit breaker for {CircuitBreakerName} will now be triggered", name); triggerAction(lastException); } } diff --git a/src/ServiceControl/Infrastructure/Settings/Settings.cs b/src/ServiceControl/Infrastructure/Settings/Settings.cs index 35a2433323..772d33203d 100644 --- a/src/ServiceControl/Infrastructure/Settings/Settings.cs +++ b/src/ServiceControl/Infrastructure/Settings/Settings.cs @@ -402,7 +402,7 @@ void LoadErrorIngestionSettings() if (!IngestErrorMessages) { - logger.LogInformation("Error ingestion disabled."); + logger.LogInformation("Error ingestion disabled"); } ErrorLogQueue = SettingsReader.Read(serviceBusRootNamespace, "ErrorLogQueue", null); diff --git a/src/ServiceControl/Infrastructure/SignalR/MessageStreamerHub.cs b/src/ServiceControl/Infrastructure/SignalR/MessageStreamerHub.cs index 21aee94189..208e5fb7a2 100644 --- a/src/ServiceControl/Infrastructure/SignalR/MessageStreamerHub.cs +++ b/src/ServiceControl/Infrastructure/SignalR/MessageStreamerHub.cs @@ -51,7 +51,7 @@ public async Task SendMessage(string data) } catch (Exception ex) { - logger.LogError(ex, "Failed to process SignalR message. AuditMessage={auditMessage}", data); + logger.LogError(ex, "Failed to process SignalR message. AuditMessage={AuditMessage}", data); throw; } } diff --git a/src/ServiceControl/MessageFailures/Api/EditFailedMessagesController.cs b/src/ServiceControl/MessageFailures/Api/EditFailedMessagesController.cs index 428be7f0ae..6b37009982 100644 --- a/src/ServiceControl/MessageFailures/Api/EditFailedMessagesController.cs +++ b/src/ServiceControl/MessageFailures/Api/EditFailedMessagesController.cs @@ -39,7 +39,7 @@ public async Task Edit(string failedMessageId, [FromBody] EditMes if (failedMessage == null) { - logger.LogWarning("The original failed message could not be loaded for id={failedMessageId}", failedMessageId); + logger.LogWarning("The original failed message could not be loaded for id={FailedMessageId}", failedMessageId); return BadRequest(); } @@ -55,13 +55,13 @@ public async Task Edit(string failedMessageId, [FromBody] EditMes if (LockedHeaderModificationValidator.Check(GetEditConfiguration().LockedHeaders, edit.MessageHeaders, failedMessage.ProcessingAttempts.Last().Headers)) { - logger.LogWarning("Locked headers have been modified on the edit-retry for MessageID {failedMessageId}", failedMessageId); + logger.LogWarning("Locked headers have been modified on the edit-retry for MessageID {FailedMessageId}", failedMessageId); return BadRequest(); } if (string.IsNullOrWhiteSpace(edit.MessageBody) || edit.MessageHeaders == null) { - logger.LogWarning("There is no message body on the edit-retry for MessageID {failedMessageId}", failedMessageId); + logger.LogWarning("There is no message body on the edit-retry for MessageID {FailedMessageId}", failedMessageId); return BadRequest(); } diff --git a/src/ServiceControl/MessageFailures/Api/RetryMessagesController.cs b/src/ServiceControl/MessageFailures/Api/RetryMessagesController.cs index 8f98d422f9..c486129df9 100644 --- a/src/ServiceControl/MessageFailures/Api/RetryMessagesController.cs +++ b/src/ServiceControl/MessageFailures/Api/RetryMessagesController.cs @@ -43,7 +43,7 @@ public async Task RetryMessageBy([FromQuery(Name = "instance_id") var forwarderError = await forwarder.SendAsync(HttpContext, remote.BaseAddress, httpMessageInvoker); if (forwarderError != ForwarderError.None && HttpContext.GetForwarderErrorFeature()?.Exception is { } exception) { - logger.LogWarning(exception, "Failed to forward the request ot remote instance at {remoteInstanceUrl}", remote.BaseAddress + HttpContext.Request.GetEncodedPathAndQuery()); + logger.LogWarning(exception, "Failed to forward the request to remote instance at {RemoteInstanceUrl}", remote.BaseAddress + HttpContext.Request.GetEncodedPathAndQuery()); } return Empty; diff --git a/src/ServiceControl/Monitoring/EndpointInstanceMonitor.cs b/src/ServiceControl/Monitoring/EndpointInstanceMonitor.cs index c50bae3dc8..5ec475da02 100644 --- a/src/ServiceControl/Monitoring/EndpointInstanceMonitor.cs +++ b/src/ServiceControl/Monitoring/EndpointInstanceMonitor.cs @@ -40,7 +40,7 @@ public async Task UpdateStatus(HeartbeatStatus newStatus, DateTime? latestTimest if (newStatus != status) { await RaiseStateChangeEvents(newStatus, latestTimestamp); - logger.LogDebug("Endpoint {logicalEndpointName} status updated from {oldHeartbeatStatus} to {newHeartbeatStatus}", Id.LogicalName, status, newStatus); + logger.LogDebug("Endpoint {LogicalEndpointName} status updated from {OldHeartbeatStatus} to {NewHeartbeatStatus}", Id.LogicalName, status, newStatus); } lastSeen = latestTimestamp; diff --git a/src/ServiceControl/Monitoring/HeartbeatEndpointSettingsSyncHostedService.cs b/src/ServiceControl/Monitoring/HeartbeatEndpointSettingsSyncHostedService.cs index 31898ecbbb..5f75cf5885 100644 --- a/src/ServiceControl/Monitoring/HeartbeatEndpointSettingsSyncHostedService.cs +++ b/src/ServiceControl/Monitoring/HeartbeatEndpointSettingsSyncHostedService.cs @@ -23,7 +23,7 @@ public class HeartbeatEndpointSettingsSyncHostedService( protected override async Task ExecuteAsync(CancellationToken cancellationToken) { - logger.LogInformation($"Starting {nameof(HeartbeatEndpointSettingsSyncHostedService)}"); + logger.LogInformation("Starting {ServiceName}", nameof(HeartbeatEndpointSettingsSyncHostedService)); try { @@ -35,7 +35,7 @@ protected override async Task ExecuteAsync(CancellationToken cancellationToken) { try { - logger.LogInformation($"Performing sync for {nameof(HeartbeatEndpointSettingsSyncHostedService)}"); + logger.LogInformation("Performing sync for {ServiceName}", nameof(HeartbeatEndpointSettingsSyncHostedService)); await PerformSync(cancellationToken); } catch (Exception ex) when (ex is not OperationCanceledException) @@ -47,7 +47,7 @@ protected override async Task ExecuteAsync(CancellationToken cancellationToken) } catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { - logger.LogInformation($"Stopping {nameof(HeartbeatEndpointSettingsSyncHostedService)}"); + logger.LogInformation("Stopping {ServiceName}", nameof(HeartbeatEndpointSettingsSyncHostedService)); } } @@ -80,7 +80,7 @@ async Task PurgeMonitoringDataThatDoesNotNeedToBeTracked(CancellationToken cance { endpointInstanceMonitoring.RemoveEndpoint(endpointId); await monitoringDataStore.Delete(endpointId); - logger.LogInformation($"Removed endpoint '{endpointSetting.Name}' from monitoring data."); + logger.LogInformation("Removed endpoint '{EndpointName}' from monitoring data", endpointSetting.Name); } } } @@ -108,7 +108,7 @@ async Task InitialiseSettings(HashSet monitorEndpoints, CancellationToke { await endpointSettingsStore.Delete(endpointSetting.Name, cancellationToken); logger.LogInformation( - $"Removed EndpointTracking setting for '{endpointSetting.Name}' endpoint, since this endpoint is no longer monitored."); + "Removed EndpointTracking setting for '{Setting}' endpoint, since this endpoint is no longer monitored", endpointSetting.Name); } settingsNames.Add(endpointSetting.Name); @@ -121,7 +121,7 @@ await endpointSettingsStore.UpdateEndpointSettings( new EndpointSettings { Name = string.Empty, TrackInstances = userSetTrackInstances }, cancellationToken); logger.LogInformation( - $"Initialized default value of EndpointTracking to {(userSetTrackInstances ? "tracking" : "not tracking")}."); + "Initialized default value of EndpointTracking to {TrackInstances}", userSetTrackInstances ? "tracking" : "not tracking"); } // Initialise settings for any missing endpoint @@ -131,7 +131,7 @@ await endpointSettingsStore.UpdateEndpointSettings( new EndpointSettings { Name = name, TrackInstances = userSetTrackInstances }, cancellationToken); logger.LogInformation( - $"Initialized '{name}' value of EndpointTracking to {(userSetTrackInstances ? "tracking" : "not tracking")}."); + "Initialized '{Setting}' value of EndpointTracking to {TrackInstances}", name, userSetTrackInstances ? "tracking" : "not tracking"); } } } \ No newline at end of file diff --git a/src/ServiceControl/Monitoring/HeartbeatMonitoringHostedService.cs b/src/ServiceControl/Monitoring/HeartbeatMonitoringHostedService.cs index a84dff5a81..93f6818d74 100644 --- a/src/ServiceControl/Monitoring/HeartbeatMonitoringHostedService.cs +++ b/src/ServiceControl/Monitoring/HeartbeatMonitoringHostedService.cs @@ -31,7 +31,7 @@ async Task CheckEndpoints() { var inactivityThreshold = DateTime.UtcNow - gracePeriod; - logger.LogDebug("Monitoring Endpoint Instances. Inactivity Threshold = {inactivityThreshold}", inactivityThreshold); + logger.LogDebug("Monitoring Endpoint Instances. Inactivity Threshold = {InactivityThreshold}", inactivityThreshold); await monitor.CheckEndpoints(inactivityThreshold); return TimerJobExecutionResult.ScheduleNextExecution; diff --git a/src/ServiceControl/Notifications/Email/EmailSender.cs b/src/ServiceControl/Notifications/Email/EmailSender.cs index 257b3044bc..57e07375c5 100644 --- a/src/ServiceControl/Notifications/Email/EmailSender.cs +++ b/src/ServiceControl/Notifications/Email/EmailSender.cs @@ -20,7 +20,7 @@ public async Task Send(EmailNotifications settings, string subject, string body, } catch (Exception e) { - logger.LogWarning(e, "Failure sending email."); + logger.LogWarning(e, "Failure sending email"); throw; } } diff --git a/src/ServiceControl/Operations/ErrorIngestor.cs b/src/ServiceControl/Operations/ErrorIngestor.cs index 820e62758c..39f4f264f5 100644 --- a/src/ServiceControl/Operations/ErrorIngestor.cs +++ b/src/ServiceControl/Operations/ErrorIngestor.cs @@ -87,7 +87,7 @@ public async Task Ingest(List contexts, CancellationToken cancel if (settings.ForwardErrorMessages) { - logger.LogDebug("Forwarding {failedMessageCount} messages", storedFailed.Count); + logger.LogDebug("Forwarding {FailedMessageCount} messages", storedFailed.Count); await Forward(storedFailed, cancellationToken); @@ -112,7 +112,7 @@ async Task> PersistFailedMessages(List> PersistFailedMessages(List> Process(IReadOnlyList logger.LogError(e.ExceptionObject as Exception, "Unhandled exception was caught."); + AppDomain.CurrentDomain.UnhandledException += (s, e) => logger.LogError(e.ExceptionObject as Exception, "Unhandled exception was caught"); // Hack: See https://github.com/Particular/ServiceControl/issues/4392 var exitCode = await IntegratedSetup.Run(); diff --git a/src/ServiceControl/Recoverability/Archiving/ArchiveAllInGroupHandler.cs b/src/ServiceControl/Recoverability/Archiving/ArchiveAllInGroupHandler.cs index fe8b4ba4d4..cabaab602b 100644 --- a/src/ServiceControl/Recoverability/Archiving/ArchiveAllInGroupHandler.cs +++ b/src/ServiceControl/Recoverability/Archiving/ArchiveAllInGroupHandler.cs @@ -18,7 +18,7 @@ public async Task Handle(ArchiveAllInGroup message, IMessageHandlerContext conte { if (retryingManager.IsRetryInProgressFor(message.GroupId)) { - logger.LogWarning("Attempt to archive a group ({messageGroupId}) which is currently in the process of being retried", message.GroupId); + logger.LogWarning("Attempt to archive a group ({MessageGroupId}) which is currently in the process of being retried", message.GroupId); return; } diff --git a/src/ServiceControl/Recoverability/Archiving/UnArchiveAllInGroupHandler.cs b/src/ServiceControl/Recoverability/Archiving/UnArchiveAllInGroupHandler.cs index 82078c1e00..fd853f5f65 100644 --- a/src/ServiceControl/Recoverability/Archiving/UnArchiveAllInGroupHandler.cs +++ b/src/ServiceControl/Recoverability/Archiving/UnArchiveAllInGroupHandler.cs @@ -18,7 +18,7 @@ public async Task Handle(UnarchiveAllInGroup message, IMessageHandlerContext con { if (retryingManager.IsRetryInProgressFor(message.GroupId)) { - logger.LogWarning("Attempt to unarchive a group ({messageGroupId}) which is currently in the process of being retried", message.GroupId); + logger.LogWarning("Attempt to unarchive a group ({MessageGroupId}) which is currently in the process of being retried", message.GroupId); return; } diff --git a/src/ServiceControl/Recoverability/Editing/EditHandler.cs b/src/ServiceControl/Recoverability/Editing/EditHandler.cs index 8a0c97caae..86d01b7454 100644 --- a/src/ServiceControl/Recoverability/Editing/EditHandler.cs +++ b/src/ServiceControl/Recoverability/Editing/EditHandler.cs @@ -34,7 +34,7 @@ public async Task Handle(EditAndSend message, IMessageHandlerContext context) if (failedMessage == null) { - logger.LogWarning("Discarding edit {messageId} because no message failure for id {failedMessageId} has been found", context.MessageId, message.FailedMessageId); + logger.LogWarning("Discarding edit {MessageId} because no message failure for id {FailedMessageId} has been found", context.MessageId, message.FailedMessageId); return; } @@ -43,7 +43,7 @@ public async Task Handle(EditAndSend message, IMessageHandlerContext context) { if (failedMessage.Status != FailedMessageStatus.Unresolved) { - logger.LogWarning("Discarding edit {messageId} because message failure {failedMessageId} doesn't have state 'Unresolved'", context.MessageId, message.FailedMessageId); + logger.LogWarning("Discarding edit {MessageId} because message failure {FailedMessageId} doesn't have state 'Unresolved'", context.MessageId, message.FailedMessageId); return; } @@ -52,7 +52,7 @@ public async Task Handle(EditAndSend message, IMessageHandlerContext context) } else if (editId != context.MessageId) { - logger.LogWarning("Discarding edit & retry request because the failed message id {failedMessageId} has already been edited by Message ID {editedMessageId}", message.FailedMessageId, editId); + logger.LogWarning("Discarding edit & retry request because the failed message id {FailedMessageId} has already been edited by Message ID {EditedMessageId}", message.FailedMessageId, editId); return; } diff --git a/src/ServiceControl/Recoverability/Retrying/CorruptedReplyToHeaderStrategy.cs b/src/ServiceControl/Recoverability/Retrying/CorruptedReplyToHeaderStrategy.cs index f11b61efb7..262b20a38c 100644 --- a/src/ServiceControl/Recoverability/Retrying/CorruptedReplyToHeaderStrategy.cs +++ b/src/ServiceControl/Recoverability/Retrying/CorruptedReplyToHeaderStrategy.cs @@ -36,7 +36,7 @@ public void FixCorruptedReplyToHeader(IDictionary headers) if (machineName == localMachineName && machineName != originatingMachine) { var fixedReplyToAddress = $"{queueName}@{originatingMachine}"; - logger.LogInformation("Detected corrupted ReplyToAddress `{replyToAddress}`. Correcting to `{fixedReplyToAddress}`", replyToAddress, fixedReplyToAddress); + logger.LogInformation("Detected corrupted ReplyToAddress `{ReplyToAddress}`. Correcting to `{FixedReplyToAddress}`", replyToAddress, fixedReplyToAddress); headers["ServiceControl.OldReplyToAddress"] = replyToAddress; headers[Headers.ReplyToAddress] = fixedReplyToAddress; } diff --git a/src/ServiceControl/Recoverability/Retrying/Handlers/RetryAllInGroupHandler.cs b/src/ServiceControl/Recoverability/Retrying/Handlers/RetryAllInGroupHandler.cs index fe3d0b2003..8f17182f23 100644 --- a/src/ServiceControl/Recoverability/Retrying/Handlers/RetryAllInGroupHandler.cs +++ b/src/ServiceControl/Recoverability/Retrying/Handlers/RetryAllInGroupHandler.cs @@ -13,13 +13,13 @@ public async Task Handle(RetryAllInGroup message, IMessageHandlerContext context { if (retries == null) { - logger.LogWarning("Attempt to retry a group ({messageGroupId}) when retries are disabled", message.GroupId); + logger.LogWarning("Attempt to retry a group ({MessageGroupId}) when retries are disabled", message.GroupId); return; } if (archiver.IsArchiveInProgressFor(message.GroupId)) { - logger.LogWarning("Attempt to retry a group ({messageGroupId}) which is currently in the process of being archived", message.GroupId); + logger.LogWarning("Attempt to retry a group ({MessageGroupId}) which is currently in the process of being archived", message.GroupId); return; } diff --git a/src/ServiceControl/Recoverability/Retrying/InMemoryRetry.cs b/src/ServiceControl/Recoverability/Retrying/InMemoryRetry.cs index 980884abd5..81364cd320 100644 --- a/src/ServiceControl/Recoverability/Retrying/InMemoryRetry.cs +++ b/src/ServiceControl/Recoverability/Retrying/InMemoryRetry.cs @@ -178,7 +178,7 @@ await domainEvents.Raise(new MessagesSubmittedForRetry }); } - logger.LogInformation("Retry operation {requestId} completed. {numberOfMessagesSkipped} messages skipped, {numberOfMessagesForwarded} forwarded. Total {totalNumberOfMessages}", + logger.LogInformation("Retry operation {RequestId} completed. {NumberOfMessagesSkipped} messages skipped, {NumberOfMessagesForwarded} forwarded. Total {TotalNumberOfMessages}", RequestId, NumberOfMessagesSkipped, NumberOfMessagesForwarded, diff --git a/src/ServiceControl/Recoverability/Retrying/Infrastructure/ReturnToSender.cs b/src/ServiceControl/Recoverability/Retrying/Infrastructure/ReturnToSender.cs index 04a9163da2..c04662fa12 100644 --- a/src/ServiceControl/Recoverability/Retrying/Infrastructure/ReturnToSender.cs +++ b/src/ServiceControl/Recoverability/Retrying/Infrastructure/ReturnToSender.cs @@ -21,7 +21,7 @@ public virtual async Task HandleMessage(MessageContext message, IMessageDispatch byte[] body = null; var messageId = message.NativeMessageId; - logger.LogDebug("{messageId}: Retrieving message body", messageId); + logger.LogDebug("{MessageId}: Retrieving message body", messageId); if (outgoingHeaders.TryGetValue("ServiceControl.Retry.Attempt.MessageId", out var attemptMessageId)) { @@ -30,14 +30,14 @@ public virtual async Task HandleMessage(MessageContext message, IMessageDispatch } else { - logger.LogWarning("{messageId}: Can't find message body. Missing header ServiceControl.Retry.Attempt.MessageId", messageId); + logger.LogWarning("{MessageId}: Can't find message body. Missing header ServiceControl.Retry.Attempt.MessageId", messageId); } var outgoingMessage = new OutgoingMessage(messageId, outgoingHeaders, body ?? EmptyBody); var destination = outgoingHeaders["ServiceControl.TargetEndpointAddress"]; - logger.LogDebug("{messageId}: Forwarding message to {destination}", messageId, destination); + logger.LogDebug("{MessageId}: Forwarding message to {Destination}", messageId, destination); if (!outgoingHeaders.TryGetValue("ServiceControl.RetryTo", out var retryTo)) { @@ -46,14 +46,14 @@ public virtual async Task HandleMessage(MessageContext message, IMessageDispatch } else { - logger.LogDebug("{messageId}: Found ServiceControl.RetryTo header. Rerouting to {retryTo}", messageId, retryTo); + logger.LogDebug("{MessageId}: Found ServiceControl.RetryTo header. Rerouting to {RetryTo}", messageId, retryTo); } var transportOp = new TransportOperation(outgoingMessage, new UnicastAddressTag(retryTo)); await sender.Dispatch(new TransportOperations(transportOp), message.TransportTransaction, cancellationToken); - logger.LogDebug("{messageId}: Forwarded message to {retryTo}", messageId, retryTo); + logger.LogDebug("{MessageId}: Forwarded message to {RetryTo}", messageId, retryTo); } async Task FetchFromFailedMessage(Dictionary outgoingHeaders, string messageId, string attemptMessageId) @@ -63,11 +63,11 @@ async Task FetchFromFailedMessage(Dictionary outgoingHea if (body == null) { - logger.LogWarning("{messageId}: Message Body not found in failed message with unique id {uniqueMessageId} for attempt Id {attemptMessageId}", messageId, uniqueMessageId, attemptMessageId); + logger.LogWarning("{MessageId}: Message Body not found in failed message with unique id {UniqueMessageId} for attempt Id {AttemptMessageId}", messageId, uniqueMessageId, attemptMessageId); } else { - logger.LogDebug("{messageId}: Body size: {messageLength} bytes retrieved from failed message attachment", messageId, body.LongLength); + logger.LogDebug("{MessageId}: Body size: {MessageLength} bytes retrieved from failed message attachment", messageId, body.LongLength); } return body; diff --git a/src/ServiceControl/Recoverability/Retrying/Infrastructure/ReturnToSenderDequeuer.cs b/src/ServiceControl/Recoverability/Retrying/Infrastructure/ReturnToSenderDequeuer.cs index fcbd9b9ced..7bade70a97 100644 --- a/src/ServiceControl/Recoverability/Retrying/Infrastructure/ReturnToSenderDequeuer.cs +++ b/src/ServiceControl/Recoverability/Retrying/Infrastructure/ReturnToSenderDequeuer.cs @@ -61,7 +61,7 @@ public async Task StopAsync(CancellationToken cancellationToken) async Task Handle(MessageContext message, CancellationToken cancellationToken) { var stagingId = message.Headers["ServiceControl.Retry.StagingId"]; - logger.LogDebug("Handling message with id {nativeMessageId} and staging id {stagingId} in input queue {inputAddress}", message.NativeMessageId, stagingId, InputAddress); + logger.LogDebug("Handling message with id {NativeMessageId} and staging id {StagingId} in input queue {InputAddress}", message.NativeMessageId, stagingId, InputAddress); if (shouldProcess(message)) { @@ -70,7 +70,7 @@ async Task Handle(MessageContext message, CancellationToken cancellationToken) } else { - logger.LogWarning("Rejecting message from staging queue as it's not part of a fully staged batch: {nativeMessageId}", message.NativeMessageId); + logger.LogWarning("Rejecting message from staging queue as it's not part of a fully staged batch: {NativeMessageId}", message.NativeMessageId); } } @@ -92,7 +92,7 @@ void CountMessageAndStopIfReachedTarget() { var currentMessageCount = Interlocked.Increment(ref actualMessageCount); - logger.LogDebug("Forwarding message {currentMessageCount} of {targetMessageCount}", currentMessageCount, targetMessageCount); + logger.LogDebug("Forwarding message {CurrentMessageCount} of {TargetMessageCount}", currentMessageCount, targetMessageCount); if (currentMessageCount >= targetMessageCount.GetValueOrDefault()) { @@ -120,7 +120,7 @@ public virtual async Task Run(string forwardingBatchId, Predicate OnError(ErrorContext errorContext, Cancella var message = errorContext.Message; var destination = message.Headers["ServiceControl.TargetEndpointAddress"]; var messageUniqueId = message.Headers["ServiceControl.Retry.UniqueMessageId"]; - logger.LogWarning(errorContext.Exception, "Failed to send '{messageUniqueId}' message to '{destination}' for retry. Attempting to revert message status to unresolved so it can be tried again", messageUniqueId, destination); + logger.LogWarning(errorContext.Exception, "Failed to send '{UniqueMessageId}' message to '{Destination}' for retry. Attempting to revert message status to unresolved so it can be tried again", messageUniqueId, destination); await dataStore.RevertRetry(messageUniqueId); diff --git a/src/ServiceControl/Recoverability/Retrying/RetriesGateway.cs b/src/ServiceControl/Recoverability/Retrying/RetriesGateway.cs index f2de937d36..7c1f8941a7 100644 --- a/src/ServiceControl/Recoverability/Retrying/RetriesGateway.cs +++ b/src/ServiceControl/Recoverability/Retrying/RetriesGateway.cs @@ -21,7 +21,7 @@ public RetriesGateway(IRetryDocumentDataStore store, RetryingManager operationMa public async Task StartRetryForSingleMessage(string uniqueMessageId) { - logger.LogInformation("Retrying a single message {uniqueMessageId}", uniqueMessageId); + logger.LogInformation("Retrying a single message {UniqueMessageId}", uniqueMessageId); var requestId = uniqueMessageId; var retryType = RetryType.SingleMessage; @@ -34,7 +34,7 @@ public async Task StartRetryForSingleMessage(string uniqueMessageId) public async Task StartRetryForMessageSelection(string[] uniqueMessageIds) { - logger.LogInformation("Retrying a selection of {messageCount} messages", uniqueMessageIds.Length); + logger.LogInformation("Retrying a selection of {MessageCount} messages", uniqueMessageIds.Length); var requestId = DeterministicGuid.MakeId(string.Join(string.Empty, uniqueMessageIds)).ToString(); var retryType = RetryType.MultipleMessages; @@ -49,7 +49,7 @@ async Task StageRetryByUniqueMessageIds(string requestId, RetryType retryType, s { if (messageIds == null || !messageIds.Any()) { - logger.LogInformation("Batch '{batchName}' contains no messages", batchName); + logger.LogInformation("Batch '{BatchName}' contains no messages", batchName); return; } @@ -57,13 +57,13 @@ async Task StageRetryByUniqueMessageIds(string requestId, RetryType retryType, s var batchDocumentId = await store.CreateBatchDocument(RetryDocumentManager.RetrySessionId, requestId, retryType, failedMessageRetryIds, originator, startTime, last, batchName, classifier); - logger.LogInformation("Created Batch '{batchDocumentId}' with {batchMessageCount} messages for '{batchName}'.", batchDocumentId, messageIds.Length, batchName); + logger.LogInformation("Created Batch '{BatchDocumentId}' with {BatchMessageCount} messages for '{BatchName}'", batchDocumentId, messageIds.Length, batchName); await store.StageRetryByUniqueMessageIds(batchDocumentId, messageIds); await MoveBatchToStaging(batchDocumentId); - logger.LogInformation("Moved Batch '{batchDocumentId}' to Staging", batchDocumentId); + logger.LogInformation("Moved Batch '{BatchDocumentId}' to Staging", batchDocumentId); } // Needs to be overridable by a test @@ -115,27 +115,27 @@ static string GetBatchName(int pageNum, int totalPages, string context) public void StartRetryForAllMessages() { var item = new RetryForAllMessages(); - logger.LogInformation("Enqueuing index based bulk retry '{item}'", item); + logger.LogInformation("Enqueuing index based bulk retry '{Item}'", item); bulkRequests.Enqueue(item); } public void StartRetryForEndpoint(string endpoint) { var item = new RetryForEndpoint(endpoint); - logger.LogInformation("Enqueuing index based bulk retry '{item}'", item); + logger.LogInformation("Enqueuing index based bulk retry '{Item}'", item); bulkRequests.Enqueue(item); } public void StartRetryForFailedQueueAddress(string failedQueueAddress, FailedMessageStatus status) { var item = new RetryForFailedQueueAddress(failedQueueAddress, status); - logger.LogInformation("Enqueuing index based bulk retry '{item}'", item); + logger.LogInformation("Enqueuing index based bulk retry '{Item}'", item); bulkRequests.Enqueue(item); } public void EnqueueRetryForFailureGroup(RetryForFailureGroup item) { - logger.LogInformation("Enqueuing index based bulk retry '{item}'", item); + logger.LogInformation("Enqueuing index based bulk retry '{Item}'", item); bulkRequests.Enqueue(item); } diff --git a/src/ServiceControl/Recoverability/Retrying/RetryDocumentManager.cs b/src/ServiceControl/Recoverability/Retrying/RetryDocumentManager.cs index 165c71f369..d7afc3e6c9 100644 --- a/src/ServiceControl/Recoverability/Retrying/RetryDocumentManager.cs +++ b/src/ServiceControl/Recoverability/Retrying/RetryDocumentManager.cs @@ -21,12 +21,12 @@ public async Task AdoptOrphanedBatches() { var orphanedBatches = await store.QueryOrphanedBatches(RetrySessionId); - logger.LogInformation("Found {orphanedBatchCount} orphaned retry batches from previous sessions", orphanedBatches.Results.Count); + logger.LogInformation("Found {OrphanedBatchCount} orphaned retry batches from previous sessions", orphanedBatches.Results.Count); // let's leave Task.Run for now due to sync sends await Task.WhenAll(orphanedBatches.Results.Select(b => Task.Run(async () => { - logger.LogInformation("Adopting retry batch {b.Id} with {b.FailureRetries.Count} messages", b.Id, b.FailureRetries.Count); + logger.LogInformation("Adopting retry batch {BatchId} with {BatchMessageCount} messages", b.Id, b.FailureRetries.Count); await MoveBatchToStaging(b.Id); }))); @@ -56,7 +56,7 @@ public async Task RebuildRetryOperationState() { if (!string.IsNullOrWhiteSpace(group.RequestId)) { - logger.LogDebug("Rebuilt retry operation status for {retryType}/{retryRequestId}. Aggregated batchsize: {retryBatchSize}", group.RetryType, group.RequestId, group.InitialBatchSize); + logger.LogDebug("Rebuilt retry operation status for {RetryType}/{RetryRequestId}. Aggregated batchsize: {RetryBatchSize}", group.RetryType, group.RequestId, group.InitialBatchSize); await operationManager.PreparedAdoptedBatch(group.RequestId, group.RetryType, group.InitialBatchSize, group.InitialBatchSize, group.Originator, group.Classifier, group.StartTime, group.Last); } diff --git a/src/ServiceControl/Recoverability/Retrying/RetryProcessor.cs b/src/ServiceControl/Recoverability/Retrying/RetryProcessor.cs index 6ee73cdadb..dbdeab6477 100644 --- a/src/ServiceControl/Recoverability/Retrying/RetryProcessor.cs +++ b/src/ServiceControl/Recoverability/Retrying/RetryProcessor.cs @@ -62,7 +62,7 @@ async Task MoveStagedBatchesToForwardingBatch(IRetryBatchesManager manager if (stagingBatch != null) { - logger.LogInformation("Staging batch {stagingBatchId}", stagingBatch.Id); + logger.LogInformation("Staging batch {StagingBatchId}", stagingBatch.Id); redirects = await manager.GetOrCreateMessageRedirectsCollection(); var stagedMessages = await Stage(stagingBatch, manager); var skippedMessages = stagingBatch.InitialBatchSize - stagedMessages; @@ -70,7 +70,7 @@ async Task MoveStagedBatchesToForwardingBatch(IRetryBatchesManager manager if (stagedMessages > 0) { - logger.LogInformation("Batch {stagingBatchId} with {stagedMessages} messages staged and {skippedMessages} skipped ready to be forwarded", stagingBatch.Id, stagedMessages, skippedMessages); + logger.LogInformation("Batch {StagingBatchId} with {StagedMessages} messages staged and {SkippedMessages} skipped ready to be forwarded", stagingBatch.Id, stagedMessages, skippedMessages); await manager.Store(new RetryBatchNowForwarding { RetryBatchId = stagingBatch.Id @@ -97,21 +97,21 @@ async Task ForwardCurrentBatch(IRetryBatchesManager manager, CancellationT if (nowForwarding != null) { - logger.LogDebug("Loading batch {retryBatchId} for forwarding", nowForwarding.RetryBatchId); + logger.LogDebug("Loading batch {RetryBatchId} for forwarding", nowForwarding.RetryBatchId); var forwardingBatch = await manager.GetRetryBatch(nowForwarding.RetryBatchId, cancellationToken); if (forwardingBatch != null) { - logger.LogInformation("Forwarding batch {retryBatchId}", forwardingBatch.Id); + logger.LogInformation("Forwarding batch {RetryBatchId}", forwardingBatch.Id); await Forward(forwardingBatch, manager, cancellationToken); - logger.LogDebug("Retry batch {retryBatchId} forwarded", forwardingBatch.Id); + logger.LogDebug("Retry batch {RetryBatchId} forwarded", forwardingBatch.Id); } else { - logger.LogWarning("Could not find retry batch {retryBatchId} to forward", nowForwarding.RetryBatchId); + logger.LogWarning("Could not find retry batch {RetryBatchId} to forward", nowForwarding.RetryBatchId); } logger.LogDebug("Removing forwarding document"); @@ -132,7 +132,7 @@ async Task Forward(RetryBatch forwardingBatch, IRetryBatchesManager manager, Can if (isRecoveringFromPrematureShutdown) { - logger.LogWarning("Recovering from premature shutdown. Starting forwarder for batch {forwardingBatchId} in timeout mode", forwardingBatch.Id); + logger.LogWarning("Recovering from premature shutdown. Starting forwarder for batch {ForwardingBatchId} in timeout mode", forwardingBatch.Id); await returnToSender.Run(forwardingBatch.Id, IsPartOfStagedBatch(forwardingBatch.StagingId), null, cancellationToken); await retryingManager.ForwardedBatch(forwardingBatch.RequestId, forwardingBatch.RetryType, forwardingBatch.InitialBatchSize); } @@ -140,11 +140,11 @@ async Task Forward(RetryBatch forwardingBatch, IRetryBatchesManager manager, Can { if (messageCount == 0) { - logger.LogInformation("Skipping forwarding of batch {forwardingBatchId}: no messages to forward", forwardingBatch.Id); + logger.LogInformation("Skipping forwarding of batch {ForwardingBatchId}: no messages to forward", forwardingBatch.Id); } else { - logger.LogInformation("Starting forwarder for batch {forwardingBatchId} with {messageCount} messages in counting mode", forwardingBatch.Id, messageCount); + logger.LogInformation("Starting forwarder for batch {ForwardingBatchId} with {BatchMessageCount} messages in counting mode", forwardingBatch.Id, messageCount); await returnToSender.Run(forwardingBatch.Id, IsPartOfStagedBatch(forwardingBatch.StagingId), messageCount, cancellationToken); } @@ -153,7 +153,7 @@ async Task Forward(RetryBatch forwardingBatch, IRetryBatchesManager manager, Can manager.Delete(forwardingBatch); - logger.LogInformation("Done forwarding batch {forwardingBatchId}", forwardingBatch.Id); + logger.LogInformation("Done forwarding batch {ForwardingBatchId}", forwardingBatch.Id); } static Predicate IsPartOfStagedBatch(string stagingId) @@ -186,7 +186,7 @@ async Task Stage(RetryBatch stagingBatch, IRetryBatchesManager manager) if (failedMessageRetriesById.Count == 0) { - logger.LogInformation("Retry batch {retryBatchId} cancelled as all matching unresolved messages are already marked for retry as part of another batch", stagingBatch.Id); + logger.LogInformation("Retry batch {RetryBatchId} cancelled as all matching unresolved messages are already marked for retry as part of another batch", stagingBatch.Id); manager.Delete(stagingBatch); return 0; } @@ -194,7 +194,7 @@ async Task Stage(RetryBatch stagingBatch, IRetryBatchesManager manager) var failedMessagesDocs = await manager.GetFailedMessages(failedMessageRetriesById.Keys); var messages = failedMessagesDocs.Where(m => m != null).ToArray(); - logger.LogInformation("Staging {messageCount} messages for retry batch {retryBatchId} with staging attempt Id {stagingId}", messages.Length, stagingBatch.Id, stagingId); + logger.LogInformation("Staging {MessageCount} messages for retry batch {RetryBatchId} with staging attempt Id {StagingId}", messages.Length, stagingBatch.Id, stagingId); var previousAttemptFailed = false; var transportOperations = new TransportOperation[messages.Length]; @@ -231,7 +231,7 @@ await domainEvents.Raise(new MessagesSubmittedForRetry stagingBatch.Status = RetryBatchStatus.Forwarding; stagingBatch.StagingId = stagingId; stagingBatch.FailureRetries = failedMessageRetriesById.Values.Where(x => msgLookup[x.FailedMessageId].Any()).Select(x => x.Id).ToArray(); - logger.LogInformation("Retry batch {retryBatchId} staged with Staging Id {stagingId} and {retryFailureCount} matching failure retries", stagingBatch.Id, stagingBatch.StagingId, stagingBatch.FailureRetries.Count); + logger.LogInformation("Retry batch {RetryBatchId} staged with Staging Id {StagingId} and {RetryFailureCount} matching failure retries", stagingBatch.Id, stagingBatch.StagingId, stagingBatch.FailureRetries.Count); return messages.Length; } @@ -281,13 +281,13 @@ async Task TryStageMessage(TransportOperation transportOperation, FailedMessageR if (incrementedAttempts < MaxStagingAttempts) { - logger.LogWarning(e, "Attempt {stagingRetryAttempt} of {stagingRetryLimit} to stage a retry message {retryMessageId} failed", incrementedAttempts, MaxStagingAttempts, uniqueMessageId); + logger.LogWarning(e, "Attempt {StagingRetryAttempt} of {StagingRetryLimit} to stage a retry message {RetryMessageId} failed", incrementedAttempts, MaxStagingAttempts, uniqueMessageId); await store.IncrementAttemptCounter(failedMessageRetry); } else { - logger.LogError(e, "Retry message {retryMessageId} reached its staging retry limit ({stagingRetryLimit}) and is going to be removed from the batch", uniqueMessageId, MaxStagingAttempts); + logger.LogError(e, "Retry message {RetryMessageId} reached its staging retry limit ({StagingRetryLimit}) and is going to be removed from the batch", uniqueMessageId, MaxStagingAttempts); await store.DeleteFailedMessageRetry(uniqueMessageId); diff --git a/src/ServiceControl/SagaAudit/SagaUpdatedHandler.cs b/src/ServiceControl/SagaAudit/SagaUpdatedHandler.cs index f67f95002a..9baface096 100644 --- a/src/ServiceControl/SagaAudit/SagaUpdatedHandler.cs +++ b/src/ServiceControl/SagaAudit/SagaUpdatedHandler.cs @@ -29,7 +29,7 @@ public async Task Handle(SagaUpdatedMessage message, IMessageHandlerContext cont var endpointName = context.MessageHeaders.TryGetValue(Headers.ReplyToAddress, out var val) ? val : "(Unknown Endpoint)"; logger.LogError("Received a saga audit message in the ServiceControl queue that should have been sent to the audit queue. " + - "This indicates that the endpoint '{endpointName}' using the SagaAudit plugin is misconfigured and should be changed to use the system's audit queue instead. " + + "This indicates that the endpoint '{EndpointName}' using the SagaAudit plugin is misconfigured and should be changed to use the system's audit queue instead. " + "The message has been forwarded to the audit queue, but this may not be possible in a future version of ServiceControl.", endpointName); await context.ForwardCurrentMessageTo(auditQueueName); } @@ -57,12 +57,12 @@ async Task RefreshAuditQueue() // Pick any audit queue, assume all instance are based on competing consumer auditQueueName = sagaAudit.GetProperty("SagaAuditQueue").GetString(); nextAuditQueueNameRefresh = DateTime.UtcNow.AddMinutes(5); - logger.LogInformation("Refreshed audit queue name '{auditQueueName}' from ServiceControl Audit instance. Will continue to use this value for forwarding saga update messages for the next 5 minutes.", auditQueueName); + logger.LogInformation("Refreshed audit queue name '{AuditQueueName}' from ServiceControl Audit instance. Will continue to use this value for forwarding saga update messages for the next 5 minutes.", auditQueueName); } } catch (Exception x) { - logger.LogWarning("Unable to refresh audit queue name from ServiceControl Audit instance. Will continue to check at most every 15 seconds. Exception message: {exceptionMessage}", x.Message); + logger.LogWarning("Unable to refresh audit queue name from ServiceControl Audit instance. Will continue to check at most every 15 seconds. Exception message: {ExceptionMessage}", x.Message); nextAuditQueueNameRefresh = DateTime.UtcNow.AddSeconds(15); } finally From 5ace667954eb3951f23a3d8dccc9ad8966556b07 Mon Sep 17 00:00:00 2001 From: Andreas Bednarz Date: Tue, 17 Jun 2025 14:15:21 +1000 Subject: [PATCH 5/5] Remove unnecessary fields --- .../CompositeViews/Messages/GetMessagesController.cs | 2 -- src/ServiceControl/Licensing/ActiveLicense.cs | 2 -- .../MessageFailures/Api/EditFailedMessagesController.cs | 2 -- .../Recoverability/Retrying/Infrastructure/ReturnToSender.cs | 1 - src/ServiceControl/SagaAudit/SagaUpdatedHandler.cs | 1 - 5 files changed, 8 deletions(-) diff --git a/src/ServiceControl/CompositeViews/Messages/GetMessagesController.cs b/src/ServiceControl/CompositeViews/Messages/GetMessagesController.cs index d29837891a..e7133ba20a 100644 --- a/src/ServiceControl/CompositeViews/Messages/GetMessagesController.cs +++ b/src/ServiceControl/CompositeViews/Messages/GetMessagesController.cs @@ -162,7 +162,5 @@ public async Task> SearchByKeyword([FromQuery] PagingInfo pa Response.WithQueryStatsAndPagingInfo(result.QueryStats, pagingInfo); return result.Results; } - - readonly ILogger logger = logger; } } \ No newline at end of file diff --git a/src/ServiceControl/Licensing/ActiveLicense.cs b/src/ServiceControl/Licensing/ActiveLicense.cs index 6dff02574f..eed4880136 100644 --- a/src/ServiceControl/Licensing/ActiveLicense.cs +++ b/src/ServiceControl/Licensing/ActiveLicense.cs @@ -58,7 +58,5 @@ internal static async Task ValidateTrialLicense(LicenseDetails l return licenseDetails; } static readonly int MaxTrialPeriodInDays = 14; - - readonly ILogger logger = logger; } } \ No newline at end of file diff --git a/src/ServiceControl/MessageFailures/Api/EditFailedMessagesController.cs b/src/ServiceControl/MessageFailures/Api/EditFailedMessagesController.cs index 6b37009982..9c0413cbac 100644 --- a/src/ServiceControl/MessageFailures/Api/EditFailedMessagesController.cs +++ b/src/ServiceControl/MessageFailures/Api/EditFailedMessagesController.cs @@ -122,8 +122,6 @@ EditConfigurationModel GetEditConfiguration() => "Header" } }; - - readonly ILogger logger = logger; } public class EditConfigurationModel diff --git a/src/ServiceControl/Recoverability/Retrying/Infrastructure/ReturnToSender.cs b/src/ServiceControl/Recoverability/Retrying/Infrastructure/ReturnToSender.cs index c04662fa12..3b27006b4b 100644 --- a/src/ServiceControl/Recoverability/Retrying/Infrastructure/ReturnToSender.cs +++ b/src/ServiceControl/Recoverability/Retrying/Infrastructure/ReturnToSender.cs @@ -74,6 +74,5 @@ async Task FetchFromFailedMessage(Dictionary outgoingHea } static readonly byte[] EmptyBody = Array.Empty(); - readonly ILogger logger = logger; } } diff --git a/src/ServiceControl/SagaAudit/SagaUpdatedHandler.cs b/src/ServiceControl/SagaAudit/SagaUpdatedHandler.cs index 9baface096..47a7ba3b8e 100644 --- a/src/ServiceControl/SagaAudit/SagaUpdatedHandler.cs +++ b/src/ServiceControl/SagaAudit/SagaUpdatedHandler.cs @@ -74,6 +74,5 @@ async Task RefreshAuditQueue() static string auditQueueName; static DateTime nextAuditQueueNameRefresh; static readonly SemaphoreSlim semaphore = new(1); - readonly ILogger logger = logger; } }