From 05e817af36f6f6bf78e9b31d700afaa392732e51 Mon Sep 17 00:00:00 2001 From: Timo Notheisen Date: Tue, 10 Oct 2023 16:00:06 +0200 Subject: [PATCH 001/133] chore: update readme with TODO --- README.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/README.md b/README.md index 2c5a764d32..0f9f6b8f24 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,12 @@ Share your feedback with the Enmeshed team by contributing to the [discussions]( Contribution to this project is highly appreciated. Head over to our [contribution guide](https://github.com/nmshd/.github/blob/main/CONTRIBUTING.md) to learn more. +## Development + +### Logging + +TODO: describe how to generate event ids (min: 100,000, max: 999,999) + ## License [MIT](LICENSE) From 00caaf5877ff7c9aaa21d45d41bea54453f14410 Mon Sep 17 00:00:00 2001 From: Timo Notheisen Date: Tue, 10 Oct 2023 16:00:34 +0200 Subject: [PATCH 002/133] feat: add examples --- .../Database/SaveChangesTimeInterceptor.cs | 21 +++++++++++-- .../Tooling/Extensions/ILoggerExtensions.cs | 19 ++++++++++-- .../src/Tooling/Extensions/LogEventIds.cs | 2 +- .../DeleteExpiredChallenges/Handler.cs | 31 +++++++++++++++++-- 4 files changed, 65 insertions(+), 8 deletions(-) diff --git a/BuildingBlocks/src/BuildingBlocks.Infrastructure/Persistence/Database/SaveChangesTimeInterceptor.cs b/BuildingBlocks/src/BuildingBlocks.Infrastructure/Persistence/Database/SaveChangesTimeInterceptor.cs index aa840ae645..7e860b8d1b 100644 --- a/BuildingBlocks/src/BuildingBlocks.Infrastructure/Persistence/Database/SaveChangesTimeInterceptor.cs +++ b/BuildingBlocks/src/BuildingBlocks.Infrastructure/Persistence/Database/SaveChangesTimeInterceptor.cs @@ -8,7 +8,7 @@ namespace Enmeshed.BuildingBlocks.Infrastructure.Persistence.Database; public class SaveChangesTimeInterceptor : SaveChangesInterceptor { private readonly ILogger _logger; - private Stopwatch _stopwatch; + private Stopwatch? _stopwatch; public SaveChangesTimeInterceptor(ILogger logger) { @@ -29,8 +29,23 @@ public override async ValueTask SavedChangesAsync( int result, CancellationToken cancellationToken = default) { - _stopwatch.Stop(); - _logger.LogDebug(LogEventIds.EXECUTION_TIME, "Executed '{action}' in {elapsedMilliseconds}ms.", "SaveChangesAsync", _stopwatch.ElapsedMilliseconds); + _stopwatch!.Stop(); + _logger.ExecutedAction("SaveChangesAsync", _stopwatch.ElapsedMilliseconds); return await base.SavedChangesAsync(eventData, result, cancellationToken); } } + +file static class Logs +{ + private static readonly Action EXECUTED_ACTION = + LoggerMessage.Define( + LogLevel.Debug, + LogEventIds.EXECUTION_TIME, + "Executed '{action}' in {elapsedMilliseconds}ms." + ); + + public static void ExecutedAction(this ILogger logger, string actionName, long elapsedMilliseconds) + { + EXECUTED_ACTION(logger, actionName, elapsedMilliseconds, default!); + } +} diff --git a/BuildingBlocks/src/Tooling/Extensions/ILoggerExtensions.cs b/BuildingBlocks/src/Tooling/Extensions/ILoggerExtensions.cs index dc474094c8..2e25653e98 100644 --- a/BuildingBlocks/src/Tooling/Extensions/ILoggerExtensions.cs +++ b/BuildingBlocks/src/Tooling/Extensions/ILoggerExtensions.cs @@ -22,7 +22,7 @@ public static async Task TraceTime(this ILogger logger, Func action, strin finally { watch.Stop(); - logger.LogDebug(LogEventIds.EXECUTION_TIME, "Executed '{action}' in {elapsedMilliseconds}ms.", actionName ?? "Action", watch.ElapsedMilliseconds); + logger.ExecutedAction(actionName ?? "Action", watch.ElapsedMilliseconds); } } @@ -39,7 +39,22 @@ public static async Task TraceTime(this ILogger logger, Func> acti finally { watch.Stop(); - logger.LogDebug(LogEventIds.EXECUTION_TIME, "Executed '{action}' in {elapsedMilliseconds}ms.", actionName ?? "Action", watch.ElapsedMilliseconds); + logger.ExecutedAction(actionName ?? "Action", watch.ElapsedMilliseconds); } } } + +file static class Logs +{ + private static readonly Action EXECUTED_ACTION = + LoggerMessage.Define( + LogLevel.Debug, + LogEventIds.EXECUTION_TIME, + "Executed '{action}' in {elapsedMilliseconds}ms." + ); + + public static void ExecutedAction(this ILogger logger, string actionName, long elapsedMilliseconds) + { + EXECUTED_ACTION(logger, actionName, elapsedMilliseconds, default!); + } +} diff --git a/BuildingBlocks/src/Tooling/Extensions/LogEventIds.cs b/BuildingBlocks/src/Tooling/Extensions/LogEventIds.cs index 8888549692..ccdc6cb3a4 100644 --- a/BuildingBlocks/src/Tooling/Extensions/LogEventIds.cs +++ b/BuildingBlocks/src/Tooling/Extensions/LogEventIds.cs @@ -3,5 +3,5 @@ namespace Enmeshed.Tooling.Extensions; public static class LogEventIds { - public static readonly EventId EXECUTION_TIME = new(1000, "ExecutionTime"); + public static readonly EventId EXECUTION_TIME = new(293800, "ExecutionTime"); } diff --git a/Modules/Challenges/src/Challenges.Application/Challenges/Commands/DeleteExpiredChallenges/Handler.cs b/Modules/Challenges/src/Challenges.Application/Challenges/Commands/DeleteExpiredChallenges/Handler.cs index 78ac39b0a0..df2105e48c 100644 --- a/Modules/Challenges/src/Challenges.Application/Challenges/Commands/DeleteExpiredChallenges/Handler.cs +++ b/Modules/Challenges/src/Challenges.Application/Challenges/Commands/DeleteExpiredChallenges/Handler.cs @@ -19,16 +19,43 @@ public async Task Handle(DeleteExpiredChallenge { if (cancellationToken.IsCancellationRequested) { - _logger.LogWarning("Cancellation was request. Stopping execution..."); + _logger.CancellationRequested(); return DeleteExpiredChallengesResponse.NoDeletedChallenges(); } var deletedChallengesCount = await _challengesRepository.DeleteExpiredChallenges(cancellationToken); - _logger.LogInformation("Deletion of '{deletedChallengesCount}' challenges successful.", deletedChallengesCount); + _logger.DeletionSuccessful(deletedChallengesCount); var response = new DeleteExpiredChallengesResponse(deletedChallengesCount); return response; } } + +file static class LoggerExtensions +{ + private static readonly Action CANCELLATION_REQUESTED = + LoggerMessage.Define( + LogLevel.Debug, + new EventId(599235, "Enmeshed.Challenges.Application.DeleteExpiredChallenges.Handler.CancellationRequested"), + "Cancellation was requested. Stopping execution..." + ); + + private static readonly Action DELETION_SUCCESSFUL = + LoggerMessage.Define( + LogLevel.Debug, + new EventId(916630, ".DeleteExpiredChallenges.Handler.DeletionSuccessful"), + "Deletion of '{deletedChallengesCount}' challenges successful." + ); + + public static void CancellationRequested(this ILogger logger) + { + CANCELLATION_REQUESTED(logger, default!); + } + + public static void DeletionSuccessful(this ILogger logger, int numberOfDeletedChallenges) + { + DELETION_SUCCESSFUL(logger, numberOfDeletedChallenges, default!); + } +} From 7612dab0d9f68edaabd5856269212c8869940199 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Wed, 11 Oct 2023 10:49:30 +0200 Subject: [PATCH 003/133] feat: introduced log event ids chore: fixed minor typos in log statement messages --- .../ExceptionFilters/CustomExceptionFilter.cs | 87 ++++++++++++++++--- 1 file changed, 77 insertions(+), 10 deletions(-) diff --git a/BuildingBlocks/src/BuildingBlocks.API/Mvc/ExceptionFilters/CustomExceptionFilter.cs b/BuildingBlocks/src/BuildingBlocks.API/Mvc/ExceptionFilters/CustomExceptionFilter.cs index 14df253a2e..eed89540a3 100644 --- a/BuildingBlocks/src/BuildingBlocks.API/Mvc/ExceptionFilters/CustomExceptionFilter.cs +++ b/BuildingBlocks/src/BuildingBlocks.API/Mvc/ExceptionFilters/CustomExceptionFilter.cs @@ -41,8 +41,8 @@ public override void OnException(ExceptionContext context) switch (context.Exception) { case InfrastructureException infrastructureException: - _logger.LogInformation( - "An '{exception}' occurred. Error Code: '{code}'. Error message: '{message}'", nameof(InfrastructureException), infrastructureException.Code, infrastructureException.Message); + _logger.InfrastructureException( + infrastructureException, infrastructureException.Code, infrastructureException.Message); httpError = CreateHttpErrorForInfrastructureException(infrastructureException); @@ -51,8 +51,8 @@ public override void OnException(ExceptionContext context) break; case ApplicationException applicationException: - _logger.LogInformation( - "An '{exception}' occurred. Error Code: '{code}'. Error message: '{message}'", nameof(ApplicationException), applicationException.Code, applicationException.Message); + _logger.ApplicationException( + applicationException, applicationException.Code, applicationException.Message); httpError = CreateHttpErrorForApplicationException(applicationException); @@ -60,9 +60,9 @@ public override void OnException(ExceptionContext context) (int)GetStatusCodeForApplicationException(applicationException); break; + case DomainException domainException: - _logger.LogInformation( - "A '{exception}' occurred. Error Code: '{code}'. Error message: '{message}'", nameof(DomainException), domainException.Code, domainException.Message); + _logger.DomainException(domainException, domainException.Code, domainException.Message); httpError = CreateHttpErrorForDomainException(domainException); @@ -70,8 +70,7 @@ public override void OnException(ExceptionContext context) break; case BadHttpRequestException _: - _logger.LogInformation( - "'{error_code}': The body of the request is too large.", ERROR_CODE_REQUEST_BODY_TOO_LARGE); + _logger.RequestBodyTooLarge(ERROR_CODE_REQUEST_BODY_TOO_LARGE); httpError = HttpError.ForProduction( ERROR_CODE_REQUEST_BODY_TOO_LARGE, @@ -83,8 +82,7 @@ public override void OnException(ExceptionContext context) break; default: - _logger.LogError(context.Exception, - "Unexpected Error while processing request to '{uri}'", context.HttpContext.Request.GetUri()); + _logger.ErrorWhileProcessingRequestToUri(context.HttpContext.Request.GetUri(), context.Exception); httpError = CreateHttpErrorForUnexpectedException(context); @@ -218,3 +216,72 @@ private IEnumerable GetFormattedStackTrace(Exception exception) Regex.Matches(exception.StackTrace, "at .+").Select(m => m.Value.Trim()); } } + +file static class LoggerExtensions +{ + private static readonly Action INFRASTRUCTURE_EXCEPTION = + LoggerMessage.Define( + LogLevel.Information, + new EventId(560507, "ExceptionFilter.InfrastructureException"), + "An '{exception}' occurred. Error Code: '{code}'. Error message: '{message}'." + ); + + private static readonly Action APPLICATION_EXCEPTION = + LoggerMessage.Define( + LogLevel.Information, + new EventId(437832, "ExceptionFilter.ApplicationException"), + "An '{exception}' occurred. Error Code: '{code}'. Error message: '{message}'." + ); + + private static readonly Action DOMAIN_EXCEPTION = + LoggerMessage.Define( + LogLevel.Information, + new EventId(505278, "ExceptionFilter.DomainException"), + "An '{exception}' occurred. Error Code: '{code}'. Error message: '{message}'." + ); + + private static readonly Action REQUEST_BODY_TOO_LARGE = + LoggerMessage.Define( + LogLevel.Information, + new EventId(938218, "ExceptionFilter.RequestBodyTooLarge"), + "'{error_code}': The body of the request is too large." + ); + + private static readonly Action ERROR_WHILE_PROCESSING_REQUEST_TO_URI = + LoggerMessage.Define( + LogLevel.Error, + new EventId(259125, "ExceptionFilter.ErrorWhileProcessingRequestToUri"), + "Unexpected Error while processing request to '{uri}'." + ); + + + public static void InfrastructureException( + this ILogger logger, InfrastructureException infrastructureException, string errorCode, string errorMessage) + { + INFRASTRUCTURE_EXCEPTION(logger, infrastructureException, errorCode, errorMessage, default!); + } + + public static void ApplicationException( + this ILogger logger, ApplicationException applicationException, string errorCode, string errorMessage) + { + APPLICATION_EXCEPTION(logger, applicationException, errorCode, errorMessage, default!); + } + + public static void DomainException( + this ILogger logger, DomainException domainException, string errorCode, string errorMessage) + { + DOMAIN_EXCEPTION(logger, domainException, errorCode, errorMessage, default!); + } + + public static void RequestBodyTooLarge( + this ILogger logger, string errorCode) + { + REQUEST_BODY_TOO_LARGE(logger, errorCode, default!); + } + + public static void ErrorWhileProcessingRequestToUri( + this ILogger logger, Uri uri, Exception e) + { + ERROR_WHILE_PROCESSING_REQUEST_TO_URI(logger, uri, e); + } +} From 06bc09953864921d576e301bec969af160502d11 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Wed, 11 Oct 2023 12:58:23 +0200 Subject: [PATCH 004/133] feat: introduced log event ids chore: fixed minor typos in log statement messages --- .../MediatR/LoggingBehavior.cs | 28 ++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/BuildingBlocks/src/BuildingBlocks.Application/MediatR/LoggingBehavior.cs b/BuildingBlocks/src/BuildingBlocks.Application/MediatR/LoggingBehavior.cs index dabbf09204..64ccfc9027 100644 --- a/BuildingBlocks/src/BuildingBlocks.Application/MediatR/LoggingBehavior.cs +++ b/BuildingBlocks/src/BuildingBlocks.Application/MediatR/LoggingBehavior.cs @@ -1,4 +1,5 @@ using System.Diagnostics; +using Enmeshed.BuildingBlocks.Infrastructure.Exceptions; using MediatR; using Microsoft.Extensions.Logging; @@ -38,6 +39,31 @@ private void After() var logLevel = _watch.ElapsedMilliseconds < 1000 ? LogLevel.Information : LogLevel.Warning; - _logger.Log(logLevel, EVENT_ID_EXECUTION_TIME, "Handled '{requestName}' ('{timeElapsed}' ms)", typeof(TRequest).Name, _watch.ElapsedMilliseconds); + _logger.HandleRequest(typeof(TRequest).Name, _watch.ElapsedMilliseconds); + } +} + +file static class LoggerExtensions +{ + private static readonly Action HANDLED_REQUEST_WARNING = + LoggerMessage.Define( + LogLevel.Warning, + new EventId(000000, "LoggingBehavior.HandleRequestInformation"), + "Handled '{requestName}' ('{timeElapsed}' ms)." + ); + + private static readonly Action HANDLED_REQUEST_INFORMATION = + LoggerMessage.Define( + LogLevel.Information, + new EventId(000000, "LoggingBehavior.HandleRequestInformation"), + "Handled '{requestName}' ('{timeElapsed}' ms)." + ); + + public static void HandleRequest(this ILogger logger, string requestName, long timeElapsed) + { + if (timeElapsed > 1000) + HANDLED_REQUEST_WARNING(logger, requestName, timeElapsed, default!); + else + HANDLED_REQUEST_INFORMATION(logger, requestName, timeElapsed, default!); } } From 63a9bee0640659ea2ad1ca76d7a1b0c203c22c6f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Wed, 11 Oct 2023 13:05:10 +0200 Subject: [PATCH 005/133] chore: added random event ids --- .../src/BuildingBlocks.Application/MediatR/LoggingBehavior.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/BuildingBlocks/src/BuildingBlocks.Application/MediatR/LoggingBehavior.cs b/BuildingBlocks/src/BuildingBlocks.Application/MediatR/LoggingBehavior.cs index 64ccfc9027..d828799c89 100644 --- a/BuildingBlocks/src/BuildingBlocks.Application/MediatR/LoggingBehavior.cs +++ b/BuildingBlocks/src/BuildingBlocks.Application/MediatR/LoggingBehavior.cs @@ -48,14 +48,14 @@ file static class LoggerExtensions private static readonly Action HANDLED_REQUEST_WARNING = LoggerMessage.Define( LogLevel.Warning, - new EventId(000000, "LoggingBehavior.HandleRequestInformation"), + new EventId(437002, "LoggingBehavior.HandleRequestInformation"), "Handled '{requestName}' ('{timeElapsed}' ms)." ); private static readonly Action HANDLED_REQUEST_INFORMATION = LoggerMessage.Define( LogLevel.Information, - new EventId(000000, "LoggingBehavior.HandleRequestInformation"), + new EventId(214089, "LoggingBehavior.HandleRequestInformation"), "Handled '{requestName}' ('{timeElapsed}' ms)." ); From f80e8b0f5777fe74ebe201b2f944f50d1065b38b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Wed, 11 Oct 2023 14:00:13 +0200 Subject: [PATCH 006/133] feat: introduced log event ids --- .../EventBusAzureServiceBus.cs | 104 +++++++++++++++--- 1 file changed, 86 insertions(+), 18 deletions(-) diff --git a/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/AzureServiceBus/EventBusAzureServiceBus.cs b/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/AzureServiceBus/EventBusAzureServiceBus.cs index e4e4fcf053..7dc33d9e3c 100644 --- a/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/AzureServiceBus/EventBusAzureServiceBus.cs +++ b/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/AzureServiceBus/EventBusAzureServiceBus.cs @@ -67,12 +67,12 @@ public async void Publish(IntegrationEvent @event) Subject = eventName }; - _logger.LogTrace("Sending integration event with id '{MessageId}'...", message.MessageId); + _logger.SendingIntegrationEvent(message.MessageId); await _logger.TraceTime(async () => await _sender.SendMessageAsync(message), nameof(_sender.SendMessageAsync)); - _logger.LogTrace("Successfully sent integration event with id '{MessageId}'.", message.MessageId); + _logger.LogDebug("Successfully sent integration event with id '{MessageId}'.", message.MessageId); } public void Subscribe() @@ -85,7 +85,7 @@ public void Subscribe() if (!containsKey) try { - _logger.LogTrace("Trying to create subscription on Service Bus..."); + _logger.LogInformation("Trying to create subscription on Service Bus..."); _serviceBusPersisterConnection.AdministrationClient.CreateRuleAsync(TOPIC_NAME, _subscriptionName, new CreateRuleOptions @@ -94,7 +94,7 @@ public void Subscribe() Name = eventName }).GetAwaiter().GetResult(); - _logger.LogTrace("Successfully created subscription on Service Bus."); + _logger.LogInformation("Successfully created subscription on Service Bus."); } catch (ServiceBusException) { @@ -118,8 +118,7 @@ private async Task RegisterSubscriptionClientMessageHandlerAsync() if (await ProcessEvent(eventName, messageData)) await args.CompleteMessageAsync(args.Message); else - _logger.LogInformation( - "The event with the MessageId '{messageId}' wasn't processed and will therefore not be completed.", args.Message.MessageId); + _logger.EventWasNotProcessed(args.Message.MessageId); }; _processor.ProcessErrorAsync += ErrorHandler; @@ -131,8 +130,7 @@ private Task ErrorHandler(ProcessErrorEventArgs args) var ex = args.Exception; var context = args.ErrorSource; - _logger.LogError(ex, "ERROR handling message: {ExceptionMessage} - Context: {@ExceptionContext}", - ex.Message, context); + _logger.ErrorHandlingMessage(ex.Message, context, ex); return Task.CompletedTask; } @@ -140,7 +138,10 @@ private Task ErrorHandler(ProcessErrorEventArgs args) private async Task ProcessEvent(string eventName, string message) { if (!_subscriptionManager.HasSubscriptionsForEvent(eventName)) + { + _logger.NoSubscriptionForEvent(eventName); return false; + } await using var scope = _autofac.BeginLifetimeScope(AUTOFAC_SCOPE_NAME); @@ -160,25 +161,92 @@ private async Task ProcessEvent(string eventName, string message) try { var policy = EventBusRetryPolicyFactory.Create( - _handlerRetryBehavior, - (ex, _) => _logger.LogWarning( - "The following error was thrown while executing '{eventHandlerType}':\n'{errorMessage}'\n{stacktrace}.\nAttempting to retry...", - eventType.Name, - ex.Message, - ex.StackTrace) - ); + _handlerRetryBehavior, (ex, _) => _logger.ErrorWhileExecutingEventHandlerType(eventType.Name, ex.Message, ex.StackTrace, ex)); await policy.ExecuteAsync(() => (Task)concreteType.GetMethod("Handle")!.Invoke(handler, new[] { integrationEvent })!); } catch (Exception ex) { - _logger.LogError(ex, - $"An error occurred while processing the integration event with id '{integrationEvent.IntegrationEventId}'."); + _logger.ErrorWhileProcessingIntegrationEvent(integrationEvent.IntegrationEventId, ex); return false; } } - return true; } } + +file static class LoggerExtensions +{ + private static readonly Action SENDING_INTEGRATION_EVENT = + LoggerMessage.Define( + LogLevel.Debug, + new EventId(302940, "EventBusAzureServiceBus.SendingIntegrationEvent"), + "Sending integration event with id '{messageId}'..." + ); + + private static readonly Action EVENT_WAS_NOT_PROCESSED = + LoggerMessage.Define( + LogLevel.Information, + new EventId(630568, "EventBusAzureServiceBus.EventWasNotProcessed"), + "The event with the MessageId '{messageId}' wasn't processed and will therefore not be completed." + ); + + private static readonly Action ERROR_HANDLING_MESSAGE = + LoggerMessage.Define( + LogLevel.Error, + new EventId(949322, "EventBusAzureServiceBus.ErrorHandlingMessage"), + "ERROR handling message: '{exceptionMessage}' - Context: '{@exceptionContext}'." + ); + + private static readonly Action NO_SUBSCRIPTION_FOR_EVENT = + LoggerMessage.Define( + LogLevel.Warning, + new EventId(341537, "EventBusAzureServiceBus.NoSubscriptionForEvent"), + "No subscription for event: '{eventName}'." + ); + + private static readonly Action ERROR_WHILE_EXECUTING_EVENT_HANDLER_TYPE = + LoggerMessage.Define( + LogLevel.Warning, + new EventId(726744, "EventBusAzureServiceBus.ErrorWhileExecutingEventHandlerType"), + "The following error was thrown while executing '{eventHandlerType}':\n'{errorMessage}'\n{stackTrace}.\nAttempting to retry..." + ); + + private static readonly Action ERROR_WHILE_PROCESSING_INTEGRATION_EVENT = + LoggerMessage.Define( + LogLevel.Error, + new EventId(146670, "EventBusAzureServiceBus.ErrorWhileProcessingIntegrationEvent"), + "An error occurred while processing the integration event with id '{integrationEventId}'." + ); + + public static void SendingIntegrationEvent(this ILogger logger, string messageId) + { + SENDING_INTEGRATION_EVENT(logger, messageId, default!); + } + + public static void EventWasNotProcessed(this ILogger logger, string messageId) + { + EVENT_WAS_NOT_PROCESSED(logger, messageId, default!); + } + + public static void ErrorHandlingMessage(this ILogger logger, string exceptionMessage, ServiceBusErrorSource exceptionContext, Exception e) + { + ERROR_HANDLING_MESSAGE(logger, exceptionMessage, exceptionContext, e); + } + + public static void NoSubscriptionForEvent(this ILogger logger, string eventName) + { + NO_SUBSCRIPTION_FOR_EVENT(logger, eventName, default!); + } + + public static void ErrorWhileExecutingEventHandlerType(this ILogger logger, string eventHandlerType, string errorMessage, string stackTrace, Exception e) + { + ERROR_WHILE_EXECUTING_EVENT_HANDLER_TYPE(logger, eventHandlerType, errorMessage, stackTrace, e); + } + + public static void ErrorWhileProcessingIntegrationEvent(this ILogger logger, string integrationEventId, Exception e) + { + ERROR_WHILE_PROCESSING_INTEGRATION_EVENT(logger, integrationEventId, e); + } +} From 9dc7a6afb8bbce95ebe1d5a47849c53d93782505 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Wed, 11 Oct 2023 14:17:32 +0200 Subject: [PATCH 007/133] chore: supressed nullable warning --- .../EventBus/AzureServiceBus/EventBusAzureServiceBus.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/AzureServiceBus/EventBusAzureServiceBus.cs b/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/AzureServiceBus/EventBusAzureServiceBus.cs index 7dc33d9e3c..ea17a2f23c 100644 --- a/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/AzureServiceBus/EventBusAzureServiceBus.cs +++ b/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/AzureServiceBus/EventBusAzureServiceBus.cs @@ -161,7 +161,7 @@ private async Task ProcessEvent(string eventName, string message) try { var policy = EventBusRetryPolicyFactory.Create( - _handlerRetryBehavior, (ex, _) => _logger.ErrorWhileExecutingEventHandlerType(eventType.Name, ex.Message, ex.StackTrace, ex)); + _handlerRetryBehavior, (ex, _) => _logger.ErrorWhileExecutingEventHandlerType(eventType.Name, ex.Message, ex.StackTrace!, ex)); await policy.ExecuteAsync(() => (Task)concreteType.GetMethod("Handle")!.Invoke(handler, new[] { integrationEvent })!); } From f60822887f1ad318efd437f45f855c5651db75d1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Wed, 11 Oct 2023 14:18:19 +0200 Subject: [PATCH 008/133] feat: introduced log event ids --- .../EventBusGoogleCloudPubSub.cs | 66 +++++++++++++++---- 1 file changed, 55 insertions(+), 11 deletions(-) diff --git a/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/GoogleCloudPubSub/EventBusGoogleCloudPubSub.cs b/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/GoogleCloudPubSub/EventBusGoogleCloudPubSub.cs index de7cf466f1..dc0619fdf9 100644 --- a/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/GoogleCloudPubSub/EventBusGoogleCloudPubSub.cs +++ b/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/GoogleCloudPubSub/EventBusGoogleCloudPubSub.cs @@ -1,5 +1,6 @@ using System.Text.RegularExpressions; using Autofac; +using Azure.Messaging.ServiceBus; using Enmeshed.BuildingBlocks.Application.Abstractions.Infrastructure.EventBus; using Enmeshed.BuildingBlocks.Application.Abstractions.Infrastructure.EventBus.Events; using Enmeshed.BuildingBlocks.Infrastructure.EventBus.Json; @@ -66,7 +67,7 @@ public async void Publish(IntegrationEvent @event) var messageId = await _logger.TraceTime( () => _connection.PublisherClient.PublishAsync(message), nameof(_connection.PublisherClient.PublishAsync)); - _logger.LogTrace("Successfully sent integration event with id '{messageId}'.", messageId); + _logger.EventWasNotProcessed(messageId); } public void Subscribe() @@ -97,8 +98,7 @@ private static string RemoveIntegrationEventSuffix(string typeName) } catch (Exception ex) { - _logger.LogError(ex, "ERROR handling message: {ExceptionMessage} - Context: {@ExceptionSource}", - ex.Message, ex.Source); + _logger.ErrorHandlingMessage(ex); return SubscriberClient.Reply.Nack; } @@ -110,7 +110,7 @@ private async Task ProcessEvent(string eventName, string message) { if (!_subscriptionManager.HasSubscriptionsForEvent(eventName)) { - _logger.LogWarning("No subscription for event: '{EventName}'", eventName); + _logger.NoSubscriptionForEvent(eventName); return; } @@ -132,15 +132,59 @@ private async Task ProcessEvent(string eventName, string message) var handleMethod = handler.GetType().GetMethod("Handle"); var policy = EventBusRetryPolicyFactory.Create( - _handlerRetryBehavior, - (ex, _) => _logger.LogWarning( - "The following error was thrown while executing '{eventHandlerType}':\n'{errorMessage}'\n{stacktrace}.\nAttempting to retry...", - eventName, - ex.Message, - ex.StackTrace) - ); + _handlerRetryBehavior, (ex, _) => _logger.ErrorWhileExecutingEventHandlerType(eventName, ex.Message, ex.StackTrace!, ex)); await policy.ExecuteAsync(() => (Task)handleMethod!.Invoke(handler, new object[] { integrationEvent })!); } } } + +file static class LoggerExtensions +{ + private static readonly Action SENDING_INTEGRATION_EVENT = + LoggerMessage.Define( + LogLevel.Debug, + new EventId(830408, "EventBusGoogleCloudPubSub.SendingIntegrationEvent"), + "Successfully sent integration event with id '{messageId}'." + ); + + private static readonly Action ERROR_HANDLING_MESSAGE = + LoggerMessage.Define( + LogLevel.Error, + new EventId(949322, "EventBusAzureServiceBus.ErrorHandlingMessage"), + "ERROR handling message: '{exceptionMessage}' - Context: '{@exceptionSource}'." + ); + + private static readonly Action NO_SUBSCRIPTION_FOR_EVENT = + LoggerMessage.Define( + LogLevel.Warning, + new EventId(341537, "EventBusAzureServiceBus.NoSubscriptionForEvent"), + "No subscription for event: '{eventName}'." + ); + + private static readonly Action ERROR_WHILE_EXECUTING_EVENT_HANDLER_TYPE = + LoggerMessage.Define( + LogLevel.Warning, + new EventId(726744, "EventBusAzureServiceBus.ErrorWhileExecutingEventHandlerType"), + "The following error was thrown while executing '{eventHandlerType}':\n'{errorMessage}'\n{stackTrace}.\nAttempting to retry..." + ); + + public static void EventWasNotProcessed(this ILogger logger, string messageId) + { + SENDING_INTEGRATION_EVENT(logger, messageId, default!); + } + + public static void ErrorHandlingMessage(this ILogger logger, Exception e) + { + ERROR_HANDLING_MESSAGE(logger, e.Message, e.Source!, e); + } + public static void NoSubscriptionForEvent(this ILogger logger, string eventName) + { + NO_SUBSCRIPTION_FOR_EVENT(logger, eventName, default!); + } + + public static void ErrorWhileExecutingEventHandlerType(this ILogger logger, string eventHandlerType, string errorMessage, string stackTrace, Exception e) + { + ERROR_WHILE_EXECUTING_EVENT_HANDLER_TYPE(logger, eventHandlerType, errorMessage, stackTrace, e); + } +} From 1830a4a7c54ac001d3c0da31d5ab9a76f365234d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Wed, 11 Oct 2023 14:35:25 +0200 Subject: [PATCH 009/133] fix: updated event ids to unique values --- .../EventBus/GoogleCloudPubSub/EventBusGoogleCloudPubSub.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/GoogleCloudPubSub/EventBusGoogleCloudPubSub.cs b/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/GoogleCloudPubSub/EventBusGoogleCloudPubSub.cs index dc0619fdf9..0ace8f78c4 100644 --- a/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/GoogleCloudPubSub/EventBusGoogleCloudPubSub.cs +++ b/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/GoogleCloudPubSub/EventBusGoogleCloudPubSub.cs @@ -151,21 +151,21 @@ file static class LoggerExtensions private static readonly Action ERROR_HANDLING_MESSAGE = LoggerMessage.Define( LogLevel.Error, - new EventId(949322, "EventBusAzureServiceBus.ErrorHandlingMessage"), + new EventId(712382, "EventBusGoogleCloudPubSub.ErrorHandlingMessage"), "ERROR handling message: '{exceptionMessage}' - Context: '{@exceptionSource}'." ); private static readonly Action NO_SUBSCRIPTION_FOR_EVENT = LoggerMessage.Define( LogLevel.Warning, - new EventId(341537, "EventBusAzureServiceBus.NoSubscriptionForEvent"), + new EventId(590747, "EventBusGoogleCloudPubSub.NoSubscriptionForEvent"), "No subscription for event: '{eventName}'." ); private static readonly Action ERROR_WHILE_EXECUTING_EVENT_HANDLER_TYPE = LoggerMessage.Define( LogLevel.Warning, - new EventId(726744, "EventBusAzureServiceBus.ErrorWhileExecutingEventHandlerType"), + new EventId(304842, "EventBusGoogleCloudPubSub.ErrorWhileExecutingEventHandlerType"), "The following error was thrown while executing '{eventHandlerType}':\n'{errorMessage}'\n{stackTrace}.\nAttempting to retry..." ); From 2593143e3b87ba865869bf4f9a6dc60029185d01 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Wed, 11 Oct 2023 14:36:07 +0200 Subject: [PATCH 010/133] feat: introduced log event ids --- .../DefaultRabbitMQPersisterConnection.cs | 69 ++++++++++++++++--- 1 file changed, 58 insertions(+), 11 deletions(-) diff --git a/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/RabbitMQ/DefaultRabbitMQPersisterConnection.cs b/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/RabbitMQ/DefaultRabbitMQPersisterConnection.cs index 9d01d14c7f..9e2ae3dbbc 100644 --- a/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/RabbitMQ/DefaultRabbitMQPersisterConnection.cs +++ b/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/RabbitMQ/DefaultRabbitMQPersisterConnection.cs @@ -48,7 +48,7 @@ public void Dispose() } catch (IOException ex) { - _logger.LogCritical(ex.ToString()); + _logger.LogCritical(ex, ex.Message); } } @@ -60,8 +60,9 @@ public bool TryConnect() { var policy = Policy.Handle() .Or() - .WaitAndRetry(_retryCount, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), - (ex, _) => _logger.LogWarning(ex.ToString())); + .WaitAndRetry(_retryCount, + retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), + (ex, _) => _logger.BrokerUnreachableException(ex.ToString())); policy.Execute(() => _connection = _connectionFactory .CreateConnection()); @@ -86,27 +87,73 @@ public bool TryConnect() private void OnConnectionBlocked(object? sender, ConnectionBlockedEventArgs e) { if (_disposed) return; - - _logger.LogWarning("A RabbitMQ connection is shutdown. Trying to re-connect..."); - + _logger.ConnectionIsShutdown(); TryConnect(); } private void OnCallbackException(object? sender, CallbackExceptionEventArgs e) { if (_disposed) return; - - _logger.LogWarning("A RabbitMQ connection throw exception. Trying to re-connect..."); - + _logger.ConnectionThrewAnException(); TryConnect(); } private void OnConnectionShutdown(object? sender, ShutdownEventArgs reason) { if (_disposed) return; + _logger.ConnectionIsOnShutdown(); + TryConnect(); + } +} + +file static class LoggerExtensions +{ + // TODO-Nikola: review after Timo gets back to me + private static readonly Action BROKER_UNREACHABLE_EXCEPTION = + LoggerMessage.Define( + LogLevel.Warning, + new EventId(715507, "DefaultRabbitMqPersistentConnection.BrokerUnreachableException"), + "{exceptionString}" + ); + + private static readonly Action CONNECTION_IS_SHUTDOWN = + LoggerMessage.Define( + LogLevel.Warning, + new EventId(119836, "DefaultRabbitMqPersistentConnection.ConnectionIsShutdown"), + "A RabbitMQ connection is shutdown. Trying to re-connect..." + ); + + private static readonly Action CONNECTION_THREW_AN_EXCEPTION = + LoggerMessage.Define( + LogLevel.Warning, + new EventId(143946, "DefaultRabbitMqPersistentConnection.ConnectionThrewAnException"), + "A RabbitMQ connection threw an exception. Trying to re-connect..." + ); + + private static readonly Action CONNECTION_IS_ON_SHUTDOWN = + LoggerMessage.Define( + LogLevel.Warning, + new EventId(454129, "DefaultRabbitMqPersistentConnection.ConnectionIsOnShutdown"), + "A RabbitMQ connection is on shutdown. Trying to re-connect..." + ); + + public static void BrokerUnreachableException(this ILogger logger, string exceptionString) + { + BROKER_UNREACHABLE_EXCEPTION(logger, exceptionString, default!); + } - _logger.LogWarning("A RabbitMQ connection is on shutdown. Trying to re-connect..."); + public static void ConnectionIsShutdown(this ILogger logger) + { + CONNECTION_IS_SHUTDOWN(logger, default!); + } - TryConnect(); + public static void ConnectionThrewAnException(this ILogger logger) + { + CONNECTION_THREW_AN_EXCEPTION(logger, default!); + } + + public static void ConnectionIsOnShutdown(this ILogger logger) + { + CONNECTION_IS_ON_SHUTDOWN(logger, default!); } } From 80b6230be773256640fb0f1fa81a4b631ad9b0cb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Wed, 11 Oct 2023 14:57:41 +0200 Subject: [PATCH 011/133] feat: introduced log event ids --- .../EventBus/RabbitMQ/EventBusRabbitMQ.cs | 94 +++++++++++++++---- 1 file changed, 75 insertions(+), 19 deletions(-) diff --git a/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/RabbitMQ/EventBusRabbitMQ.cs b/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/RabbitMQ/EventBusRabbitMQ.cs index 8845f34718..94787b842b 100644 --- a/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/RabbitMQ/EventBusRabbitMQ.cs +++ b/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/RabbitMQ/EventBusRabbitMQ.cs @@ -56,16 +56,17 @@ public void Publish(IntegrationEvent @event) var policy = Policy.Handle() .Or() - .WaitAndRetry(_connectionRetryCount, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), - (ex, _) => _logger.LogWarning(ex.ToString())); + .WaitAndRetry(_connectionRetryCount, + retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), + (ex, _) => _logger.SocketException(ex.Message, ex)); var eventName = @event.GetType().Name; - _logger.LogTrace("Creating RabbitMQ channel to publish event: '{EventId}' ({EventName})", @event.IntegrationEventId, eventName); + _logger.LogInformation("Creating RabbitMQ channel to publish event: '{EventId}' ({EventName})", @event.IntegrationEventId, eventName); _persistentConnection.CreateModel().ExchangeDeclare(BROKER_NAME, "direct"); - _logger.LogTrace("Declaring RabbitMQ exchange to publish event: '{EventId}'", @event.IntegrationEventId); + _logger.LogInformation("Declaring RabbitMQ exchange to publish event: '{EventId}'", @event.IntegrationEventId); var message = JsonConvert.SerializeObject(@event, new JsonSerializerSettings { @@ -76,7 +77,7 @@ public void Publish(IntegrationEvent @event) policy.Execute(() => { - _logger.LogTrace("Publishing event to RabbitMQ: '{EventId}'", @event.IntegrationEventId); + _logger.LogDebug("Publishing event to RabbitMQ: '{EventId}'", @event.IntegrationEventId); using var channel = _persistentConnection.CreateModel(); var properties = channel.CreateBasicProperties(); @@ -89,7 +90,7 @@ public void Publish(IntegrationEvent @event) properties, body); - _logger.LogTrace("Successfully published event with id '{integrationEventId}'.", @event.IntegrationEventId); + _logger.IntegrationEventId(@event.IntegrationEventId); }); } @@ -130,7 +131,7 @@ private IModel CreateConsumerChannel() { if (!_persistentConnection.IsConnected) _persistentConnection.TryConnect(); - _logger.LogTrace("Creating RabbitMQ consumer channel"); + _logger.LogInformation("Creating RabbitMQ consumer channel"); var channel = _persistentConnection.CreateModel(); @@ -156,11 +157,9 @@ private IModel CreateConsumerChannel() } catch (Exception ex) { - channel.BasicReject(eventArgs.DeliveryTag, true); - _logger.LogError(ex, - $"An error occurred while processing the integration event of type '{eventName}'."); + _logger.ErrorWhileProcessingIntegrationEvent(eventName, ex); } }; @@ -179,7 +178,7 @@ private IModel CreateConsumerChannel() private async Task ProcessEvent(string eventName, string message) { - _logger.LogTrace("Processing RabbitMQ event: '{EventName}'", eventName); + _logger.LogDebug("Processing RabbitMQ event: '{EventName}'", eventName); if (_subsManager.HasSubscriptionsForEvent(eventName)) { @@ -202,20 +201,77 @@ private async Task ProcessEvent(string eventName, string message) var concreteType = typeof(IIntegrationEventHandler<>).MakeGenericType(eventType); var policy = EventBusRetryPolicyFactory.Create( - _handlerRetryBehavior, - (ex, _) => _logger.LogWarning( - "The following error was thrown while executing '{eventHandlerType}':\n'{errorMessage}'\n{stacktrace}.\nAttempting to retry...", - eventType.Name, - ex.Message, - ex.StackTrace) - ); + _handlerRetryBehavior, (ex, _) => _logger.ErrorWhileExecutingEventHandlerType(eventName, ex.Message, ex.StackTrace!, ex)); await policy.ExecuteAsync(() => (Task)concreteType.GetMethod("Handle")!.Invoke(handler, new[] { integrationEvent })!); } } else { - _logger.LogWarning("No subscription for RabbitMQ event: '{EventName}'", eventName); + _logger.NoSubscriptionForEvent(eventName); } } } + +file static class LoggerExtensions +{ + // TODO-Nikola: review after Timo gets back to me + private static readonly Action SOCKET_EXCEPTION = + LoggerMessage.Define( + LogLevel.Warning, + new EventId(411326, "EventBusRabbitMQ.SocketException"), + "{exceptionString}" + ); + + private static readonly Action PUBLISHED_INTEGERATION_EVENT = + LoggerMessage.Define( + LogLevel.Debug, + new EventId(585231, "EventBusRabbitMQ.PublishedIntegrationEvent"), + "Successfully published event with id '{integrationEventId}'." + ); + + private static readonly Action ERROR_WHILE_PROCESSING_INTEGRATION_EVENT = + LoggerMessage.Define( + LogLevel.Error, + new EventId(702822, "EventBusRabbitMQ.ErrorWhileProcessingIntegrationEvent"), + "An error occurred while processing the integration event of type '{eventName}'." + ); + + private static readonly Action NO_SUBSCRIPTION_FOR_EVENT = + LoggerMessage.Define( + LogLevel.Warning, + new EventId(980768, "EventBusRabbitMQ.NoSubscriptionForEvent"), + "No subscription for event: '{eventName}'." + ); + + private static readonly Action ERROR_WHILE_EXECUTING_EVENT_HANDLER_TYPE = + LoggerMessage.Define( + LogLevel.Warning, + new EventId(288394, "EventBusRabbitMQ.ErrorWhileExecutingEventHandlerType"), + "The following error was thrown while executing '{eventHandlerType}':\n'{errorMessage}'\n{stackTrace}.\nAttempting to retry..." + ); + + public static void SocketException(this ILogger logger, string exceptionString, Exception e) + { + SOCKET_EXCEPTION(logger, exceptionString, e); + } + + public static void IntegrationEventId(this ILogger logger, string integrationEventId) + { + PUBLISHED_INTEGERATION_EVENT(logger, integrationEventId, default!); + } + + public static void ErrorWhileProcessingIntegrationEvent(this ILogger logger, string eventName, Exception e) + { + ERROR_WHILE_PROCESSING_INTEGRATION_EVENT(logger, eventName, e); + } + public static void NoSubscriptionForEvent(this ILogger logger, string eventName) + { + NO_SUBSCRIPTION_FOR_EVENT(logger, eventName, default!); + } + + public static void ErrorWhileExecutingEventHandlerType(this ILogger logger, string eventHandlerType, string errorMessage, string stackTrace, Exception e) + { + ERROR_WHILE_EXECUTING_EVENT_HANDLER_TYPE(logger, eventHandlerType, errorMessage, stackTrace, e); + } +} From 653ce33c6d3368481de9771ee2c05737501de6f7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Wed, 11 Oct 2023 19:20:06 +0200 Subject: [PATCH 012/133] chore: updated messages that only contain exception message --- .../EventBus/RabbitMQ/DefaultRabbitMQPersisterConnection.cs | 1 - .../EventBus/RabbitMQ/EventBusRabbitMQ.cs | 1 - 2 files changed, 2 deletions(-) diff --git a/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/RabbitMQ/DefaultRabbitMQPersisterConnection.cs b/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/RabbitMQ/DefaultRabbitMQPersisterConnection.cs index 9e2ae3dbbc..dc7169a063 100644 --- a/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/RabbitMQ/DefaultRabbitMQPersisterConnection.cs +++ b/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/RabbitMQ/DefaultRabbitMQPersisterConnection.cs @@ -108,7 +108,6 @@ private void OnConnectionShutdown(object? sender, ShutdownEventArgs reason) file static class LoggerExtensions { - // TODO-Nikola: review after Timo gets back to me private static readonly Action BROKER_UNREACHABLE_EXCEPTION = LoggerMessage.Define( LogLevel.Warning, diff --git a/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/RabbitMQ/EventBusRabbitMQ.cs b/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/RabbitMQ/EventBusRabbitMQ.cs index 94787b842b..fdcefd9bdb 100644 --- a/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/RabbitMQ/EventBusRabbitMQ.cs +++ b/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/RabbitMQ/EventBusRabbitMQ.cs @@ -215,7 +215,6 @@ private async Task ProcessEvent(string eventName, string message) file static class LoggerExtensions { - // TODO-Nikola: review after Timo gets back to me private static readonly Action SOCKET_EXCEPTION = LoggerMessage.Define( LogLevel.Warning, From f47b890fd18ef8aaa88dfbe5b6eb8282961e6858 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Wed, 11 Oct 2023 19:31:36 +0200 Subject: [PATCH 013/133] feat: introduced log event ids --- .../AzureStorageAccount.cs | 31 +++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/BuildingBlocks/src/BuildingBlocks.Infrastructure/Persistence/BlobStorage/AzureStorageAccount/AzureStorageAccount.cs b/BuildingBlocks/src/BuildingBlocks.Infrastructure/Persistence/BlobStorage/AzureStorageAccount/AzureStorageAccount.cs index d1b5996998..3f20c578ca 100644 --- a/BuildingBlocks/src/BuildingBlocks.Infrastructure/Persistence/BlobStorage/AzureStorageAccount/AzureStorageAccount.cs +++ b/BuildingBlocks/src/BuildingBlocks.Infrastructure/Persistence/BlobStorage/AzureStorageAccount/AzureStorageAccount.cs @@ -74,7 +74,7 @@ public Task> FindAllAsync(string folder, string? prefix } catch (Exception ex) { - _logger.LogError("There was an error listing all the blobs.", ex); + _logger.ErrorListingAllTheBlobs(ex); throw; } } @@ -127,10 +127,37 @@ private async Task DeleteRemovedBlobs() } catch (Exception ex) { - _logger.LogError("There was an error deleting the blob with id '{cloudBlockBlobName}'. {ex}", cloudBlockBlob.Name, ex); + _logger.ErrorDeletingTheBlob(cloudBlockBlob.Name, ex); throw new NotFoundException(); } _logger.LogTrace("Deletion successful."); } } + +file static class LoggerExtensions +{ + private static readonly Action ERROR_LISTING_ALL_THE_BLOBS = + LoggerMessage.Define( + LogLevel.Error, + new EventId(516591, "AzureStorageAccount.ErrorListingAllTheBlobs"), + "There was an error listing all the blobs." + ); + + private static readonly Action ERROR_DELETING_THE_BLOB = + LoggerMessage.Define( + LogLevel.Error, + new EventId(645028, "AzureStorageAccount.ErrorDeletingTheBlob"), + "There was an error deleting the blob with id '{cloudBlockBlobName}'. {ex}" + ); + + public static void ErrorListingAllTheBlobs(this ILogger logger, Exception e) + { + ERROR_LISTING_ALL_THE_BLOBS(logger, e); + } + + public static void ErrorDeletingTheBlob(this ILogger logger, string cloudBlockBlobName, Exception e) + { + ERROR_DELETING_THE_BLOB(logger, cloudBlockBlobName, e, default!); + } +} From defd5e5745022e64383b242b75d859af095c84de Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Thu, 12 Oct 2023 13:31:06 +0200 Subject: [PATCH 014/133] feat: introduced log event ids --- .../GoogleCloudStorage/GoogleCloudStorage.cs | 74 +++++++++++++++++-- 1 file changed, 69 insertions(+), 5 deletions(-) diff --git a/BuildingBlocks/src/BuildingBlocks.Infrastructure/Persistence/BlobStorage/GoogleCloudStorage/GoogleCloudStorage.cs b/BuildingBlocks/src/BuildingBlocks.Infrastructure/Persistence/BlobStorage/GoogleCloudStorage/GoogleCloudStorage.cs index 374d1a7599..46318b371b 100644 --- a/BuildingBlocks/src/BuildingBlocks.Infrastructure/Persistence/BlobStorage/GoogleCloudStorage/GoogleCloudStorage.cs +++ b/BuildingBlocks/src/BuildingBlocks.Infrastructure/Persistence/BlobStorage/GoogleCloudStorage/GoogleCloudStorage.cs @@ -1,4 +1,5 @@ using System.Net; +using System.Reflection.Metadata; using Enmeshed.BuildingBlocks.Application.Abstractions.Exceptions; using Enmeshed.BuildingBlocks.Application.Abstractions.Infrastructure.Persistence.BlobStorage; using Google; @@ -57,7 +58,7 @@ await _logger.TraceTime(async () => catch (Exception ex) { EliminateNotFound(ex, blobId); - _logger.LogError("There was an error downloading the blob with key '{blobId}'. {ex}", blobId, ex); + _logger.ErrorDownloadingTheBlobWithKey(blobId, ex); throw; } } @@ -75,7 +76,7 @@ public Task> FindAllAsync(string folder, string? prefix } catch (Exception ex) { - _logger.LogError("There was an error listing all the blobs.", ex); + _logger.ErrorListingAllTheBlobs(ex); throw; } } @@ -116,7 +117,7 @@ await _storageClient.UploadObjectAsync(blob.Folder, blob.Name, null, } catch (Exception ex) { - _logger.LogError("There was an error uploading the blob with key '{blobName}'. {ex}", blob.Name, ex); + _logger.ErrorUploadingTheBlobWithName(blob.Name, ex); throw; } finally @@ -133,7 +134,7 @@ private async Task EnsureKeyDoesNotExist(string folder, string key) await _logger.TraceTime(async () => await _storageClient.GetObjectAsync(folder, key), nameof(_storageClient.GetObjectAsync)); - _logger.LogError("The blob with the given key already exists."); + _logger.ErrorBlobWithTheKeyExists(); throw new BlobAlreadyExistsException(key); } catch (GoogleApiException ex) @@ -160,7 +161,7 @@ private async Task DeleteRemovedBlobs() catch (Exception ex) { EliminateNotFound(ex, blob.Name); - _logger.LogError("There was an error deleting the blob with key '{blobKey}'. {ex}", blob, ex); + _logger.ErrorDeletingTheBlobWithName(blob.Name, ex); throw; } @@ -171,3 +172,66 @@ private record ChangedBlob(string Folder, string Name, byte[] Content); private record RemovedBlob(string Folder, string Name); } + +file static class LoggerExtensions +{ + private static readonly Action ERROR_DOWNLOADING_THE_BLOB_WITH_KEY = + LoggerMessage.Define( + LogLevel.Error, + new EventId(000000, "GoogleCloudStorage.ErrorDownloadingTheBlobWithKey"), + "There was an error downloading the blob with key '{blobId}'. {ex}" + ); + + private static readonly Action ERROR_LISTING_ALL_THE_BLOBS = + LoggerMessage.Define( + LogLevel.Error, + new EventId(000000, "GoogleCloudStorage.ErrorListingAllTheBlobs"), + "There was an error listing all the blobs." + ); + + private static readonly Action ERROR_UPLOADING_THE_BLOB_WITH_NAME = + LoggerMessage.Define( + LogLevel.Error, + new EventId(000000, "GoogleCloudStorage.ErrorUploadingTheBlobWithName"), + "There was an error uploading the blob with name '{blobName}'. {ex}" + ); + + private static readonly Action ERROR_BLOB_WITH_THE_KEY_EXISTS = + LoggerMessage.Define( + LogLevel.Error, + new EventId(000000, "GoogleCloudStorage.ErrorBlobWithTheKeyExists"), + "The blob with the given key already exists." + ); + + private static readonly Action ERROR_DELETING_THE_BLOB_WITH_NAME = + LoggerMessage.Define( + LogLevel.Error, + new EventId(000000, "GoogleCloudStorage.ErrorDeletingTheBlobWithName"), + "There was an error downloading the blob with name '{blobName}'. {ex}" + ); + + public static void ErrorDownloadingTheBlobWithKey(this ILogger logger, string blobId, Exception e) + { + ERROR_DOWNLOADING_THE_BLOB_WITH_KEY(logger, blobId, e, e); + } + + public static void ErrorListingAllTheBlobs(this ILogger logger, Exception e) + { + ERROR_LISTING_ALL_THE_BLOBS(logger, e); + } + + public static void ErrorUploadingTheBlobWithName(this ILogger logger, string blobName, Exception e) + { + ERROR_UPLOADING_THE_BLOB_WITH_NAME(logger, blobName, e, e); + } + + public static void ErrorBlobWithTheKeyExists(this ILogger logger) + { + ERROR_BLOB_WITH_THE_KEY_EXISTS(logger, default!); + } + + public static void ErrorDeletingTheBlobWithName(this ILogger logger, string blobName, Exception e) + { + ERROR_DELETING_THE_BLOB_WITH_NAME(logger, blobName, e, e); + } +} From e300a4e470f7425a0206e1167b651580086deb81 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Thu, 12 Oct 2023 13:37:17 +0200 Subject: [PATCH 015/133] chore: removed unused directives --- .../EventBus/GoogleCloudPubSub/EventBusGoogleCloudPubSub.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/GoogleCloudPubSub/EventBusGoogleCloudPubSub.cs b/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/GoogleCloudPubSub/EventBusGoogleCloudPubSub.cs index 0ace8f78c4..f2c2895ca7 100644 --- a/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/GoogleCloudPubSub/EventBusGoogleCloudPubSub.cs +++ b/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/GoogleCloudPubSub/EventBusGoogleCloudPubSub.cs @@ -1,6 +1,5 @@ using System.Text.RegularExpressions; using Autofac; -using Azure.Messaging.ServiceBus; using Enmeshed.BuildingBlocks.Application.Abstractions.Infrastructure.EventBus; using Enmeshed.BuildingBlocks.Application.Abstractions.Infrastructure.EventBus.Events; using Enmeshed.BuildingBlocks.Infrastructure.EventBus.Json; From 0b818dec41d0873741bef5a8ceab7d10f1bd65f5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Thu, 12 Oct 2023 13:37:31 +0200 Subject: [PATCH 016/133] chore: replaced generic codes with proper ones --- .../GoogleCloudStorage/GoogleCloudStorage.cs | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/BuildingBlocks/src/BuildingBlocks.Infrastructure/Persistence/BlobStorage/GoogleCloudStorage/GoogleCloudStorage.cs b/BuildingBlocks/src/BuildingBlocks.Infrastructure/Persistence/BlobStorage/GoogleCloudStorage/GoogleCloudStorage.cs index 46318b371b..fa35b00de9 100644 --- a/BuildingBlocks/src/BuildingBlocks.Infrastructure/Persistence/BlobStorage/GoogleCloudStorage/GoogleCloudStorage.cs +++ b/BuildingBlocks/src/BuildingBlocks.Infrastructure/Persistence/BlobStorage/GoogleCloudStorage/GoogleCloudStorage.cs @@ -1,5 +1,4 @@ using System.Net; -using System.Reflection.Metadata; using Enmeshed.BuildingBlocks.Application.Abstractions.Exceptions; using Enmeshed.BuildingBlocks.Application.Abstractions.Infrastructure.Persistence.BlobStorage; using Google; @@ -178,35 +177,35 @@ file static class LoggerExtensions private static readonly Action ERROR_DOWNLOADING_THE_BLOB_WITH_KEY = LoggerMessage.Define( LogLevel.Error, - new EventId(000000, "GoogleCloudStorage.ErrorDownloadingTheBlobWithKey"), + new EventId(997942, "GoogleCloudStorage.ErrorDownloadingTheBlobWithKey"), "There was an error downloading the blob with key '{blobId}'. {ex}" ); private static readonly Action ERROR_LISTING_ALL_THE_BLOBS = LoggerMessage.Define( LogLevel.Error, - new EventId(000000, "GoogleCloudStorage.ErrorListingAllTheBlobs"), + new EventId(998879, "GoogleCloudStorage.ErrorListingAllTheBlobs"), "There was an error listing all the blobs." ); private static readonly Action ERROR_UPLOADING_THE_BLOB_WITH_NAME = LoggerMessage.Define( LogLevel.Error, - new EventId(000000, "GoogleCloudStorage.ErrorUploadingTheBlobWithName"), + new EventId(166344, "GoogleCloudStorage.ErrorUploadingTheBlobWithName"), "There was an error uploading the blob with name '{blobName}'. {ex}" ); private static readonly Action ERROR_BLOB_WITH_THE_KEY_EXISTS = LoggerMessage.Define( LogLevel.Error, - new EventId(000000, "GoogleCloudStorage.ErrorBlobWithTheKeyExists"), + new EventId(358892, "GoogleCloudStorage.ErrorBlobWithTheKeyExists"), "The blob with the given key already exists." ); private static readonly Action ERROR_DELETING_THE_BLOB_WITH_NAME = LoggerMessage.Define( LogLevel.Error, - new EventId(000000, "GoogleCloudStorage.ErrorDeletingTheBlobWithName"), + new EventId(304533, "GoogleCloudStorage.ErrorDeletingTheBlobWithName"), "There was an error downloading the blob with name '{blobName}'. {ex}" ); From 5a2a165fda5dedee9f427a1b094bd9c7bd418444 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Thu, 12 Oct 2023 13:40:14 +0200 Subject: [PATCH 017/133] feat: introduced log event ids --- .../Clients/Commands/DeleteClient/Handler.cs | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/Modules/Devices/src/Devices.Application/Clients/Commands/DeleteClient/Handler.cs b/Modules/Devices/src/Devices.Application/Clients/Commands/DeleteClient/Handler.cs index 0f3efe6bab..28376a1543 100644 --- a/Modules/Devices/src/Devices.Application/Clients/Commands/DeleteClient/Handler.cs +++ b/Modules/Devices/src/Devices.Application/Clients/Commands/DeleteClient/Handler.cs @@ -21,6 +21,21 @@ public async Task Handle(DeleteClientCommand request, CancellationToken cancella await _oAuthClientsRepository.Delete(request.ClientId, cancellationToken); - _logger.LogTrace("Successfully deleted client with id '{clientId}'.", request.ClientId); + _logger.DeletedClientWithId(request.ClientId); + } +} + +file static class LoggerExtensions +{ + private static readonly Action DELETED_CLIENT_WITH_ID = + LoggerMessage.Define( + LogLevel.Information, + new EventId(418943, "DeleteClient.Handler.DeletedClientWithId"), + "Successfully deleted client with id '{clientId}'." + ); + + public static void DeletedClientWithId(this ILogger logger, string clientId) + { + DELETED_CLIENT_WITH_ID(logger, clientId, default!); } } From e52ce1f220c0d0ca037ba11a68c78757957f5a29 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Thu, 12 Oct 2023 13:47:08 +0200 Subject: [PATCH 018/133] chore: both blob ids and names are now referred to as 'name' in all places --- .../GoogleCloudStorage/GoogleCloudStorage.cs | 24 +++++++++---------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/BuildingBlocks/src/BuildingBlocks.Infrastructure/Persistence/BlobStorage/GoogleCloudStorage/GoogleCloudStorage.cs b/BuildingBlocks/src/BuildingBlocks.Infrastructure/Persistence/BlobStorage/GoogleCloudStorage/GoogleCloudStorage.cs index fa35b00de9..4d0c836cb5 100644 --- a/BuildingBlocks/src/BuildingBlocks.Infrastructure/Persistence/BlobStorage/GoogleCloudStorage/GoogleCloudStorage.cs +++ b/BuildingBlocks/src/BuildingBlocks.Infrastructure/Persistence/BlobStorage/GoogleCloudStorage/GoogleCloudStorage.cs @@ -57,7 +57,7 @@ await _logger.TraceTime(async () => catch (Exception ex) { EliminateNotFound(ex, blobId); - _logger.ErrorDownloadingTheBlobWithKey(blobId, ex); + _logger.ErrorDownloadingTheBlobWithName(blobId, ex); throw; } } @@ -133,7 +133,7 @@ private async Task EnsureKeyDoesNotExist(string folder, string key) await _logger.TraceTime(async () => await _storageClient.GetObjectAsync(folder, key), nameof(_storageClient.GetObjectAsync)); - _logger.ErrorBlobWithTheKeyExists(); + _logger.ErrorBlobWithTheNameExists(); throw new BlobAlreadyExistsException(key); } catch (GoogleApiException ex) @@ -174,11 +174,11 @@ private record RemovedBlob(string Folder, string Name); file static class LoggerExtensions { - private static readonly Action ERROR_DOWNLOADING_THE_BLOB_WITH_KEY = + private static readonly Action ERROR_DOWNLOADING_THE_BLOB_WITH_NAME = LoggerMessage.Define( LogLevel.Error, - new EventId(997942, "GoogleCloudStorage.ErrorDownloadingTheBlobWithKey"), - "There was an error downloading the blob with key '{blobId}'. {ex}" + new EventId(997942, "GoogleCloudStorage.ErrorDownloadingTheBlobWithName"), + "There was an error downloading the blob with name '{blobId}'. {ex}" ); private static readonly Action ERROR_LISTING_ALL_THE_BLOBS = @@ -195,11 +195,11 @@ file static class LoggerExtensions "There was an error uploading the blob with name '{blobName}'. {ex}" ); - private static readonly Action ERROR_BLOB_WITH_THE_KEY_EXISTS = + private static readonly Action ERROR_BLOB_WITH_THE_NAME_EXISTS = LoggerMessage.Define( LogLevel.Error, - new EventId(358892, "GoogleCloudStorage.ErrorBlobWithTheKeyExists"), - "The blob with the given key already exists." + new EventId(358892, "GoogleCloudStorage.ErrorBlobWithTheNameExists"), + "The blob with the given name already exists." ); private static readonly Action ERROR_DELETING_THE_BLOB_WITH_NAME = @@ -209,9 +209,9 @@ file static class LoggerExtensions "There was an error downloading the blob with name '{blobName}'. {ex}" ); - public static void ErrorDownloadingTheBlobWithKey(this ILogger logger, string blobId, Exception e) + public static void ErrorDownloadingTheBlobWithName(this ILogger logger, string blobId, Exception e) { - ERROR_DOWNLOADING_THE_BLOB_WITH_KEY(logger, blobId, e, e); + ERROR_DOWNLOADING_THE_BLOB_WITH_NAME(logger, blobId, e, e); } public static void ErrorListingAllTheBlobs(this ILogger logger, Exception e) @@ -224,9 +224,9 @@ public static void ErrorUploadingTheBlobWithName(this ILogger logger, string blo ERROR_UPLOADING_THE_BLOB_WITH_NAME(logger, blobName, e, e); } - public static void ErrorBlobWithTheKeyExists(this ILogger logger) + public static void ErrorBlobWithTheNameExists(this ILogger logger) { - ERROR_BLOB_WITH_THE_KEY_EXISTS(logger, default!); + ERROR_BLOB_WITH_THE_NAME_EXISTS(logger, default!); } public static void ErrorDeletingTheBlobWithName(this ILogger logger, string blobName, Exception e) From 471d3761af2e92b8f820490b43405a3b8aa7748d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Thu, 12 Oct 2023 13:50:46 +0200 Subject: [PATCH 019/133] feat: introduced log event ids --- .../Devices/Commands/ChangePassword/Handler.cs | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/Modules/Devices/src/Devices.Application/Devices/Commands/ChangePassword/Handler.cs b/Modules/Devices/src/Devices.Application/Devices/Commands/ChangePassword/Handler.cs index 5bbca64b9b..ce513561ec 100644 --- a/Modules/Devices/src/Devices.Application/Devices/Commands/ChangePassword/Handler.cs +++ b/Modules/Devices/src/Devices.Application/Devices/Commands/ChangePassword/Handler.cs @@ -33,6 +33,21 @@ public async Task Handle(ChangePasswordCommand request, CancellationToken cancel if (!changePasswordResult.Succeeded) throw new OperationFailedException(ApplicationErrors.Devices.ChangePasswordFailed(changePasswordResult.Errors.First().Description)); - _logger.LogTrace("Successfully changed password for device with id '{activeDevice}'.", _activeDevice); + _logger.ChangedPasswordForDeviceWithId(_activeDevice); + } +} + +file static class LoggerExtensions +{ + private static readonly Action CHANGED_PASSWORD_FOR_DEVICE_WITH_ID = + LoggerMessage.Define( + LogLevel.Information, + new EventId(277894, "ChangePassword.Handler.ChangedPasswordForDeviceWithId"), + "Successfully changed password for device with id '{activeDevice}'." + ); + + public static void ChangedPasswordForDeviceWithId(this ILogger logger, DeviceId activeDevice) + { + CHANGED_PASSWORD_FOR_DEVICE_WITH_ID(logger, activeDevice, default!); } } From c4083efcd0b3dc111d1c6257ba9667d2274eedd2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Thu, 12 Oct 2023 13:53:47 +0200 Subject: [PATCH 020/133] feat: introduced log event ids --- .../Devices/Commands/DeleteDevice/Handler.cs | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/Modules/Devices/src/Devices.Application/Devices/Commands/DeleteDevice/Handler.cs b/Modules/Devices/src/Devices.Application/Devices/Commands/DeleteDevice/Handler.cs index 87c7c2e2ec..39d6c5a6c6 100644 --- a/Modules/Devices/src/Devices.Application/Devices/Commands/DeleteDevice/Handler.cs +++ b/Modules/Devices/src/Devices.Application/Devices/Commands/DeleteDevice/Handler.cs @@ -2,6 +2,7 @@ using Backbone.Modules.Devices.Application.Infrastructure.Persistence.Repository; using Enmeshed.BuildingBlocks.Application.Abstractions.Exceptions; using Enmeshed.BuildingBlocks.Application.Abstractions.Infrastructure.UserContext; +using Enmeshed.DevelopmentKit.Identity.ValueObjects; using MediatR; using Microsoft.Extensions.Logging; @@ -39,6 +40,21 @@ public async Task Handle(DeleteDeviceCommand request, CancellationToken cancella await _identitiesRepository.Update(device, cancellationToken); - _logger.LogTrace("Successfully marked device with id '{deviceId}' as deleted.", request.DeviceId); + _logger.MarkDeviceWithIdAsDeleted(request.DeviceId); + } +} + +file static class LoggerExtensions +{ + private static readonly Action MARK_DEVICE_WITH_ID_AS_DELETED = + LoggerMessage.Define( + LogLevel.Information, + new EventId(776010, "DeleteDevice.Handler.MarkDeviceWithIdAsDeleted"), + "Successfully marked device with id '{deviceId}' as deleted." + ); + + public static void MarkDeviceWithIdAsDeleted(this ILogger logger, DeviceId deviceId) + { + MARK_DEVICE_WITH_ID_AS_DELETED(logger, deviceId, default!); } } From fb6355f74de8635a803f26c6b156c1e2689c7119 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Thu, 12 Oct 2023 13:57:28 +0200 Subject: [PATCH 021/133] feat: introduced log event ids --- .../Devices/Commands/RegisterDevice/Handler.cs | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/Modules/Devices/src/Devices.Application/Devices/Commands/RegisterDevice/Handler.cs b/Modules/Devices/src/Devices.Application/Devices/Commands/RegisterDevice/Handler.cs index ca00486294..6bf18eef3c 100644 --- a/Modules/Devices/src/Devices.Application/Devices/Commands/RegisterDevice/Handler.cs +++ b/Modules/Devices/src/Devices.Application/Devices/Commands/RegisterDevice/Handler.cs @@ -7,6 +7,7 @@ using Backbone.Modules.Devices.Domain.Entities; using Enmeshed.BuildingBlocks.Application.Abstractions.Exceptions; using Enmeshed.BuildingBlocks.Application.Abstractions.Infrastructure.UserContext; +using Enmeshed.DevelopmentKit.Identity.ValueObjects; using MediatR; using Microsoft.Extensions.Logging; @@ -39,7 +40,7 @@ public async Task Handle(RegisterDeviceCommand command, await _identitiesRepository.AddUser(user, command.DevicePassword); - _logger.LogTrace("Successfully created device. Device ID: '{deviceId}', User ID: {userId}, Username: {userName}", user.DeviceId, user.Id, user.UserName); + _logger.CreatedDevice(user.DeviceId, user.Id, user.UserName); return new RegisterDeviceResponse { @@ -109,3 +110,18 @@ public override void Write(Utf8JsonWriter writer, JsonSerializer.Serialize(writer, value, options); } } + +file static class LoggerExtensions +{ + private static readonly Action CREATED_DEVICE = + LoggerMessage.Define( + LogLevel.Information, + new EventId(219823, "RegisterDevice.Handler.CreatedDevice"), + "Successfully created device. Device ID: '{deviceId}', User ID: '{userId}', Username: '{userName}'." + ); + + public static void CreatedDevice(this ILogger logger, DeviceId deviceId, string userId, string userName) + { + CREATED_DEVICE(logger, deviceId, userId, userName, default!); + } +} From cee99ebc984858e626cbadffaae95be4f319f0b8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Thu, 12 Oct 2023 14:03:41 +0200 Subject: [PATCH 022/133] feat: introduced log event ids --- .../Commands/CreateIdentity/Handler.cs | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/Modules/Devices/src/Devices.Application/Identities/Commands/CreateIdentity/Handler.cs b/Modules/Devices/src/Devices.Application/Identities/Commands/CreateIdentity/Handler.cs index 7c26718f4a..68db45d88c 100644 --- a/Modules/Devices/src/Devices.Application/Identities/Commands/CreateIdentity/Handler.cs +++ b/Modules/Devices/src/Devices.Application/Identities/Commands/CreateIdentity/Handler.cs @@ -54,12 +54,10 @@ public async Task Handle(CreateIdentityCommand command, await _identitiesRepository.AddUser(user, command.DevicePassword); - _logger.LogTrace("Identity created. Address: '{address}', Device ID: {deviceId}, Username: {userName}", newIdentity.Address, user.DeviceId, user.UserName); + _logger.CreatedIdentity(newIdentity.Address, user.DeviceId, user.UserName); _eventBus.Publish(new IdentityCreatedIntegrationEvent(newIdentity)); - _logger.LogTrace("Successfully published IdentityCreatedIntegrationEvent. Identity Address: '{address}', Tier Id: {tierId}", newIdentity.Address, client.DefaultTier); - return new CreateIdentityResponse { Address = address, @@ -73,3 +71,18 @@ public async Task Handle(CreateIdentityCommand command, }; } } + +file static class LoggerExtensions +{ + private static readonly Action CREATED_IDENTITY = + LoggerMessage.Define( + LogLevel.Information, + new EventId(436321, "CreateIdentity.Handler.CreatedIdentity"), + "Identity created. Address: '{address}', Device ID: '{deviceId}', Username: '{userName}'." + ); + + public static void CreatedIdentity(this ILogger logger, IdentityAddress identityAddress, DeviceId deviceId, string userName) + { + CREATED_IDENTITY(logger, identityAddress, deviceId, userName, default!); + } +} From 049ba5b2057a42314bc1d0a93a6c2c19dbd46273 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Thu, 12 Oct 2023 14:09:40 +0200 Subject: [PATCH 023/133] feat: introduced log event ids --- .../Tiers/Commands/CreateTier/Handler.cs | 20 ++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/Modules/Devices/src/Devices.Application/Tiers/Commands/CreateTier/Handler.cs b/Modules/Devices/src/Devices.Application/Tiers/Commands/CreateTier/Handler.cs index d54d7881f5..8b25e63cc8 100644 --- a/Modules/Devices/src/Devices.Application/Tiers/Commands/CreateTier/Handler.cs +++ b/Modules/Devices/src/Devices.Application/Tiers/Commands/CreateTier/Handler.cs @@ -2,6 +2,7 @@ using Backbone.Modules.Devices.Application.IntegrationEvents.Outgoing; using Backbone.Modules.Devices.Domain.Aggregates.Tier; using Enmeshed.BuildingBlocks.Application.Abstractions.Infrastructure.EventBus; +using Enmeshed.DevelopmentKit.Identity.ValueObjects; using MediatR; using Microsoft.Extensions.Logging; using ApplicationException = Enmeshed.BuildingBlocks.Application.Abstractions.Exceptions.ApplicationException; @@ -33,12 +34,25 @@ public async Task Handle(CreateTierCommand request, Cancella await _tierRepository.AddAsync(tier, cancellationToken); - _logger.LogTrace("Successfully created tier. Tier ID: '{tierId}', Tier Name: {tierName}", tier.Id.Value, tier.Name.Value); + _logger.CreatedTier(tier.Id.Value, tier.Name.Value); _eventBus.Publish(new TierCreatedIntegrationEvent(tier)); - _logger.LogTrace("Successfully published TierCreatedIntegrationEvent. Tier ID: '{tierId}', Tier Name: {tierName}", tier.Id.Value, tier.Name.Value); - return new CreateTierResponse(tier.Id, tier.Name); } } + +file static class LoggerExtensions +{ + private static readonly Action CREATED_TIER = + LoggerMessage.Define( + LogLevel.Information, + new EventId(383136, "CreateTier.Handler.CreatedTier"), + "Successfully created tier. Tier ID: '{tierId}', Tier Name: {tierName}" + ); + + public static void CreatedTier(this ILogger logger, string tierId, string tierName) + { + CREATED_TIER(logger, tierId, tierName, default!); + } +} From 745f0aef481f9f293d220fe3c8452069575cbdab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Thu, 12 Oct 2023 14:34:45 +0200 Subject: [PATCH 024/133] feat: introduced log event ids --- .../AzureNotificationHubPushService.cs | 33 ++++++++++++++++--- 1 file changed, 29 insertions(+), 4 deletions(-) diff --git a/Modules/Devices/src/Devices.Infrastructure/PushNotifications/AzureNotificationHub/AzureNotificationHubPushService.cs b/Modules/Devices/src/Devices.Infrastructure/PushNotifications/AzureNotificationHub/AzureNotificationHubPushService.cs index 63defcb695..dde43654c5 100644 --- a/Modules/Devices/src/Devices.Infrastructure/PushNotifications/AzureNotificationHub/AzureNotificationHubPushService.cs +++ b/Modules/Devices/src/Devices.Infrastructure/PushNotifications/AzureNotificationHub/AzureNotificationHubPushService.cs @@ -39,7 +39,7 @@ public async Task UpdateRegistration(IdentityAddress address, DeviceId deviceId, await _notificationHubClient.CreateOrUpdateInstallationAsync(installation, cancellationToken); - _logger.LogTrace("New device successfully registered."); + _logger.DeviceRegistered(); } public async Task SendNotification(IdentityAddress recipient, object pushNotification, CancellationToken cancellationToken) @@ -58,8 +58,6 @@ public async Task SendNotification(IdentityAddress recipient, object pushNotific .Build(); await _notificationHubClient.SendNotificationAsync(notification, GetNotificationTags(recipient), cancellationToken); - - _logger.LogTrace("Successfully sent push notification to identity '{recipient}' on platform '{notificationPlatform}': {notification}", recipient, notificationPlatform, notification.ToJson()); } } @@ -74,7 +72,7 @@ public async Task DeleteRegistration(DeviceId deviceId, CancellationToken cancel else { await _notificationHubClient.DeleteInstallationAsync(deviceId, cancellationToken); - _logger.LogInformation("Unregistered device '{deviceId} from push notifications.", deviceId); + _logger.DeviceUnregistered(deviceId); } } @@ -117,3 +115,30 @@ public static string ToJson(this Notification notification) return JsonSerializer.Serialize(notification, SERIALIZER_OPTIONS); } } + +file static class LoggerExtensions +{ + private static readonly Action DEVICE_REGISTERED = + LoggerMessage.Define( + LogLevel.Information, + new EventId(585563, "AzureNotificationHubPushService.DeviceRegistered"), + "New device successfully registered." + ); + + private static readonly Action DEVICE_UNREGISTERED = + LoggerMessage.Define( + LogLevel.Information, + new EventId(767782, "AzureNotificationHubPushService.DeviceUnregistered"), + "Unregistered device '{deviceId}' from push notifications." + ); + + public static void DeviceRegistered(this ILogger logger) + { + DEVICE_REGISTERED(logger, default!); + } + + public static void DeviceUnregistered(this ILogger logger, DeviceId deviceId) + { + DEVICE_UNREGISTERED(logger, deviceId, default!); + } +} From 2a205723f7b9f77127bda7664a6246341d0c9f5e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Thu, 12 Oct 2023 15:07:46 +0200 Subject: [PATCH 025/133] feat: introduced log event ids --- .../DirectPush/DirectPushService.cs | 48 +++++++++++++++++-- 1 file changed, 43 insertions(+), 5 deletions(-) diff --git a/Modules/Devices/src/Devices.Infrastructure/PushNotifications/DirectPush/DirectPushService.cs b/Modules/Devices/src/Devices.Infrastructure/PushNotifications/DirectPush/DirectPushService.cs index b0b66dee81..8dcf609ff0 100644 --- a/Modules/Devices/src/Devices.Infrastructure/PushNotifications/DirectPush/DirectPushService.cs +++ b/Modules/Devices/src/Devices.Infrastructure/PushNotifications/DirectPush/DirectPushService.cs @@ -49,14 +49,12 @@ private async Task HandleNotificationResponses(SendResults sendResults) switch (sendResult.Error.Reason) { case ErrorReason.InvalidHandle: - _logger.LogInformation("Deleting device registration for '{deviceId}' since handle is no longer valid.", sendResult.DeviceId); + _logger.DeletingDeviceRegistration(sendResult.DeviceId); deviceIdsToDelete.Add(sendResult.DeviceId); break; case ErrorReason.Unexpected: - _logger.LogError( - "The following error occurred while trying to send the notification for '{deviceId}': '{error}'", - sendResult.DeviceId, sendResult.Error.Message); + _logger.ErrorWhileTryingToSendNotification(sendResult.DeviceId, sendResult.Error.Message); break; default: throw new ArgumentOutOfRangeException($"Reason '{sendResult.Error.Reason}' not supported"); @@ -94,6 +92,7 @@ public async Task UpdateRegistration(IdentityAddress address, DeviceId deviceId, } catch (InfrastructureException exception) when (exception.Code == InfrastructureErrors.UniqueKeyViolation().Code) { + // This exception can be ignored. It is only thrown in case of a concurrent registration request from multiple devices. _logger.LogInformation(exception.Message); } } @@ -110,7 +109,46 @@ public async Task DeleteRegistration(DeviceId deviceId, CancellationToken cancel else { await _pnsRegistrationRepository.Delete(new List { deviceId }, cancellationToken); - _logger.LogInformation("Unregistered device '{deviceId} from push notifications.", deviceId); + _logger.UnregisteredDevice(deviceId); } } } + +file static class LoggerExtensions +{ + private static readonly Action DELETING_DEVICE_REGISTRATION = + LoggerMessage.Define( + LogLevel.Information, + new EventId(950845, "DirectPushService.DeletingDeviceRegistration"), + "Deleting device registration for '{deviceId}' since handle is no longer valid." + ); + + private static readonly Action ERROR_WHILE_TRYING_TO_SEND_NOTIFICATION = + LoggerMessage.Define( + LogLevel.Error, + new EventId(624412, "DirectPushService.ErrorWhileTryingToSendNotification"), + "The following error occurred while trying to send the notification for '{deviceId}': '{error}'." + ); + + private static readonly Action UNREGISTERED_DEVICE = + LoggerMessage.Define( + LogLevel.Information, + new EventId(628738, "DirectPushService.UnregisteredDevice"), + "Unregistered device '{deviceId} from push notifications." + ); + + public static void DeletingDeviceRegistration(this ILogger logger, DeviceId deviceId) + { + DELETING_DEVICE_REGISTRATION(logger, deviceId, default!); + } + + public static void ErrorWhileTryingToSendNotification(this ILogger logger, DeviceId deviceId, string error) + { + ERROR_WHILE_TRYING_TO_SEND_NOTIFICATION(logger, deviceId, error, default!); + } + + public static void UnregisteredDevice(this ILogger logger, DeviceId deviceId) + { + UNREGISTERED_DEVICE(logger, deviceId, default!); + } +} From 904597785da8b055e501b0e498090fc78a85ad3a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Thu, 12 Oct 2023 15:21:21 +0200 Subject: [PATCH 026/133] feat: introduced log event ids --- .../Infrastructure/Reporter/LogReporter.cs | 31 +++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/Modules/Files/src/Files.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs b/Modules/Files/src/Files.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs index 3a456e34d9..ae6aab49d6 100644 --- a/Modules/Files/src/Files.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs +++ b/Modules/Files/src/Files.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs @@ -20,12 +20,12 @@ public void Complete() { foreach (var databaseId in _databaseIds) { - _logger.LogError("no blob found for file id: '{databaseId}'", databaseId); + _logger.NoBlobForFileId(databaseId); } foreach (var blobId in _blobIds) { - _logger.LogError("no database entry found for blob id: '{blobId}'", blobId); + _logger.NoDatabaseEntryForBlobId(blobId); } } @@ -39,3 +39,30 @@ public void ReportOrphanedDatabaseId(FileId id) _databaseIds.Add(id); } } + +file static class LoggerExtensions +{ + private static readonly Action NO_BLOB_FOR_FILE_ID = + LoggerMessage.Define( + LogLevel.Error, + new EventId(629592, "SanityCheck.NoBlobForFileId"), + "No blob found for file id: '{databaseId}'." + ); + + private static readonly Action NO_DATABASE_ENTRY_FOR_BLOB_ID = + LoggerMessage.Define( + LogLevel.Error, + new EventId(487180, "SanityCheck.NoDatabaseEntryForBlobId"), + "No database entry found for blob id: '{blobId}'." + ); + + public static void NoBlobForFileId(this ILogger logger, FileId fileId) + { + NO_BLOB_FOR_FILE_ID(logger, fileId, default!); + } + + public static void NoDatabaseEntryForBlobId(this ILogger logger, string blobId) + { + NO_DATABASE_ENTRY_FOR_BLOB_ID(logger, blobId, default!); + } +} From 22a73e1f7852729d615cb18fca603875fed74841 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Thu, 12 Oct 2023 15:25:41 +0200 Subject: [PATCH 027/133] chore: updated log event names --- .../Infrastructure/Reporter/LogReporter.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Modules/Files/src/Files.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs b/Modules/Files/src/Files.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs index ae6aab49d6..d83ac8dd31 100644 --- a/Modules/Files/src/Files.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs +++ b/Modules/Files/src/Files.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs @@ -45,14 +45,14 @@ file static class LoggerExtensions private static readonly Action NO_BLOB_FOR_FILE_ID = LoggerMessage.Define( LogLevel.Error, - new EventId(629592, "SanityCheck.NoBlobForFileId"), + new EventId(629592, "Files.SanityCheck.NoBlobForFileId"), "No blob found for file id: '{databaseId}'." ); private static readonly Action NO_DATABASE_ENTRY_FOR_BLOB_ID = LoggerMessage.Define( LogLevel.Error, - new EventId(487180, "SanityCheck.NoDatabaseEntryForBlobId"), + new EventId(487180, "Files.SanityCheck.NoDatabaseEntryForBlobId"), "No database entry found for blob id: '{blobId}'." ); From 0551bacac38fb07cdd03c1b87c64e0ba1af2a2d7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Thu, 12 Oct 2023 15:28:18 +0200 Subject: [PATCH 028/133] feat: introduced log event ids --- .../Infrastructure/Reporter/LogReporter.cs | 31 +++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/Modules/Messages/src/Messages.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs b/Modules/Messages/src/Messages.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs index 6a4c3b549c..3032b894dc 100644 --- a/Modules/Messages/src/Messages.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs +++ b/Modules/Messages/src/Messages.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs @@ -20,12 +20,12 @@ public void Complete() { foreach (var databaseId in _databaseIds) { - _logger.LogError("no blob found for message id: '{databaseId}'", databaseId); + _logger.NoBlobForMessageId(databaseId); } foreach (var blobId in _blobIds) { - _logger.LogError("no database entry found for blob id: '{blobId}'", blobId); + _logger.NoDatabaseEntryForBlobId(blobId); } } @@ -39,3 +39,30 @@ public void ReportOrphanedDatabaseId(MessageId id) _databaseIds.Add(id); } } + +file static class LoggerExtensions +{ + private static readonly Action NO_BLOB_FOR_MESSAGE_ID = + LoggerMessage.Define( + LogLevel.Error, + new EventId(859729, "Messages.SanityCheck.NoBlobForMessageId"), + "No blob found for file id: '{databaseId}'." + ); + + private static readonly Action NO_DATABASE_ENTRY_FOR_BLOB_ID = + LoggerMessage.Define( + LogLevel.Error, + new EventId(809167, "Messages.SanityCheck.NoDatabaseEntryForBlobId"), + "No database entry found for blob id: '{blobId}'." + ); + + public static void NoBlobForMessageId(this ILogger logger, MessageId messageId) + { + NO_BLOB_FOR_MESSAGE_ID(logger, messageId, default!); + } + + public static void NoDatabaseEntryForBlobId(this ILogger logger, string blobId) + { + NO_DATABASE_ENTRY_FOR_BLOB_ID(logger, blobId, default!); + } +} From a5bd7808e55d5d4a49ce2d81dcd764e487715a09 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Thu, 12 Oct 2023 15:29:28 +0200 Subject: [PATCH 029/133] chore: updated missing and redundant single quotes --- .../Messages/Commands/SendMessage/Handler.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Modules/Messages/src/Messages.Application/Messages/Commands/SendMessage/Handler.cs b/Modules/Messages/src/Messages.Application/Messages/Commands/SendMessage/Handler.cs index 944c1a9545..320406bbb7 100644 --- a/Modules/Messages/src/Messages.Application/Messages/Commands/SendMessage/Handler.cs +++ b/Modules/Messages/src/Messages.Application/Messages/Commands/SendMessage/Handler.cs @@ -72,7 +72,7 @@ private async Task> ValidateRecipients(SendMessageCom if (idOfRelationshipBetweenSenderAndRecipient == null) { - _logger.LogInformation("Sending message aborted. There is no relationship between sender ('{sender}') and recipient ({recipient}).", sender, recipientDto.Address); + _logger.LogInformation("Sending message aborted. There is no relationship between sender ({sender}) and recipient ({recipient}).", sender, recipientDto.Address); throw new OperationFailedException(ApplicationErrors.NoRelationshipToRecipientExists(recipientDto.Address)); } @@ -81,7 +81,7 @@ private async Task> ValidateRecipients(SendMessageCom if (numberOfUnreceivedMessagesFromActiveIdentity >= _options.MaxNumberOfUnreceivedMessagesFromOneSender) { _logger.LogInformation( - "Sending message aborted. Recipient {recipient} already has {numberOfUnreceivedMessagesFromActiveIdentity} unreceived messages from sender {sender}, which is more than the maximum ({maxNumberOfUnreceivedMessagesFromOneSender}).", + "Sending message aborted. Recipient '{recipient}' already has '{numberOfUnreceivedMessagesFromActiveIdentity}' unreceived messages from sender '{sender}', which is more than the maximum ({maxNumberOfUnreceivedMessagesFromOneSender}).", recipientDto.Address, numberOfUnreceivedMessagesFromActiveIdentity, sender, _options.MaxNumberOfUnreceivedMessagesFromOneSender); throw new OperationFailedException(ApplicationErrors.MaxNumberOfUnreceivedMessagesReached(recipientDto.Address)); From 0d01fdff57ea5467bd0e13f610a1a211cc4ee023 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Fri, 13 Oct 2023 09:22:35 +0200 Subject: [PATCH 030/133] chore: removed unused directives --- .../src/Devices.Application/Tiers/Commands/CreateTier/Handler.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/Modules/Devices/src/Devices.Application/Tiers/Commands/CreateTier/Handler.cs b/Modules/Devices/src/Devices.Application/Tiers/Commands/CreateTier/Handler.cs index 8b25e63cc8..6477643c75 100644 --- a/Modules/Devices/src/Devices.Application/Tiers/Commands/CreateTier/Handler.cs +++ b/Modules/Devices/src/Devices.Application/Tiers/Commands/CreateTier/Handler.cs @@ -2,7 +2,6 @@ using Backbone.Modules.Devices.Application.IntegrationEvents.Outgoing; using Backbone.Modules.Devices.Domain.Aggregates.Tier; using Enmeshed.BuildingBlocks.Application.Abstractions.Infrastructure.EventBus; -using Enmeshed.DevelopmentKit.Identity.ValueObjects; using MediatR; using Microsoft.Extensions.Logging; using ApplicationException = Enmeshed.BuildingBlocks.Application.Abstractions.Exceptions.ApplicationException; From 4328d1520f8b719a8229b9e705371634f7472e86 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Fri, 13 Oct 2023 09:33:22 +0200 Subject: [PATCH 031/133] feat: introduced log event ids --- .../IdentityCreatedIntegrationEventHandler.cs | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/Modules/Quotas/src/Quotas.Application/IntegrationEvents/Incoming/IdentityCreated/IdentityCreatedIntegrationEventHandler.cs b/Modules/Quotas/src/Quotas.Application/IntegrationEvents/Incoming/IdentityCreated/IdentityCreatedIntegrationEventHandler.cs index 4f4a4f6e9e..01ff76e360 100644 --- a/Modules/Quotas/src/Quotas.Application/IntegrationEvents/Incoming/IdentityCreated/IdentityCreatedIntegrationEventHandler.cs +++ b/Modules/Quotas/src/Quotas.Application/IntegrationEvents/Incoming/IdentityCreated/IdentityCreatedIntegrationEventHandler.cs @@ -3,6 +3,7 @@ using Backbone.Modules.Quotas.Domain.Aggregates.Tiers; using Backbone.Modules.Quotas.Domain.Metrics; using Enmeshed.BuildingBlocks.Application.Abstractions.Infrastructure.EventBus; +using Enmeshed.DevelopmentKit.Identity.ValueObjects; using Microsoft.Extensions.Logging; namespace Backbone.Modules.Quotas.Application.IntegrationEvents.Incoming.IdentityCreated; @@ -39,8 +40,21 @@ public async Task Handle(IdentityCreatedIntegrationEvent integrationEvent) await _identitiesRepository.Add(identity, CancellationToken.None); - _logger.LogTrace("Successfully created identity. Identity Address: '{address}', Tier ID: {tierId}", identity.Address, identity.TierId); + _logger.IdentityCreated(identity.Address, identity.TierId); + } +} - _logger.LogTrace("'{quotasCount}' Tier Quotas created for Identity: {identityAddress} ", tier.Quotas.Count, identity.Address); +file static class LoggerExtensions +{ + private static readonly Action IDENTITY_CREATED = + LoggerMessage.Define( + LogLevel.Information, + new EventId(811934, "IdentityCreatedIntegrationEventHandler.IdentityCreated"), + "Successfully created identity. Identity Address: '{address}', Tier ID: '{tierId}'." + ); + + public static void IdentityCreated(this ILogger logger, string address, TierId tierId) + { + IDENTITY_CREATED(logger, address, tierId, default!); } } From b6878d8d125b346ce6a202981f671c5db8dbf028 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Fri, 13 Oct 2023 09:36:51 +0200 Subject: [PATCH 032/133] feat: introduced log event ids --- .../TierCreatedIntegrationEventHandler.cs | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/Modules/Quotas/src/Quotas.Application/IntegrationEvents/Incoming/TierCreated/TierCreatedIntegrationEventHandler.cs b/Modules/Quotas/src/Quotas.Application/IntegrationEvents/Incoming/TierCreated/TierCreatedIntegrationEventHandler.cs index 2f8a9b4283..33f109d4fd 100644 --- a/Modules/Quotas/src/Quotas.Application/IntegrationEvents/Incoming/TierCreated/TierCreatedIntegrationEventHandler.cs +++ b/Modules/Quotas/src/Quotas.Application/IntegrationEvents/Incoming/TierCreated/TierCreatedIntegrationEventHandler.cs @@ -20,7 +20,21 @@ public async Task Handle(TierCreatedIntegrationEvent integrationEvent) var tier = new Tier(new TierId(integrationEvent.Id), integrationEvent.Name); await _tierRepository.Add(tier, CancellationToken.None); - _logger.LogTrace("Successfully created tier. Tier ID: '{tierId}', Tier Name: {tierName}", tier.Id, tier.Name); + _logger.TierCreated(tier.Id, tier.Name); } } +file static class LoggerExtensions +{ + private static readonly Action TIER_CREATED = + LoggerMessage.Define( + LogLevel.Information, + new EventId(151788, "TierCreatedIntegrationEventHandler.TierCreated"), + "Successfully created tier. Tier ID: '{tierId}', Tier Name: '{tierName}'." + ); + + public static void TierCreated(this ILogger logger, TierId tierId, string name) + { + TIER_CREATED(logger, tierId, name, default!); + } +} From 721b31490c2e45bccce5307dd2ce31c79320e37b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Fri, 13 Oct 2023 09:37:32 +0200 Subject: [PATCH 033/133] chore: typos --- .../QuotaCreatedForTierIntegrationEventHandler.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Modules/Quotas/src/Quotas.Application/IntegrationEvents/Incoming/QuotaCreatedForTier/QuotaCreatedForTierIntegrationEventHandler.cs b/Modules/Quotas/src/Quotas.Application/IntegrationEvents/Incoming/QuotaCreatedForTier/QuotaCreatedForTierIntegrationEventHandler.cs index 8799129a2b..65308ee640 100644 --- a/Modules/Quotas/src/Quotas.Application/IntegrationEvents/Incoming/QuotaCreatedForTier/QuotaCreatedForTierIntegrationEventHandler.cs +++ b/Modules/Quotas/src/Quotas.Application/IntegrationEvents/Incoming/QuotaCreatedForTier/QuotaCreatedForTierIntegrationEventHandler.cs @@ -25,13 +25,13 @@ public QuotaCreatedForTierIntegrationEventHandler(IIdentitiesRepository identiti public async Task Handle(QuotaCreatedForTierIntegrationEvent @event) { - _logger.LogTrace("Handling QuotaCreatedForTierIntegrationEvent ... "); + _logger.LogTrace("Handling QuotaCreatedForTierIntegrationEvent..."); var identitiesWithTier = await _identitiesRepository.FindWithTier(new TierId(@event.TierId), CancellationToken.None, true); if (!identitiesWithTier.Any()) { - _logger.LogTrace("No identities found with tier ID: '{tierId}'", @event.TierId); + _logger.LogTrace("No identities found with tier ID: '{tierId}'.", @event.TierId); return; } @@ -48,6 +48,6 @@ public async Task Handle(QuotaCreatedForTierIntegrationEvent @event) var metrics = new List { tierQuotaDefinition.MetricKey.Value }; await _metricStatusesService.RecalculateMetricStatuses(identityAddresses, metrics, CancellationToken.None); - _logger.LogTrace("Successfully created quotas for Identities!"); + _logger.LogInformation("Successfully created quotas for Identities."); } } From f6e485917a608659dcfdecf85b42c207a398d7c8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Fri, 13 Oct 2023 09:41:18 +0200 Subject: [PATCH 034/133] feat: introduced log event ids --- .../TierDeletedIntegrationEventHandler.cs | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/Modules/Quotas/src/Quotas.Application/IntegrationEvents/Incoming/TierDeleted/TierDeletedIntegrationEventHandler.cs b/Modules/Quotas/src/Quotas.Application/IntegrationEvents/Incoming/TierDeleted/TierDeletedIntegrationEventHandler.cs index b529a62818..5c94d457cd 100644 --- a/Modules/Quotas/src/Quotas.Application/IntegrationEvents/Incoming/TierDeleted/TierDeletedIntegrationEventHandler.cs +++ b/Modules/Quotas/src/Quotas.Application/IntegrationEvents/Incoming/TierDeleted/TierDeletedIntegrationEventHandler.cs @@ -1,4 +1,5 @@ using Backbone.Modules.Quotas.Application.Infrastructure.Persistence.Repository; +using Backbone.Modules.Quotas.Domain.Aggregates.Tiers; using Enmeshed.BuildingBlocks.Application.Abstractions.Infrastructure.EventBus; using Microsoft.Extensions.Logging; @@ -20,7 +21,21 @@ public async Task Handle(TierDeletedIntegrationEvent integrationEvent) await _tiersRepository.RemoveById(tier.Id); - _logger.LogTrace("Successfully deleted tier. Tier ID: '{tierId}', Tier Name: {tierName}", tier.Id, tier.Name); + _logger.TierDeleted(tier.Id, tier.Name); } } +file static class LoggerExtensions +{ + private static readonly Action TIER_DELETED = + LoggerMessage.Define( + LogLevel.Information, + new EventId(582359, "TierDeletedIntegrationEventHandler.TierDeleted"), + "Successfully deleted tier. Tier ID: '{tierId}', Tier Name: '{tierName}'." + ); + + public static void TierDeleted(this ILogger logger, TierId tierId, string name) + { + TIER_DELETED(logger, tierId, name, default!); + } +} From 2ad128bd211b865e4798f902970aad60ce191717 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Fri, 13 Oct 2023 09:41:57 +0200 Subject: [PATCH 035/133] chore: removed unused directives --- .../IdentityCreated/IdentityCreatedIntegrationEventHandler.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/Modules/Quotas/src/Quotas.Application/IntegrationEvents/Incoming/IdentityCreated/IdentityCreatedIntegrationEventHandler.cs b/Modules/Quotas/src/Quotas.Application/IntegrationEvents/Incoming/IdentityCreated/IdentityCreatedIntegrationEventHandler.cs index 01ff76e360..6746fe3ae5 100644 --- a/Modules/Quotas/src/Quotas.Application/IntegrationEvents/Incoming/IdentityCreated/IdentityCreatedIntegrationEventHandler.cs +++ b/Modules/Quotas/src/Quotas.Application/IntegrationEvents/Incoming/IdentityCreated/IdentityCreatedIntegrationEventHandler.cs @@ -3,7 +3,6 @@ using Backbone.Modules.Quotas.Domain.Aggregates.Tiers; using Backbone.Modules.Quotas.Domain.Metrics; using Enmeshed.BuildingBlocks.Application.Abstractions.Infrastructure.EventBus; -using Enmeshed.DevelopmentKit.Identity.ValueObjects; using Microsoft.Extensions.Logging; namespace Backbone.Modules.Quotas.Application.IntegrationEvents.Incoming.IdentityCreated; From 67062a8651e70b46984b1b147333a8764c9c912d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Fri, 13 Oct 2023 09:45:11 +0200 Subject: [PATCH 036/133] feat: introduced log event ids --- ...efinitionDeletedIntegrationEventHandler.cs | 21 ++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/Modules/Quotas/src/Quotas.Application/IntegrationEvents/Incoming/TierQuotaDefinitionDeleted/TierQuotaDefinitionDeletedIntegrationEventHandler.cs b/Modules/Quotas/src/Quotas.Application/IntegrationEvents/Incoming/TierQuotaDefinitionDeleted/TierQuotaDefinitionDeletedIntegrationEventHandler.cs index b46065bee5..45d1112174 100644 --- a/Modules/Quotas/src/Quotas.Application/IntegrationEvents/Incoming/TierQuotaDefinitionDeleted/TierQuotaDefinitionDeletedIntegrationEventHandler.cs +++ b/Modules/Quotas/src/Quotas.Application/IntegrationEvents/Incoming/TierQuotaDefinitionDeleted/TierQuotaDefinitionDeletedIntegrationEventHandler.cs @@ -21,13 +21,13 @@ public TierQuotaDefinitionDeletedIntegrationEventHandler(IIdentitiesRepository i public async Task Handle(TierQuotaDefinitionDeletedIntegrationEvent @event) { - _logger.LogTrace("Handling '{eventName}' ... ", nameof(TierQuotaDefinitionDeletedIntegrationEvent)); + _logger.LogTrace("Handling '{eventName}'... ", nameof(TierQuotaDefinitionDeletedIntegrationEvent)); var identitiesWithTier = await _identitiesRepository.FindWithTier(new TierId(@event.TierId), CancellationToken.None, true); if (!identitiesWithTier.Any()) { - _logger.LogTrace("No identities found with tier ID: '{tierId}'", @event.TierId); + _logger.LogTrace("No identities found with tier ID: '{tierId}'.", @event.TierId); return; } @@ -40,6 +40,21 @@ public async Task Handle(TierQuotaDefinitionDeletedIntegrationEvent @event) await _identitiesRepository.Update(identitiesWithTier, CancellationToken.None); - _logger.LogTrace("Successfully deleted quotas for Identities."); + _logger.DeletedQuotasForIdentities(); + } +} + +file static class LoggerExtensions +{ + private static readonly Action DELETED_QUOTAS_FOR_IDENTITIES = + LoggerMessage.Define( + LogLevel.Information, + new EventId(942996, "TierQuotaDefinitionDeletedIntegrationEventHandler.DeletedQuotasForIdentities"), + "Successfully deleted quotas for Identities." + ); + + public static void DeletedQuotasForIdentities(this ILogger logger) + { + DELETED_QUOTAS_FOR_IDENTITIES(logger, default!); } } From b9f8edea32a649301133e431ca18b61f07e524ad Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Fri, 13 Oct 2023 09:49:50 +0200 Subject: [PATCH 037/133] feat: introduced log event ids --- .../Commands/CreateQuotaForIdentity/Handler.cs | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/Modules/Quotas/src/Quotas.Application/Tiers/Commands/CreateQuotaForIdentity/Handler.cs b/Modules/Quotas/src/Quotas.Application/Tiers/Commands/CreateQuotaForIdentity/Handler.cs index 3110450878..939b901aa7 100644 --- a/Modules/Quotas/src/Quotas.Application/Tiers/Commands/CreateQuotaForIdentity/Handler.cs +++ b/Modules/Quotas/src/Quotas.Application/Tiers/Commands/CreateQuotaForIdentity/Handler.cs @@ -39,7 +39,7 @@ public async Task Handle(CreateQuotaForIdentityCommand reque await _identitiesRepository.Update(identity, cancellationToken); - _logger.LogTrace("Successfully created Quota for Identity. Identity Address: '{identityAddress}'", identity.Address); + _logger.CreatedQuotasForIdentities(identity.Address); var identityAddresses = new List { identity.Address }; var metrics = new List { metric.Key.Value }; @@ -49,3 +49,18 @@ public async Task Handle(CreateQuotaForIdentityCommand reque return response; } } + +file static class LoggerExtensions +{ + private static readonly Action CREATED_QUOTAS_FOR_IDENTITY = + LoggerMessage.Define( + LogLevel.Information, + new EventId(868289, "CreateQuotaForIdentity.Handler.CreatedQuotasForIdentities"), + "Successfully created Quota for Identity. Identity Address: '{identityAddress}'." + ); + + public static void CreatedQuotasForIdentities(this ILogger logger, string identityAddress) + { + CREATED_QUOTAS_FOR_IDENTITY(logger, identityAddress, default!); + } +} From c9a3a86f6b08e860fbe9275ec60f653b7ecec82f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Fri, 13 Oct 2023 09:57:58 +0200 Subject: [PATCH 038/133] feat: introduced log event ids --- .../Commands/CreateQuotaForTier/Handler.cs | 22 +++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/Modules/Quotas/src/Quotas.Application/Tiers/Commands/CreateQuotaForTier/Handler.cs b/Modules/Quotas/src/Quotas.Application/Tiers/Commands/CreateQuotaForTier/Handler.cs index b31592f4ee..1e53daefe4 100644 --- a/Modules/Quotas/src/Quotas.Application/Tiers/Commands/CreateQuotaForTier/Handler.cs +++ b/Modules/Quotas/src/Quotas.Application/Tiers/Commands/CreateQuotaForTier/Handler.cs @@ -1,6 +1,7 @@ using Backbone.Modules.Quotas.Application.DTOs; using Backbone.Modules.Quotas.Application.Infrastructure.Persistence.Repository; using Backbone.Modules.Quotas.Application.IntegrationEvents.Outgoing; +using Backbone.Modules.Quotas.Domain.Aggregates.Tiers; using Enmeshed.BuildingBlocks.Application.Abstractions.Infrastructure.EventBus; using Enmeshed.BuildingBlocks.Domain; using MediatR; @@ -26,7 +27,7 @@ public Handler(ITiersRepository tierRepository, ILogger logger, IEventB public async Task Handle(CreateQuotaForTierCommand request, CancellationToken cancellationToken) { - _logger.LogInformation("Handling CreateQuotaForTierCommand ..."); + _logger.LogTrace("Handling CreateQuotaForTierCommand ..."); var tier = await _tiersRepository.Find(request.TierId, cancellationToken, true); @@ -43,13 +44,26 @@ public async Task Handle(CreateQuotaForTierCommand reque await _tiersRepository.Update(tier, cancellationToken); - _logger.LogTrace("Successfully created assigned Quota to Tier. Tier ID: '{tierId}', Tier Name: {tierName}", tier.Id, tier.Name); + _logger.CreatedQuotaToTier(tier.Id, tier.Name); _eventBus.Publish(new QuotaCreatedForTierIntegrationEvent(tier.Id, result.Value.Id)); - _logger.LogTrace("Successfully published QuotaCreatedForTierIntegrationEvent. Tier ID: '{tierId}', Tier Name: {tierName}", tier.Id, tier.Name); - var response = new TierQuotaDefinitionDTO(result.Value.Id, new MetricDTO(metric), result.Value.Max, result.Value.Period); return response; } } + +file static class LoggerExtensions +{ + private static readonly Action CREATED_QUOTA_TO_TIER = + LoggerMessage.Define( + LogLevel.Information, + new EventId(346835, "CreateQuotaForTier.Handler.CreatedQuotaToTier"), + "Successfully created Quota to Tier. Tier ID: '{tierId}', Tier Name: '{tierName}'." + ); + + public static void CreatedQuotaToTier(this ILogger logger, TierId tierId, string identityAddress) + { + CREATED_QUOTA_TO_TIER(logger, tierId, identityAddress, default!); + } +} From 0d2c08954d4114079f27c3881bbd12aab4c7a41d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Fri, 13 Oct 2023 09:59:10 +0200 Subject: [PATCH 039/133] chore: typos --- .../Tiers/Commands/CreateQuotaForTier/Handler.cs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Modules/Quotas/src/Quotas.Application/Tiers/Commands/CreateQuotaForTier/Handler.cs b/Modules/Quotas/src/Quotas.Application/Tiers/Commands/CreateQuotaForTier/Handler.cs index 1e53daefe4..b98fb253b7 100644 --- a/Modules/Quotas/src/Quotas.Application/Tiers/Commands/CreateQuotaForTier/Handler.cs +++ b/Modules/Quotas/src/Quotas.Application/Tiers/Commands/CreateQuotaForTier/Handler.cs @@ -44,7 +44,7 @@ public async Task Handle(CreateQuotaForTierCommand reque await _tiersRepository.Update(tier, cancellationToken); - _logger.CreatedQuotaToTier(tier.Id, tier.Name); + _logger.CreatedQuotaForTier(tier.Id, tier.Name); _eventBus.Publish(new QuotaCreatedForTierIntegrationEvent(tier.Id, result.Value.Id)); @@ -55,15 +55,15 @@ public async Task Handle(CreateQuotaForTierCommand reque file static class LoggerExtensions { - private static readonly Action CREATED_QUOTA_TO_TIER = + private static readonly Action CREATED_QUOTA_FOR_TIER = LoggerMessage.Define( LogLevel.Information, - new EventId(346835, "CreateQuotaForTier.Handler.CreatedQuotaToTier"), - "Successfully created Quota to Tier. Tier ID: '{tierId}', Tier Name: '{tierName}'." + new EventId(346835, "CreateQuotaForTier.Handler.CreatedQuotaForTier"), + "Successfully created Quota for Tier. Tier ID: '{tierId}', Tier Name: '{tierName}'." ); - public static void CreatedQuotaToTier(this ILogger logger, TierId tierId, string identityAddress) + public static void CreatedQuotaForTier(this ILogger logger, TierId tierId, string identityAddress) { - CREATED_QUOTA_TO_TIER(logger, tierId, identityAddress, default!); + CREATED_QUOTA_FOR_TIER(logger, tierId, identityAddress, default!); } } From 736a1131f1d7eabf5440347501d0af4e7391e8ab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Fri, 13 Oct 2023 10:10:05 +0200 Subject: [PATCH 040/133] feat: introduced log event ids --- .../Commands/DeleteQuotaForIdentity/Handler.cs | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/Modules/Quotas/src/Quotas.Application/Tiers/Commands/DeleteQuotaForIdentity/Handler.cs b/Modules/Quotas/src/Quotas.Application/Tiers/Commands/DeleteQuotaForIdentity/Handler.cs index fb55c104bd..c26cc2a7a4 100644 --- a/Modules/Quotas/src/Quotas.Application/Tiers/Commands/DeleteQuotaForIdentity/Handler.cs +++ b/Modules/Quotas/src/Quotas.Application/Tiers/Commands/DeleteQuotaForIdentity/Handler.cs @@ -33,6 +33,21 @@ public async Task Handle(DeleteQuotaForIdentityCommand request, CancellationToke await _identitiesRepository.Update(identity, cancellationToken); - _logger.LogTrace("Successfully deleted individual quota with id: '{individualQuotaId}'.", request.IndividualQuotaId); + _logger.DeletedQuota(request.IndividualQuotaId); + } +} + +file static class LoggerExtensions +{ + private static readonly Action DELETED_QUOTA = + LoggerMessage.Define( + LogLevel.Information, + new EventId(247156, "DeleteQuotaForIdentity.Handler.DeletedQuota"), + "Successfully deleted individual quota with id: '{individualQuotaId}'." + ); + + public static void DeletedQuota(this ILogger logger, string IndividualQuotaId) + { + DELETED_QUOTA(logger, IndividualQuotaId, default!); } } From 8d8e323cc19e52487c8a614ae765cf1b966ed6dd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Fri, 13 Oct 2023 10:12:17 +0200 Subject: [PATCH 041/133] feat: introduced log event ids --- .../DeleteTierQuotaDefinition/Handler.cs | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/Modules/Quotas/src/Quotas.Application/Tiers/Commands/DeleteTierQuotaDefinition/Handler.cs b/Modules/Quotas/src/Quotas.Application/Tiers/Commands/DeleteTierQuotaDefinition/Handler.cs index f8d86b39a7..e1c2573c08 100644 --- a/Modules/Quotas/src/Quotas.Application/Tiers/Commands/DeleteTierQuotaDefinition/Handler.cs +++ b/Modules/Quotas/src/Quotas.Application/Tiers/Commands/DeleteTierQuotaDefinition/Handler.cs @@ -33,11 +33,23 @@ public async Task Handle(DeleteTierQuotaDefinitionCommand request, CancellationT await _tiersRepository.Update(tier, cancellationToken); - _logger.LogTrace("Successfully deleted tier quota definition with id: '{tierQuotaDefinitionId}'.", request.TierQuotaDefinitionId); + _logger.DeletedTierQuota(request.TierQuotaDefinitionId); _eventBus.Publish(new TierQuotaDefinitionDeletedIntegrationEvent(tier.Id, request.TierQuotaDefinitionId)); + } +} - _logger.LogTrace("Successfully published '{tierQuotaDefinitionDeletedIntegrationEvent}' with id: '{tierQuotaDefinitionId}' and tier id: '{tierId}'", - nameof(TierQuotaDefinitionDeletedIntegrationEvent), request.TierQuotaDefinitionId, request.TierId); +file static class LoggerExtensions +{ + private static readonly Action DELETED_TIER_QUOTA = + LoggerMessage.Define( + LogLevel.Information, + new EventId(247156, "DeleteTierQuotaDefinition.Handler.DeletedTierQuota"), + "Successfully deleted tier quota definition with id: '{tierQuotaDefinitionId}'." + ); + + public static void DeletedTierQuota(this ILogger logger, string tierQuotaDefinitionId) + { + DELETED_TIER_QUOTA(logger, tierQuotaDefinitionId, default!); } } From 25599eb302ea26c5209627b1ae308e1c494e6af0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Fri, 13 Oct 2023 10:12:56 +0200 Subject: [PATCH 042/133] chore: parameter name starting with upper case fix --- .../Tiers/Commands/DeleteQuotaForIdentity/Handler.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Modules/Quotas/src/Quotas.Application/Tiers/Commands/DeleteQuotaForIdentity/Handler.cs b/Modules/Quotas/src/Quotas.Application/Tiers/Commands/DeleteQuotaForIdentity/Handler.cs index c26cc2a7a4..45e04cc0b0 100644 --- a/Modules/Quotas/src/Quotas.Application/Tiers/Commands/DeleteQuotaForIdentity/Handler.cs +++ b/Modules/Quotas/src/Quotas.Application/Tiers/Commands/DeleteQuotaForIdentity/Handler.cs @@ -46,8 +46,8 @@ file static class LoggerExtensions "Successfully deleted individual quota with id: '{individualQuotaId}'." ); - public static void DeletedQuota(this ILogger logger, string IndividualQuotaId) + public static void DeletedQuota(this ILogger logger, string individualQuotaId) { - DELETED_QUOTA(logger, IndividualQuotaId, default!); + DELETED_QUOTA(logger, individualQuotaId, default!); } } From ce191ee61f4d0015bf20b512107df1269384e173 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Fri, 13 Oct 2023 10:18:40 +0200 Subject: [PATCH 043/133] feat: introduced log event ids --- .../Repository/RelationshipsRepository.cs | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/Modules/Relationships/src/Relationships.Infrastructure/Persistence/Database/Repository/RelationshipsRepository.cs b/Modules/Relationships/src/Relationships.Infrastructure/Persistence/Database/Repository/RelationshipsRepository.cs index a7f0ec5ada..f9f221067b 100644 --- a/Modules/Relationships/src/Relationships.Infrastructure/Persistence/Database/Repository/RelationshipsRepository.cs +++ b/Modules/Relationships/src/Relationships.Infrastructure/Persistence/Database/Repository/RelationshipsRepository.cs @@ -172,7 +172,7 @@ private async Task SaveContentOfLatestChange(Relationship relationship) } catch (BlobAlreadyExistsException ex) { - _logger.LogError(ex, "There was an error while trying to save the content of the RelationshipChange with the id {id}. The name of the blob was {name}.", latestChange.Id, ex.BlobName); + _logger.LogError(latestChange.Id, ex.BlobName, ex); } } @@ -196,3 +196,18 @@ private async Task FillContentOfChanges(IEnumerable changes) await Task.WhenAll(changes.Select(FillContentOfChange).ToArray()); } } + +file static class LoggerExtensions +{ + private static readonly Action ERROR_TRYING_TO_SAVE_RELATIONSHIP_CHANGE = + LoggerMessage.Define( + LogLevel.Error, + new EventId(664861, "RelationshipsRepository.ErrorTryingToSaveRelationshipChange"), + "There was an error while trying to save the content of the RelationshipChange with the id '{id}'. The name of the blob was '{name}'." + ); + + public static void ErrorTryingToSaveRelationshipChange(this ILogger logger, RelationshipChangeId id, string name, Exception e) + { + ERROR_TRYING_TO_SAVE_RELATIONSHIP_CHANGE(logger, id, name, e); + } +} From 7770f3ae9088fe202e4bf98d4b04db7eb27805d6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Fri, 13 Oct 2023 10:20:10 +0200 Subject: [PATCH 044/133] fix: wrong method call --- .../Persistence/Database/Repository/RelationshipsRepository.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Modules/Relationships/src/Relationships.Infrastructure/Persistence/Database/Repository/RelationshipsRepository.cs b/Modules/Relationships/src/Relationships.Infrastructure/Persistence/Database/Repository/RelationshipsRepository.cs index f9f221067b..9023b2b89c 100644 --- a/Modules/Relationships/src/Relationships.Infrastructure/Persistence/Database/Repository/RelationshipsRepository.cs +++ b/Modules/Relationships/src/Relationships.Infrastructure/Persistence/Database/Repository/RelationshipsRepository.cs @@ -172,7 +172,7 @@ private async Task SaveContentOfLatestChange(Relationship relationship) } catch (BlobAlreadyExistsException ex) { - _logger.LogError(latestChange.Id, ex.BlobName, ex); + _logger.ErrorTryingToSaveRelationshipChange(latestChange.Id, ex.BlobName, ex); } } From 3ed939fd72111170305e6f24510e4eed332f32d3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Fri, 13 Oct 2023 10:26:41 +0200 Subject: [PATCH 045/133] feat: introduced log event ids --- .../Infrastructure/Reporter/LogReporter.cs | 31 +++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/Modules/Relationships/src/Relationships.Jobs.SanityCheck.RelationshipChange/Infrastructure/Reporter/LogReporter.cs b/Modules/Relationships/src/Relationships.Jobs.SanityCheck.RelationshipChange/Infrastructure/Reporter/LogReporter.cs index dc974b514c..e8745a3905 100644 --- a/Modules/Relationships/src/Relationships.Jobs.SanityCheck.RelationshipChange/Infrastructure/Reporter/LogReporter.cs +++ b/Modules/Relationships/src/Relationships.Jobs.SanityCheck.RelationshipChange/Infrastructure/Reporter/LogReporter.cs @@ -20,12 +20,12 @@ public void Complete() { foreach (var databaseId in _databaseIds) { - _logger.LogError("no blob found for relationship change id: '{databaseId}'", databaseId); + _logger.NoBlobForRelationshipChangeId(databaseId); } foreach (var blobId in _blobIds) { - _logger.LogError("no database entry found for blob id: '{blobId}'", blobId); + _logger.NoDatabaseEntryForBlobId(blobId); } } @@ -39,3 +39,30 @@ public void ReportOrphanedDatabaseId(RelationshipChangeId id) _databaseIds.Add(id); } } + +file static class LoggerExtensions +{ + private static readonly Action NO_BLOB_FOR_RELATIONSHIP_CHANGE_ID = + LoggerMessage.Define( + LogLevel.Error, + new EventId(349287, "Relationships.SanityCheck.NoBlobForRelationshipChangeId"), + "No blob found for relationship change id: '{databaseId}'." + ); + + private static readonly Action NO_DATABASE_ENTRY_FOR_BLOB_ID = + LoggerMessage.Define( + LogLevel.Error, + new EventId(429922, "Messages.SanityCheck.NoDatabaseEntryForBlobId"), + "No database entry found for blob id: '{blobId}'." + ); + + public static void NoBlobForRelationshipChangeId(this ILogger logger, RelationshipChangeId relationshipChangeId) + { + NO_BLOB_FOR_RELATIONSHIP_CHANGE_ID(logger, relationshipChangeId, default!); + } + + public static void NoDatabaseEntryForBlobId(this ILogger logger, string blobId) + { + NO_DATABASE_ENTRY_FOR_BLOB_ID(logger, blobId, default!); + } +} From c97d92b2fc2cdad43858fcfc924d7a7717e4b46e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Fri, 13 Oct 2023 10:32:15 +0200 Subject: [PATCH 046/133] feat: introduced log event ids --- .../Infrastructure/Reporter/LogReporter.cs | 31 +++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/Modules/Relationships/src/Relationships.Jobs.SanityCheck.RelationshipTemplate/Infrastructure/Reporter/LogReporter.cs b/Modules/Relationships/src/Relationships.Jobs.SanityCheck.RelationshipTemplate/Infrastructure/Reporter/LogReporter.cs index 1f5fbaea9d..77adb79994 100644 --- a/Modules/Relationships/src/Relationships.Jobs.SanityCheck.RelationshipTemplate/Infrastructure/Reporter/LogReporter.cs +++ b/Modules/Relationships/src/Relationships.Jobs.SanityCheck.RelationshipTemplate/Infrastructure/Reporter/LogReporter.cs @@ -20,12 +20,12 @@ public void Complete() { foreach (var databaseId in _databaseIds) { - _logger.LogError("no blob found for relationship template id: '{databaseId}'", databaseId); + _logger.NoBlobForRelationshipTemplateId(databaseId); } foreach (var blobId in _blobIds) { - _logger.LogError("no database entry found for blob id: '{blobId}'", blobId); + _logger.NoDatabaseEntryForBlobId(blobId); } } @@ -39,3 +39,30 @@ public void ReportOrphanedDatabaseId(RelationshipTemplateId id) _databaseIds.Add(id); } } + +file static class LoggerExtensions +{ + private static readonly Action NO_BLOB_FOR_RELATIONSHIP_TEMPLATE_ID = + LoggerMessage.Define( + LogLevel.Error, + new EventId(231727, "Relationships.SanityCheck.NoBlobForRelationshipTemplateId"), + "No blob found for relationship template id: '{databaseId}'." + ); + + private static readonly Action NO_DATABASE_ENTRY_FOR_BLOB_ID = + LoggerMessage.Define( + LogLevel.Error, + new EventId(232800, "Messages.SanityCheck.NoDatabaseEntryForBlobId"), + "No database entry found for blob id: '{blobId}'." + ); + + public static void NoBlobForRelationshipTemplateId(this ILogger logger, RelationshipTemplateId relationshipTemplateId) + { + NO_BLOB_FOR_RELATIONSHIP_TEMPLATE_ID(logger, relationshipTemplateId, default!); + } + + public static void NoDatabaseEntryForBlobId(this ILogger logger, string blobId) + { + NO_DATABASE_ENTRY_FOR_BLOB_ID(logger, blobId, default!); + } +} From f80bd8898f234a65b147e0bcc5da02bab57b6ac3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Fri, 13 Oct 2023 10:40:32 +0200 Subject: [PATCH 047/133] feat: introduced log event ids --- .../Infrastructure/Reporter/LogReporter.cs | 31 +++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/Modules/Synchronization/src/Synchronization.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs b/Modules/Synchronization/src/Synchronization.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs index 61dd04204d..da847433a8 100644 --- a/Modules/Synchronization/src/Synchronization.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs +++ b/Modules/Synchronization/src/Synchronization.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs @@ -20,12 +20,12 @@ public void Complete() { foreach (var databaseId in _databaseIds) { - _logger.LogError("no blob found for datawallet modification id: '{databaseId}'", databaseId); + _logger.NoBlobForDatawalletModificationId(databaseId); } foreach (var blobId in _blobIds) { - _logger.LogError("no database entry found for blob id: '{blobId}'", blobId); + _logger.NoDatabaseEntryForBlobId(blobId); } } @@ -39,3 +39,30 @@ public void ReportOrphanedDatabaseId(DatawalletModificationId id) _databaseIds.Add(id); } } + +file static class LoggerExtensions +{ + private static readonly Action NO_BLOB_FOR_DATAWALLET_MODIFICATION_ID = + LoggerMessage.Define( + LogLevel.Error, + new EventId(525684, "Synchronization.SanityCheck.NoBlobForDatawalletModificationId"), + "No blob found for datawallet modification id: '{databaseId}'." + ); + + private static readonly Action NO_DATABASE_ENTRY_FOR_BLOB_ID = + LoggerMessage.Define( + LogLevel.Error, + new EventId(560290, "Synchronization.SanityCheck.NoDatabaseEntryForBlobId"), + "No database entry found for blob id: '{blobId}'." + ); + + public static void NoBlobForDatawalletModificationId(this ILogger logger, DatawalletModificationId datawalletModificationId) + { + NO_BLOB_FOR_DATAWALLET_MODIFICATION_ID(logger, datawalletModificationId, default!); + } + + public static void NoDatabaseEntryForBlobId(this ILogger logger, string blobId) + { + NO_DATABASE_ENTRY_FOR_BLOB_ID(logger, blobId, default!); + } +} From 704f8d0ff4e6e41315f45418ad4af22a222db68d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Fri, 13 Oct 2023 10:44:10 +0200 Subject: [PATCH 048/133] feat: introdued log event ids --- .../Infrastructure/Reporter/LogReporter.cs | 31 +++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/Modules/Tokens/src/Tokens.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs b/Modules/Tokens/src/Tokens.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs index 09faa6f6a3..2cae594496 100644 --- a/Modules/Tokens/src/Tokens.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs +++ b/Modules/Tokens/src/Tokens.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs @@ -20,12 +20,12 @@ public void Complete() { foreach (var databaseId in _databaseIds) { - _logger.LogError("no blob found for token id: '{databaseId}'", databaseId); + _logger.NoBlobForTokenId(databaseId); } foreach (var blobId in _blobIds) { - _logger.LogError("no database entry found for blob id: '{blobId}'", blobId); + _logger.NoDatabaseEntryForBlobId(blobId); } } @@ -39,3 +39,30 @@ public void ReportOrphanedDatabaseId(TokenId id) _databaseIds.Add(id); } } + +file static class LoggerExtensions +{ + private static readonly Action NO_BLOB_FOR_TOKEN_ID = + LoggerMessage.Define( + LogLevel.Error, + new EventId(826083, "Tokens.SanityCheck.NoBlobForTokenId"), + "No blob found for token id: '{tokenId}'." + ); + + private static readonly Action NO_DATABASE_ENTRY_FOR_BLOB_ID = + LoggerMessage.Define( + LogLevel.Error, + new EventId(271286, "Tokens.SanityCheck.NoDatabaseEntryForBlobId"), + "No database entry found for blob id: '{blobId}'." + ); + + public static void NoBlobForTokenId(this ILogger logger, TokenId tokenId) + { + NO_BLOB_FOR_TOKEN_ID(logger, tokenId, default!); + } + + public static void NoDatabaseEntryForBlobId(this ILogger logger, string blobId) + { + NO_DATABASE_ENTRY_FOR_BLOB_ID(logger, blobId, default!); + } +} From 18b4deb0e1f98d5ca2aeed668b5b43a6b6891101 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Fri, 13 Oct 2023 12:31:45 +0200 Subject: [PATCH 049/133] chore: removed the unused variable that caused the ci/cd test to fail --- .../src/BuildingBlocks.Application/MediatR/LoggingBehavior.cs | 3 --- 1 file changed, 3 deletions(-) diff --git a/BuildingBlocks/src/BuildingBlocks.Application/MediatR/LoggingBehavior.cs b/BuildingBlocks/src/BuildingBlocks.Application/MediatR/LoggingBehavior.cs index d828799c89..f192e9b542 100644 --- a/BuildingBlocks/src/BuildingBlocks.Application/MediatR/LoggingBehavior.cs +++ b/BuildingBlocks/src/BuildingBlocks.Application/MediatR/LoggingBehavior.cs @@ -36,9 +36,6 @@ private void Before() private void After() { _watch!.Stop(); - - var logLevel = _watch.ElapsedMilliseconds < 1000 ? LogLevel.Information : LogLevel.Warning; - _logger.HandleRequest(typeof(TRequest).Name, _watch.ElapsedMilliseconds); } } From e708a89e80c858cccf307ce209a72c9a0b1ae50a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Fri, 13 Oct 2023 13:07:14 +0200 Subject: [PATCH 050/133] feat: scripts for generating random event ids --- scripts/linux/get_random_event_id.sh | 12 ++++++++++++ scripts/windows/get_random_event_id.ps1 | 1 + 2 files changed, 13 insertions(+) create mode 100644 scripts/linux/get_random_event_id.sh create mode 100644 scripts/windows/get_random_event_id.ps1 diff --git a/scripts/linux/get_random_event_id.sh b/scripts/linux/get_random_event_id.sh new file mode 100644 index 0000000000..2b223a24e7 --- /dev/null +++ b/scripts/linux/get_random_event_id.sh @@ -0,0 +1,12 @@ +#!/bin/bash + +while true; do + # Generate a random number in the range [0, 899999] + NUMBER=$(( $(dd if=/dev/urandom bs=3 count=1 2>/dev/null | od -An -i | tr -d '[:space:]') % 900000 )) + + # Adjust the number to the range [100000, 999999] + NUMBER=$(( NUMBER + 100000 )) + + echo $NUMBER + break +done diff --git a/scripts/windows/get_random_event_id.ps1 b/scripts/windows/get_random_event_id.ps1 new file mode 100644 index 0000000000..9a933f036f --- /dev/null +++ b/scripts/windows/get_random_event_id.ps1 @@ -0,0 +1 @@ +Get-Random -Minimum 100000 -Maximum 1000000 From 75d2d72198ef68b9007278bb8a2e9ddf1740cc94 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Mon, 16 Oct 2023 08:35:24 +0200 Subject: [PATCH 051/133] fix: passing nameof(InfrastructureException) instead of whole exception --- .../Mvc/ExceptionFilters/CustomExceptionFilter.cs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/BuildingBlocks/src/BuildingBlocks.API/Mvc/ExceptionFilters/CustomExceptionFilter.cs b/BuildingBlocks/src/BuildingBlocks.API/Mvc/ExceptionFilters/CustomExceptionFilter.cs index eed89540a3..4d3803178d 100644 --- a/BuildingBlocks/src/BuildingBlocks.API/Mvc/ExceptionFilters/CustomExceptionFilter.cs +++ b/BuildingBlocks/src/BuildingBlocks.API/Mvc/ExceptionFilters/CustomExceptionFilter.cs @@ -42,7 +42,7 @@ public override void OnException(ExceptionContext context) { case InfrastructureException infrastructureException: _logger.InfrastructureException( - infrastructureException, infrastructureException.Code, infrastructureException.Message); + infrastructureException.Code, infrastructureException.Message); httpError = CreateHttpErrorForInfrastructureException(infrastructureException); @@ -219,8 +219,8 @@ private IEnumerable GetFormattedStackTrace(Exception exception) file static class LoggerExtensions { - private static readonly Action INFRASTRUCTURE_EXCEPTION = - LoggerMessage.Define( + private static readonly Action INFRASTRUCTURE_EXCEPTION = + LoggerMessage.Define( LogLevel.Information, new EventId(560507, "ExceptionFilter.InfrastructureException"), "An '{exception}' occurred. Error Code: '{code}'. Error message: '{message}'." @@ -256,9 +256,9 @@ file static class LoggerExtensions public static void InfrastructureException( - this ILogger logger, InfrastructureException infrastructureException, string errorCode, string errorMessage) + this ILogger logger, string errorCode, string errorMessage) { - INFRASTRUCTURE_EXCEPTION(logger, infrastructureException, errorCode, errorMessage, default!); + INFRASTRUCTURE_EXCEPTION(logger, nameof(InfrastructureException), errorCode, errorMessage, default!); } public static void ApplicationException( From 724c17a64bd9329a5581cc192d383bdc2a2efaf3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Mon, 16 Oct 2023 08:43:45 +0200 Subject: [PATCH 052/133] chore: combined infrastructure, application and domain exceptions into one statement --- .../ExceptionFilters/CustomExceptionFilter.cs | 48 ++++--------------- 1 file changed, 10 insertions(+), 38 deletions(-) diff --git a/BuildingBlocks/src/BuildingBlocks.API/Mvc/ExceptionFilters/CustomExceptionFilter.cs b/BuildingBlocks/src/BuildingBlocks.API/Mvc/ExceptionFilters/CustomExceptionFilter.cs index 4d3803178d..bbbdc0509f 100644 --- a/BuildingBlocks/src/BuildingBlocks.API/Mvc/ExceptionFilters/CustomExceptionFilter.cs +++ b/BuildingBlocks/src/BuildingBlocks.API/Mvc/ExceptionFilters/CustomExceptionFilter.cs @@ -1,4 +1,5 @@ -using System.Net; +using System; +using System.Net; using System.Text.Json; using System.Text.RegularExpressions; using Enmeshed.BuildingBlocks.API.Extensions; @@ -41,8 +42,7 @@ public override void OnException(ExceptionContext context) switch (context.Exception) { case InfrastructureException infrastructureException: - _logger.InfrastructureException( - infrastructureException.Code, infrastructureException.Message); + _logger.InvalidUserInput(infrastructureException, infrastructureException.Code, infrastructureException.Message); httpError = CreateHttpErrorForInfrastructureException(infrastructureException); @@ -51,8 +51,7 @@ public override void OnException(ExceptionContext context) break; case ApplicationException applicationException: - _logger.ApplicationException( - applicationException, applicationException.Code, applicationException.Message); + _logger.InvalidUserInput(applicationException, applicationException.Code, applicationException.Message); httpError = CreateHttpErrorForApplicationException(applicationException); @@ -62,7 +61,7 @@ public override void OnException(ExceptionContext context) break; case DomainException domainException: - _logger.DomainException(domainException, domainException.Code, domainException.Message); + _logger.InvalidUserInput(domainException, domainException.Code, domainException.Message); httpError = CreateHttpErrorForDomainException(domainException); @@ -219,24 +218,10 @@ private IEnumerable GetFormattedStackTrace(Exception exception) file static class LoggerExtensions { - private static readonly Action INFRASTRUCTURE_EXCEPTION = + private static readonly Action INVALID_USER_INPUT = LoggerMessage.Define( LogLevel.Information, - new EventId(560507, "ExceptionFilter.InfrastructureException"), - "An '{exception}' occurred. Error Code: '{code}'. Error message: '{message}'." - ); - - private static readonly Action APPLICATION_EXCEPTION = - LoggerMessage.Define( - LogLevel.Information, - new EventId(437832, "ExceptionFilter.ApplicationException"), - "An '{exception}' occurred. Error Code: '{code}'. Error message: '{message}'." - ); - - private static readonly Action DOMAIN_EXCEPTION = - LoggerMessage.Define( - LogLevel.Information, - new EventId(505278, "ExceptionFilter.DomainException"), + new EventId(799306, "ExceptionFilter.InvalidUserInput"), "An '{exception}' occurred. Error Code: '{code}'. Error message: '{message}'." ); @@ -254,23 +239,10 @@ file static class LoggerExtensions "Unexpected Error while processing request to '{uri}'." ); - - public static void InfrastructureException( - this ILogger logger, string errorCode, string errorMessage) - { - INFRASTRUCTURE_EXCEPTION(logger, nameof(InfrastructureException), errorCode, errorMessage, default!); - } - - public static void ApplicationException( - this ILogger logger, ApplicationException applicationException, string errorCode, string errorMessage) - { - APPLICATION_EXCEPTION(logger, applicationException, errorCode, errorMessage, default!); - } - - public static void DomainException( - this ILogger logger, DomainException domainException, string errorCode, string errorMessage) + public static void InvalidUserInput( + this ILogger logger, Exception e, string errorCode, string errorMessage) { - DOMAIN_EXCEPTION(logger, domainException, errorCode, errorMessage, default!); + INVALID_USER_INPUT(logger, nameof(e.GetType), errorCode, errorMessage, default!); } public static void RequestBodyTooLarge( From d103ceb8b17e9c0a5e54b30fd8ddb3eb28749cbe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Mon, 16 Oct 2023 08:44:37 +0200 Subject: [PATCH 053/133] chore: method renamed --- .../src/BuildingBlocks.Application/MediatR/LoggingBehavior.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/BuildingBlocks/src/BuildingBlocks.Application/MediatR/LoggingBehavior.cs b/BuildingBlocks/src/BuildingBlocks.Application/MediatR/LoggingBehavior.cs index f192e9b542..f522e73352 100644 --- a/BuildingBlocks/src/BuildingBlocks.Application/MediatR/LoggingBehavior.cs +++ b/BuildingBlocks/src/BuildingBlocks.Application/MediatR/LoggingBehavior.cs @@ -36,7 +36,7 @@ private void Before() private void After() { _watch!.Stop(); - _logger.HandleRequest(typeof(TRequest).Name, _watch.ElapsedMilliseconds); + _logger.HandledMediatorRequest(typeof(TRequest).Name, _watch.ElapsedMilliseconds); } } @@ -56,7 +56,7 @@ file static class LoggerExtensions "Handled '{requestName}' ('{timeElapsed}' ms)." ); - public static void HandleRequest(this ILogger logger, string requestName, long timeElapsed) + public static void HandledMediatorRequest(this ILogger logger, string requestName, long timeElapsed) { if (timeElapsed > 1000) HANDLED_REQUEST_WARNING(logger, requestName, timeElapsed, default!); From 881097853d63906f3f86b8ad08d1ee22b0cbb4e2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Mon, 16 Oct 2023 08:46:26 +0200 Subject: [PATCH 054/133] chore: log event ids and names changed as per request --- .../src/BuildingBlocks.Application/MediatR/LoggingBehavior.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/BuildingBlocks/src/BuildingBlocks.Application/MediatR/LoggingBehavior.cs b/BuildingBlocks/src/BuildingBlocks.Application/MediatR/LoggingBehavior.cs index f522e73352..37eb9b3c2b 100644 --- a/BuildingBlocks/src/BuildingBlocks.Application/MediatR/LoggingBehavior.cs +++ b/BuildingBlocks/src/BuildingBlocks.Application/MediatR/LoggingBehavior.cs @@ -45,14 +45,14 @@ file static class LoggerExtensions private static readonly Action HANDLED_REQUEST_WARNING = LoggerMessage.Define( LogLevel.Warning, - new EventId(437002, "LoggingBehavior.HandleRequestInformation"), + new EventId(724322, "LoggingBehavior.HandleRequest"), "Handled '{requestName}' ('{timeElapsed}' ms)." ); private static readonly Action HANDLED_REQUEST_INFORMATION = LoggerMessage.Define( LogLevel.Information, - new EventId(214089, "LoggingBehavior.HandleRequestInformation"), + new EventId(724322, "LoggingBehavior.HandleRequest"), "Handled '{requestName}' ('{timeElapsed}' ms)." ); From 2f159e25800ade3972bcc5a368446de1873df227 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Mon, 16 Oct 2023 08:47:11 +0200 Subject: [PATCH 055/133] chore: log event names changed as per request --- .../src/BuildingBlocks.Application/MediatR/LoggingBehavior.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/BuildingBlocks/src/BuildingBlocks.Application/MediatR/LoggingBehavior.cs b/BuildingBlocks/src/BuildingBlocks.Application/MediatR/LoggingBehavior.cs index 37eb9b3c2b..dccc27c2c3 100644 --- a/BuildingBlocks/src/BuildingBlocks.Application/MediatR/LoggingBehavior.cs +++ b/BuildingBlocks/src/BuildingBlocks.Application/MediatR/LoggingBehavior.cs @@ -45,14 +45,14 @@ file static class LoggerExtensions private static readonly Action HANDLED_REQUEST_WARNING = LoggerMessage.Define( LogLevel.Warning, - new EventId(724322, "LoggingBehavior.HandleRequest"), + new EventId(724322, "LoggingBehavior.HandledRequestInformation"), "Handled '{requestName}' ('{timeElapsed}' ms)." ); private static readonly Action HANDLED_REQUEST_INFORMATION = LoggerMessage.Define( LogLevel.Information, - new EventId(724322, "LoggingBehavior.HandleRequest"), + new EventId(724322, "LoggingBehavior.HandledRequestInformation"), "Handled '{requestName}' ('{timeElapsed}' ms)." ); From 90b19f5ce09b9378e29c9ef2c813e12c94bca1b9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Mon, 16 Oct 2023 08:49:32 +0200 Subject: [PATCH 056/133] chore: log event name changed as per request --- .../EventBus/AzureServiceBus/EventBusAzureServiceBus.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/AzureServiceBus/EventBusAzureServiceBus.cs b/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/AzureServiceBus/EventBusAzureServiceBus.cs index d7eec03d3c..95f9a1d958 100644 --- a/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/AzureServiceBus/EventBusAzureServiceBus.cs +++ b/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/AzureServiceBus/EventBusAzureServiceBus.cs @@ -212,7 +212,7 @@ file static class LoggerExtensions private static readonly Action ERROR_WHILE_EXECUTING_EVENT_HANDLER_TYPE = LoggerMessage.Define( LogLevel.Warning, - new EventId(726744, "EventBusAzureServiceBus.ErrorWhileExecutingEventHandlerType"), + new EventId(726744, "EventBusAzureServiceBus.ErrorWhileExecutingEventHandlerCausingRetry"), "The following error was thrown while executing '{eventHandlerType}':\n'{errorMessage}'\n{stackTrace}.\nAttempting to retry..." ); From 6be2b8a65c40639195a6c34e6b2742b4260cff23 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Mon, 16 Oct 2023 09:12:48 +0200 Subject: [PATCH 057/133] chore: changes made as per requests --- .../EventBus/RabbitMQ/EventBusRabbitMQ.cs | 20 ++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/RabbitMQ/EventBusRabbitMQ.cs b/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/RabbitMQ/EventBusRabbitMQ.cs index d38791ba4f..598ccacea2 100644 --- a/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/RabbitMQ/EventBusRabbitMQ.cs +++ b/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/RabbitMQ/EventBusRabbitMQ.cs @@ -1,6 +1,7 @@ using System.Net.Sockets; using System.Text; using Autofac; +using Azure.Messaging.ServiceBus; using Enmeshed.BuildingBlocks.Application.Abstractions.Infrastructure.EventBus; using Enmeshed.BuildingBlocks.Application.Abstractions.Infrastructure.EventBus.Events; using Enmeshed.BuildingBlocks.Infrastructure.EventBus.Json; @@ -69,7 +70,7 @@ public void Publish(IntegrationEvent @event) .Or() .WaitAndRetry(_connectionRetryCount, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), - (ex, _) => _logger.SocketException(ex.Message, ex)); + (ex, _) => _logger.SocketException(ex)); var eventName = @event.GetType().Name; @@ -101,7 +102,7 @@ public void Publish(IntegrationEvent @event) properties, body); - _logger.IntegrationEventId(@event.IntegrationEventId); + _logger.PublishedIntegrationEvent(@event.IntegrationEventId); }); } @@ -258,20 +259,16 @@ file static class LoggerExtensions "The following error was thrown while executing '{eventHandlerType}':\n'{errorMessage}'\n{stackTrace}.\nAttempting to retry..." ); - public static void SocketException(this ILogger logger, string exceptionString, Exception e) + public static void SocketException(this ILogger logger, Exception e) { - SOCKET_EXCEPTION(logger, exceptionString, e); + SOCKET_EXCEPTION(logger, e.Message, e); } - public static void IntegrationEventId(this ILogger logger, string integrationEventId) + public static void PublishedIntegrationEvent(this ILogger logger, string integrationEventId) { PUBLISHED_INTEGERATION_EVENT(logger, integrationEventId, default!); } - public static void ErrorWhileProcessingIntegrationEvent(this ILogger logger, string eventName, Exception e) - { - ERROR_WHILE_PROCESSING_INTEGRATION_EVENT(logger, eventName, e); - } public static void NoSubscriptionForEvent(this ILogger logger, string eventName) { NO_SUBSCRIPTION_FOR_EVENT(logger, eventName, default!); @@ -281,4 +278,9 @@ public static void ErrorWhileExecutingEventHandlerType(this ILogger logger, stri { ERROR_WHILE_EXECUTING_EVENT_HANDLER_TYPE(logger, eventHandlerType, errorMessage, stackTrace, e); } + + public static void ErrorWhileProcessingIntegrationEvent(this ILogger logger, string eventName, Exception e) + { + ERROR_WHILE_PROCESSING_INTEGRATION_EVENT(logger, eventName, e); + } } From 7a872945759b81c1e483d837672c2f7e892ab8fe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Mon, 16 Oct 2023 09:16:22 +0200 Subject: [PATCH 058/133] chore: method names changed, log message changed --- .../AzureStorageAccount/AzureStorageAccount.cs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/BuildingBlocks/src/BuildingBlocks.Infrastructure/Persistence/BlobStorage/AzureStorageAccount/AzureStorageAccount.cs b/BuildingBlocks/src/BuildingBlocks.Infrastructure/Persistence/BlobStorage/AzureStorageAccount/AzureStorageAccount.cs index 3f20c578ca..4b764420e7 100644 --- a/BuildingBlocks/src/BuildingBlocks.Infrastructure/Persistence/BlobStorage/AzureStorageAccount/AzureStorageAccount.cs +++ b/BuildingBlocks/src/BuildingBlocks.Infrastructure/Persistence/BlobStorage/AzureStorageAccount/AzureStorageAccount.cs @@ -74,7 +74,7 @@ public Task> FindAllAsync(string folder, string? prefix } catch (Exception ex) { - _logger.ErrorListingAllTheBlobs(ex); + _logger.ErrorListingAllBlobs(ex); throw; } } @@ -127,7 +127,7 @@ private async Task DeleteRemovedBlobs() } catch (Exception ex) { - _logger.ErrorDeletingTheBlob(cloudBlockBlob.Name, ex); + _logger.ErrorDeletingBlob(cloudBlockBlob.Name, ex); throw new NotFoundException(); } @@ -140,23 +140,23 @@ file static class LoggerExtensions private static readonly Action ERROR_LISTING_ALL_THE_BLOBS = LoggerMessage.Define( LogLevel.Error, - new EventId(516591, "AzureStorageAccount.ErrorListingAllTheBlobs"), - "There was an error listing all the blobs." + new EventId(516591, "AzureStorageAccount.ErrorListingAllBlobs"), + "There was an error listing all blobs." ); private static readonly Action ERROR_DELETING_THE_BLOB = LoggerMessage.Define( LogLevel.Error, - new EventId(645028, "AzureStorageAccount.ErrorDeletingTheBlob"), + new EventId(645028, "AzureStorageAccount.ErrorDeletingBlob"), "There was an error deleting the blob with id '{cloudBlockBlobName}'. {ex}" ); - public static void ErrorListingAllTheBlobs(this ILogger logger, Exception e) + public static void ErrorListingAllBlobs(this ILogger logger, Exception e) { ERROR_LISTING_ALL_THE_BLOBS(logger, e); } - public static void ErrorDeletingTheBlob(this ILogger logger, string cloudBlockBlobName, Exception e) + public static void ErrorDeletingBlob(this ILogger logger, string cloudBlockBlobName, Exception e) { ERROR_DELETING_THE_BLOB(logger, cloudBlockBlobName, e, default!); } From 33efa543dfdf4acc62986088048d61e5e655939f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Mon, 16 Oct 2023 09:28:30 +0200 Subject: [PATCH 059/133] fix: assigned unique event id chore: updated event name --- .../Tiers/Commands/DeleteTierQuotaDefinition/Handler.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Modules/Quotas/src/Quotas.Application/Tiers/Commands/DeleteTierQuotaDefinition/Handler.cs b/Modules/Quotas/src/Quotas.Application/Tiers/Commands/DeleteTierQuotaDefinition/Handler.cs index e1c2573c08..a6115fa91e 100644 --- a/Modules/Quotas/src/Quotas.Application/Tiers/Commands/DeleteTierQuotaDefinition/Handler.cs +++ b/Modules/Quotas/src/Quotas.Application/Tiers/Commands/DeleteTierQuotaDefinition/Handler.cs @@ -44,7 +44,7 @@ file static class LoggerExtensions private static readonly Action DELETED_TIER_QUOTA = LoggerMessage.Define( LogLevel.Information, - new EventId(247156, "DeleteTierQuotaDefinition.Handler.DeletedTierQuota"), + new EventId(519284, "DeletedTierQuota"), "Successfully deleted tier quota definition with id: '{tierQuotaDefinitionId}'." ); From 8dbadf3aabe2972d61b7235c17fd64c018006b4f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Mon, 16 Oct 2023 09:29:11 +0200 Subject: [PATCH 060/133] chore: removed `handler` from event names for all handler classes' statements --- .../Clients/Commands/DeleteClient/Handler.cs | 2 +- .../Devices/Commands/ChangePassword/Handler.cs | 2 +- .../Devices/Commands/DeleteDevice/Handler.cs | 2 +- .../Devices/Commands/RegisterDevice/Handler.cs | 2 +- .../Identities/Commands/CreateIdentity/Handler.cs | 2 +- .../Devices.Application/Tiers/Commands/CreateTier/Handler.cs | 2 +- .../Tiers/Commands/CreateQuotaForIdentity/Handler.cs | 2 +- .../Tiers/Commands/CreateQuotaForTier/Handler.cs | 2 +- .../Tiers/Commands/DeleteQuotaForIdentity/Handler.cs | 2 +- 9 files changed, 9 insertions(+), 9 deletions(-) diff --git a/Modules/Devices/src/Devices.Application/Clients/Commands/DeleteClient/Handler.cs b/Modules/Devices/src/Devices.Application/Clients/Commands/DeleteClient/Handler.cs index 28376a1543..ba0ecbf948 100644 --- a/Modules/Devices/src/Devices.Application/Clients/Commands/DeleteClient/Handler.cs +++ b/Modules/Devices/src/Devices.Application/Clients/Commands/DeleteClient/Handler.cs @@ -30,7 +30,7 @@ file static class LoggerExtensions private static readonly Action DELETED_CLIENT_WITH_ID = LoggerMessage.Define( LogLevel.Information, - new EventId(418943, "DeleteClient.Handler.DeletedClientWithId"), + new EventId(418943, "DeletedClientWithId"), "Successfully deleted client with id '{clientId}'." ); diff --git a/Modules/Devices/src/Devices.Application/Devices/Commands/ChangePassword/Handler.cs b/Modules/Devices/src/Devices.Application/Devices/Commands/ChangePassword/Handler.cs index ce513561ec..bd1197fd9b 100644 --- a/Modules/Devices/src/Devices.Application/Devices/Commands/ChangePassword/Handler.cs +++ b/Modules/Devices/src/Devices.Application/Devices/Commands/ChangePassword/Handler.cs @@ -42,7 +42,7 @@ file static class LoggerExtensions private static readonly Action CHANGED_PASSWORD_FOR_DEVICE_WITH_ID = LoggerMessage.Define( LogLevel.Information, - new EventId(277894, "ChangePassword.Handler.ChangedPasswordForDeviceWithId"), + new EventId(277894, "ChangedPasswordForDeviceWithId"), "Successfully changed password for device with id '{activeDevice}'." ); diff --git a/Modules/Devices/src/Devices.Application/Devices/Commands/DeleteDevice/Handler.cs b/Modules/Devices/src/Devices.Application/Devices/Commands/DeleteDevice/Handler.cs index 39d6c5a6c6..f413ab07ed 100644 --- a/Modules/Devices/src/Devices.Application/Devices/Commands/DeleteDevice/Handler.cs +++ b/Modules/Devices/src/Devices.Application/Devices/Commands/DeleteDevice/Handler.cs @@ -49,7 +49,7 @@ file static class LoggerExtensions private static readonly Action MARK_DEVICE_WITH_ID_AS_DELETED = LoggerMessage.Define( LogLevel.Information, - new EventId(776010, "DeleteDevice.Handler.MarkDeviceWithIdAsDeleted"), + new EventId(776010, "MarkDeviceWithIdAsDeleted"), "Successfully marked device with id '{deviceId}' as deleted." ); diff --git a/Modules/Devices/src/Devices.Application/Devices/Commands/RegisterDevice/Handler.cs b/Modules/Devices/src/Devices.Application/Devices/Commands/RegisterDevice/Handler.cs index 6bf18eef3c..6016ba169a 100644 --- a/Modules/Devices/src/Devices.Application/Devices/Commands/RegisterDevice/Handler.cs +++ b/Modules/Devices/src/Devices.Application/Devices/Commands/RegisterDevice/Handler.cs @@ -116,7 +116,7 @@ file static class LoggerExtensions private static readonly Action CREATED_DEVICE = LoggerMessage.Define( LogLevel.Information, - new EventId(219823, "RegisterDevice.Handler.CreatedDevice"), + new EventId(219823, "CreatedDevice"), "Successfully created device. Device ID: '{deviceId}', User ID: '{userId}', Username: '{userName}'." ); diff --git a/Modules/Devices/src/Devices.Application/Identities/Commands/CreateIdentity/Handler.cs b/Modules/Devices/src/Devices.Application/Identities/Commands/CreateIdentity/Handler.cs index 68db45d88c..5dfa4952a6 100644 --- a/Modules/Devices/src/Devices.Application/Identities/Commands/CreateIdentity/Handler.cs +++ b/Modules/Devices/src/Devices.Application/Identities/Commands/CreateIdentity/Handler.cs @@ -77,7 +77,7 @@ file static class LoggerExtensions private static readonly Action CREATED_IDENTITY = LoggerMessage.Define( LogLevel.Information, - new EventId(436321, "CreateIdentity.Handler.CreatedIdentity"), + new EventId(436321, "CreatedIdentity"), "Identity created. Address: '{address}', Device ID: '{deviceId}', Username: '{userName}'." ); diff --git a/Modules/Devices/src/Devices.Application/Tiers/Commands/CreateTier/Handler.cs b/Modules/Devices/src/Devices.Application/Tiers/Commands/CreateTier/Handler.cs index 6477643c75..4548053220 100644 --- a/Modules/Devices/src/Devices.Application/Tiers/Commands/CreateTier/Handler.cs +++ b/Modules/Devices/src/Devices.Application/Tiers/Commands/CreateTier/Handler.cs @@ -46,7 +46,7 @@ file static class LoggerExtensions private static readonly Action CREATED_TIER = LoggerMessage.Define( LogLevel.Information, - new EventId(383136, "CreateTier.Handler.CreatedTier"), + new EventId(383136, "CreatedTier"), "Successfully created tier. Tier ID: '{tierId}', Tier Name: {tierName}" ); diff --git a/Modules/Quotas/src/Quotas.Application/Tiers/Commands/CreateQuotaForIdentity/Handler.cs b/Modules/Quotas/src/Quotas.Application/Tiers/Commands/CreateQuotaForIdentity/Handler.cs index 939b901aa7..0506263add 100644 --- a/Modules/Quotas/src/Quotas.Application/Tiers/Commands/CreateQuotaForIdentity/Handler.cs +++ b/Modules/Quotas/src/Quotas.Application/Tiers/Commands/CreateQuotaForIdentity/Handler.cs @@ -55,7 +55,7 @@ file static class LoggerExtensions private static readonly Action CREATED_QUOTAS_FOR_IDENTITY = LoggerMessage.Define( LogLevel.Information, - new EventId(868289, "CreateQuotaForIdentity.Handler.CreatedQuotasForIdentities"), + new EventId(868289, "CreatedQuotasForIdentities"), "Successfully created Quota for Identity. Identity Address: '{identityAddress}'." ); diff --git a/Modules/Quotas/src/Quotas.Application/Tiers/Commands/CreateQuotaForTier/Handler.cs b/Modules/Quotas/src/Quotas.Application/Tiers/Commands/CreateQuotaForTier/Handler.cs index b98fb253b7..e11f65b84e 100644 --- a/Modules/Quotas/src/Quotas.Application/Tiers/Commands/CreateQuotaForTier/Handler.cs +++ b/Modules/Quotas/src/Quotas.Application/Tiers/Commands/CreateQuotaForTier/Handler.cs @@ -58,7 +58,7 @@ file static class LoggerExtensions private static readonly Action CREATED_QUOTA_FOR_TIER = LoggerMessage.Define( LogLevel.Information, - new EventId(346835, "CreateQuotaForTier.Handler.CreatedQuotaForTier"), + new EventId(346835, "CreatedQuotaForTier"), "Successfully created Quota for Tier. Tier ID: '{tierId}', Tier Name: '{tierName}'." ); diff --git a/Modules/Quotas/src/Quotas.Application/Tiers/Commands/DeleteQuotaForIdentity/Handler.cs b/Modules/Quotas/src/Quotas.Application/Tiers/Commands/DeleteQuotaForIdentity/Handler.cs index 45e04cc0b0..f58fd655c3 100644 --- a/Modules/Quotas/src/Quotas.Application/Tiers/Commands/DeleteQuotaForIdentity/Handler.cs +++ b/Modules/Quotas/src/Quotas.Application/Tiers/Commands/DeleteQuotaForIdentity/Handler.cs @@ -42,7 +42,7 @@ file static class LoggerExtensions private static readonly Action DELETED_QUOTA = LoggerMessage.Define( LogLevel.Information, - new EventId(247156, "DeleteQuotaForIdentity.Handler.DeletedQuota"), + new EventId(247156, "DeleteQuota"), "Successfully deleted individual quota with id: '{individualQuotaId}'." ); From b8fb91fea9ee7f9583d10de2afc4b592d68b89f3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Mon, 16 Oct 2023 09:39:58 +0200 Subject: [PATCH 061/133] chore: naming updated as per request - `handler` not used, pattern `..` used in modules --- .../Clients/Commands/DeleteClient/Handler.cs | 2 +- .../Devices/Commands/ChangePassword/Handler.cs | 2 +- .../Devices/Commands/DeleteDevice/Handler.cs | 2 +- .../Devices/Commands/RegisterDevice/Handler.cs | 2 +- .../Identities/Commands/CreateIdentity/Handler.cs | 2 +- .../Tiers/Commands/CreateTier/Handler.cs | 2 +- .../AzureNotificationHub/AzureNotificationHubPushService.cs | 4 ++-- .../PushNotifications/DirectPush/DirectPushService.cs | 6 +++--- .../Infrastructure/Reporter/LogReporter.cs | 4 ++-- .../Infrastructure/Reporter/LogReporter.cs | 4 ++-- .../IdentityCreatedIntegrationEventHandler.cs | 2 +- .../TierCreated/TierCreatedIntegrationEventHandler.cs | 2 +- .../TierDeleted/TierDeletedIntegrationEventHandler.cs | 2 +- .../TierQuotaDefinitionDeletedIntegrationEventHandler.cs | 2 +- .../Tiers/Commands/CreateQuotaForIdentity/Handler.cs | 2 +- .../Tiers/Commands/CreateQuotaForTier/Handler.cs | 2 +- .../Tiers/Commands/DeleteQuotaForIdentity/Handler.cs | 2 +- .../Tiers/Commands/DeleteTierQuotaDefinition/Handler.cs | 2 +- .../Database/Repository/RelationshipsRepository.cs | 2 +- .../Infrastructure/Reporter/LogReporter.cs | 4 ++-- .../Infrastructure/Reporter/LogReporter.cs | 4 ++-- .../Infrastructure/Reporter/LogReporter.cs | 4 ++-- .../Infrastructure/Reporter/LogReporter.cs | 4 ++-- 23 files changed, 32 insertions(+), 32 deletions(-) diff --git a/Modules/Devices/src/Devices.Application/Clients/Commands/DeleteClient/Handler.cs b/Modules/Devices/src/Devices.Application/Clients/Commands/DeleteClient/Handler.cs index ba0ecbf948..33355a2e37 100644 --- a/Modules/Devices/src/Devices.Application/Clients/Commands/DeleteClient/Handler.cs +++ b/Modules/Devices/src/Devices.Application/Clients/Commands/DeleteClient/Handler.cs @@ -30,7 +30,7 @@ file static class LoggerExtensions private static readonly Action DELETED_CLIENT_WITH_ID = LoggerMessage.Define( LogLevel.Information, - new EventId(418943, "DeletedClientWithId"), + new EventId(418943, "Devices.DeletedClientWithId"), "Successfully deleted client with id '{clientId}'." ); diff --git a/Modules/Devices/src/Devices.Application/Devices/Commands/ChangePassword/Handler.cs b/Modules/Devices/src/Devices.Application/Devices/Commands/ChangePassword/Handler.cs index bd1197fd9b..43a687e77d 100644 --- a/Modules/Devices/src/Devices.Application/Devices/Commands/ChangePassword/Handler.cs +++ b/Modules/Devices/src/Devices.Application/Devices/Commands/ChangePassword/Handler.cs @@ -42,7 +42,7 @@ file static class LoggerExtensions private static readonly Action CHANGED_PASSWORD_FOR_DEVICE_WITH_ID = LoggerMessage.Define( LogLevel.Information, - new EventId(277894, "ChangedPasswordForDeviceWithId"), + new EventId(277894, "Devices.ChangedPasswordForDeviceWithId"), "Successfully changed password for device with id '{activeDevice}'." ); diff --git a/Modules/Devices/src/Devices.Application/Devices/Commands/DeleteDevice/Handler.cs b/Modules/Devices/src/Devices.Application/Devices/Commands/DeleteDevice/Handler.cs index f413ab07ed..762ec294e0 100644 --- a/Modules/Devices/src/Devices.Application/Devices/Commands/DeleteDevice/Handler.cs +++ b/Modules/Devices/src/Devices.Application/Devices/Commands/DeleteDevice/Handler.cs @@ -49,7 +49,7 @@ file static class LoggerExtensions private static readonly Action MARK_DEVICE_WITH_ID_AS_DELETED = LoggerMessage.Define( LogLevel.Information, - new EventId(776010, "MarkDeviceWithIdAsDeleted"), + new EventId(776010, "Devices.MarkDeviceWithIdAsDeleted"), "Successfully marked device with id '{deviceId}' as deleted." ); diff --git a/Modules/Devices/src/Devices.Application/Devices/Commands/RegisterDevice/Handler.cs b/Modules/Devices/src/Devices.Application/Devices/Commands/RegisterDevice/Handler.cs index 6016ba169a..24df392d6f 100644 --- a/Modules/Devices/src/Devices.Application/Devices/Commands/RegisterDevice/Handler.cs +++ b/Modules/Devices/src/Devices.Application/Devices/Commands/RegisterDevice/Handler.cs @@ -116,7 +116,7 @@ file static class LoggerExtensions private static readonly Action CREATED_DEVICE = LoggerMessage.Define( LogLevel.Information, - new EventId(219823, "CreatedDevice"), + new EventId(219823, "Devices.CreatedDevice"), "Successfully created device. Device ID: '{deviceId}', User ID: '{userId}', Username: '{userName}'." ); diff --git a/Modules/Devices/src/Devices.Application/Identities/Commands/CreateIdentity/Handler.cs b/Modules/Devices/src/Devices.Application/Identities/Commands/CreateIdentity/Handler.cs index 5dfa4952a6..0655b62b5e 100644 --- a/Modules/Devices/src/Devices.Application/Identities/Commands/CreateIdentity/Handler.cs +++ b/Modules/Devices/src/Devices.Application/Identities/Commands/CreateIdentity/Handler.cs @@ -77,7 +77,7 @@ file static class LoggerExtensions private static readonly Action CREATED_IDENTITY = LoggerMessage.Define( LogLevel.Information, - new EventId(436321, "CreatedIdentity"), + new EventId(436321, "Devices.CreatedIdentity"), "Identity created. Address: '{address}', Device ID: '{deviceId}', Username: '{userName}'." ); diff --git a/Modules/Devices/src/Devices.Application/Tiers/Commands/CreateTier/Handler.cs b/Modules/Devices/src/Devices.Application/Tiers/Commands/CreateTier/Handler.cs index 4548053220..88bbe94acf 100644 --- a/Modules/Devices/src/Devices.Application/Tiers/Commands/CreateTier/Handler.cs +++ b/Modules/Devices/src/Devices.Application/Tiers/Commands/CreateTier/Handler.cs @@ -46,7 +46,7 @@ file static class LoggerExtensions private static readonly Action CREATED_TIER = LoggerMessage.Define( LogLevel.Information, - new EventId(383136, "CreatedTier"), + new EventId(383136, "Devices.CreatedTier"), "Successfully created tier. Tier ID: '{tierId}', Tier Name: {tierName}" ); diff --git a/Modules/Devices/src/Devices.Infrastructure/PushNotifications/AzureNotificationHub/AzureNotificationHubPushService.cs b/Modules/Devices/src/Devices.Infrastructure/PushNotifications/AzureNotificationHub/AzureNotificationHubPushService.cs index dde43654c5..5c4c69c912 100644 --- a/Modules/Devices/src/Devices.Infrastructure/PushNotifications/AzureNotificationHub/AzureNotificationHubPushService.cs +++ b/Modules/Devices/src/Devices.Infrastructure/PushNotifications/AzureNotificationHub/AzureNotificationHubPushService.cs @@ -121,14 +121,14 @@ file static class LoggerExtensions private static readonly Action DEVICE_REGISTERED = LoggerMessage.Define( LogLevel.Information, - new EventId(585563, "AzureNotificationHubPushService.DeviceRegistered"), + new EventId(585563, "Devices.AzureNotificationHubPushService.DeviceRegistered"), "New device successfully registered." ); private static readonly Action DEVICE_UNREGISTERED = LoggerMessage.Define( LogLevel.Information, - new EventId(767782, "AzureNotificationHubPushService.DeviceUnregistered"), + new EventId(767782, "Devices.AzureNotificationHubPushService.DeviceUnregistered"), "Unregistered device '{deviceId}' from push notifications." ); diff --git a/Modules/Devices/src/Devices.Infrastructure/PushNotifications/DirectPush/DirectPushService.cs b/Modules/Devices/src/Devices.Infrastructure/PushNotifications/DirectPush/DirectPushService.cs index 8dcf609ff0..f96cb28128 100644 --- a/Modules/Devices/src/Devices.Infrastructure/PushNotifications/DirectPush/DirectPushService.cs +++ b/Modules/Devices/src/Devices.Infrastructure/PushNotifications/DirectPush/DirectPushService.cs @@ -119,21 +119,21 @@ file static class LoggerExtensions private static readonly Action DELETING_DEVICE_REGISTRATION = LoggerMessage.Define( LogLevel.Information, - new EventId(950845, "DirectPushService.DeletingDeviceRegistration"), + new EventId(950845, "Devices.DirectPushService.DeletingDeviceRegistration"), "Deleting device registration for '{deviceId}' since handle is no longer valid." ); private static readonly Action ERROR_WHILE_TRYING_TO_SEND_NOTIFICATION = LoggerMessage.Define( LogLevel.Error, - new EventId(624412, "DirectPushService.ErrorWhileTryingToSendNotification"), + new EventId(624412, "Devices.DirectPushService.ErrorWhileTryingToSendNotification"), "The following error occurred while trying to send the notification for '{deviceId}': '{error}'." ); private static readonly Action UNREGISTERED_DEVICE = LoggerMessage.Define( LogLevel.Information, - new EventId(628738, "DirectPushService.UnregisteredDevice"), + new EventId(628738, "Devices.DirectPushService.UnregisteredDevice"), "Unregistered device '{deviceId} from push notifications." ); diff --git a/Modules/Files/src/Files.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs b/Modules/Files/src/Files.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs index d83ac8dd31..6a5133568f 100644 --- a/Modules/Files/src/Files.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs +++ b/Modules/Files/src/Files.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs @@ -45,14 +45,14 @@ file static class LoggerExtensions private static readonly Action NO_BLOB_FOR_FILE_ID = LoggerMessage.Define( LogLevel.Error, - new EventId(629592, "Files.SanityCheck.NoBlobForFileId"), + new EventId(629592, "Files.LogReporter.NoBlobForFileId"), "No blob found for file id: '{databaseId}'." ); private static readonly Action NO_DATABASE_ENTRY_FOR_BLOB_ID = LoggerMessage.Define( LogLevel.Error, - new EventId(487180, "Files.SanityCheck.NoDatabaseEntryForBlobId"), + new EventId(487180, "Files.LogReporter.NoDatabaseEntryForBlobId"), "No database entry found for blob id: '{blobId}'." ); diff --git a/Modules/Messages/src/Messages.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs b/Modules/Messages/src/Messages.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs index 3032b894dc..bf5fc2dd7b 100644 --- a/Modules/Messages/src/Messages.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs +++ b/Modules/Messages/src/Messages.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs @@ -45,14 +45,14 @@ file static class LoggerExtensions private static readonly Action NO_BLOB_FOR_MESSAGE_ID = LoggerMessage.Define( LogLevel.Error, - new EventId(859729, "Messages.SanityCheck.NoBlobForMessageId"), + new EventId(859729, "Messages.LogReporter.NoBlobForMessageId"), "No blob found for file id: '{databaseId}'." ); private static readonly Action NO_DATABASE_ENTRY_FOR_BLOB_ID = LoggerMessage.Define( LogLevel.Error, - new EventId(809167, "Messages.SanityCheck.NoDatabaseEntryForBlobId"), + new EventId(809167, "Messages.LogReporter.NoDatabaseEntryForBlobId"), "No database entry found for blob id: '{blobId}'." ); diff --git a/Modules/Quotas/src/Quotas.Application/IntegrationEvents/Incoming/IdentityCreated/IdentityCreatedIntegrationEventHandler.cs b/Modules/Quotas/src/Quotas.Application/IntegrationEvents/Incoming/IdentityCreated/IdentityCreatedIntegrationEventHandler.cs index 6746fe3ae5..2162d7bfe9 100644 --- a/Modules/Quotas/src/Quotas.Application/IntegrationEvents/Incoming/IdentityCreated/IdentityCreatedIntegrationEventHandler.cs +++ b/Modules/Quotas/src/Quotas.Application/IntegrationEvents/Incoming/IdentityCreated/IdentityCreatedIntegrationEventHandler.cs @@ -48,7 +48,7 @@ file static class LoggerExtensions private static readonly Action IDENTITY_CREATED = LoggerMessage.Define( LogLevel.Information, - new EventId(811934, "IdentityCreatedIntegrationEventHandler.IdentityCreated"), + new EventId(811934, "Quotas.IdentityCreatedIntegrationEventHandler.IdentityCreated"), "Successfully created identity. Identity Address: '{address}', Tier ID: '{tierId}'." ); diff --git a/Modules/Quotas/src/Quotas.Application/IntegrationEvents/Incoming/TierCreated/TierCreatedIntegrationEventHandler.cs b/Modules/Quotas/src/Quotas.Application/IntegrationEvents/Incoming/TierCreated/TierCreatedIntegrationEventHandler.cs index 33f109d4fd..937cc0acda 100644 --- a/Modules/Quotas/src/Quotas.Application/IntegrationEvents/Incoming/TierCreated/TierCreatedIntegrationEventHandler.cs +++ b/Modules/Quotas/src/Quotas.Application/IntegrationEvents/Incoming/TierCreated/TierCreatedIntegrationEventHandler.cs @@ -29,7 +29,7 @@ file static class LoggerExtensions private static readonly Action TIER_CREATED = LoggerMessage.Define( LogLevel.Information, - new EventId(151788, "TierCreatedIntegrationEventHandler.TierCreated"), + new EventId(151788, "Quotas.TierCreatedIntegrationEventHandler.TierCreated"), "Successfully created tier. Tier ID: '{tierId}', Tier Name: '{tierName}'." ); diff --git a/Modules/Quotas/src/Quotas.Application/IntegrationEvents/Incoming/TierDeleted/TierDeletedIntegrationEventHandler.cs b/Modules/Quotas/src/Quotas.Application/IntegrationEvents/Incoming/TierDeleted/TierDeletedIntegrationEventHandler.cs index 5c94d457cd..6e9c5deed3 100644 --- a/Modules/Quotas/src/Quotas.Application/IntegrationEvents/Incoming/TierDeleted/TierDeletedIntegrationEventHandler.cs +++ b/Modules/Quotas/src/Quotas.Application/IntegrationEvents/Incoming/TierDeleted/TierDeletedIntegrationEventHandler.cs @@ -30,7 +30,7 @@ file static class LoggerExtensions private static readonly Action TIER_DELETED = LoggerMessage.Define( LogLevel.Information, - new EventId(582359, "TierDeletedIntegrationEventHandler.TierDeleted"), + new EventId(582359, "Quotas.TierDeletedIntegrationEventHandler.TierDeleted"), "Successfully deleted tier. Tier ID: '{tierId}', Tier Name: '{tierName}'." ); diff --git a/Modules/Quotas/src/Quotas.Application/IntegrationEvents/Incoming/TierQuotaDefinitionDeleted/TierQuotaDefinitionDeletedIntegrationEventHandler.cs b/Modules/Quotas/src/Quotas.Application/IntegrationEvents/Incoming/TierQuotaDefinitionDeleted/TierQuotaDefinitionDeletedIntegrationEventHandler.cs index 45d1112174..ae430b8d2c 100644 --- a/Modules/Quotas/src/Quotas.Application/IntegrationEvents/Incoming/TierQuotaDefinitionDeleted/TierQuotaDefinitionDeletedIntegrationEventHandler.cs +++ b/Modules/Quotas/src/Quotas.Application/IntegrationEvents/Incoming/TierQuotaDefinitionDeleted/TierQuotaDefinitionDeletedIntegrationEventHandler.cs @@ -49,7 +49,7 @@ file static class LoggerExtensions private static readonly Action DELETED_QUOTAS_FOR_IDENTITIES = LoggerMessage.Define( LogLevel.Information, - new EventId(942996, "TierQuotaDefinitionDeletedIntegrationEventHandler.DeletedQuotasForIdentities"), + new EventId(942996, "Quotas.TierQuotaDefinitionDeletedIntegrationEventHandler.DeletedQuotasForIdentities"), "Successfully deleted quotas for Identities." ); diff --git a/Modules/Quotas/src/Quotas.Application/Tiers/Commands/CreateQuotaForIdentity/Handler.cs b/Modules/Quotas/src/Quotas.Application/Tiers/Commands/CreateQuotaForIdentity/Handler.cs index 0506263add..5527fafe84 100644 --- a/Modules/Quotas/src/Quotas.Application/Tiers/Commands/CreateQuotaForIdentity/Handler.cs +++ b/Modules/Quotas/src/Quotas.Application/Tiers/Commands/CreateQuotaForIdentity/Handler.cs @@ -55,7 +55,7 @@ file static class LoggerExtensions private static readonly Action CREATED_QUOTAS_FOR_IDENTITY = LoggerMessage.Define( LogLevel.Information, - new EventId(868289, "CreatedQuotasForIdentities"), + new EventId(868289, "Quotas.CreatedQuotasForIdentities"), "Successfully created Quota for Identity. Identity Address: '{identityAddress}'." ); diff --git a/Modules/Quotas/src/Quotas.Application/Tiers/Commands/CreateQuotaForTier/Handler.cs b/Modules/Quotas/src/Quotas.Application/Tiers/Commands/CreateQuotaForTier/Handler.cs index e11f65b84e..9dbd1e2b5a 100644 --- a/Modules/Quotas/src/Quotas.Application/Tiers/Commands/CreateQuotaForTier/Handler.cs +++ b/Modules/Quotas/src/Quotas.Application/Tiers/Commands/CreateQuotaForTier/Handler.cs @@ -58,7 +58,7 @@ file static class LoggerExtensions private static readonly Action CREATED_QUOTA_FOR_TIER = LoggerMessage.Define( LogLevel.Information, - new EventId(346835, "CreatedQuotaForTier"), + new EventId(346835, "Quotas.CreatedQuotaForTier"), "Successfully created Quota for Tier. Tier ID: '{tierId}', Tier Name: '{tierName}'." ); diff --git a/Modules/Quotas/src/Quotas.Application/Tiers/Commands/DeleteQuotaForIdentity/Handler.cs b/Modules/Quotas/src/Quotas.Application/Tiers/Commands/DeleteQuotaForIdentity/Handler.cs index f58fd655c3..018595011c 100644 --- a/Modules/Quotas/src/Quotas.Application/Tiers/Commands/DeleteQuotaForIdentity/Handler.cs +++ b/Modules/Quotas/src/Quotas.Application/Tiers/Commands/DeleteQuotaForIdentity/Handler.cs @@ -42,7 +42,7 @@ file static class LoggerExtensions private static readonly Action DELETED_QUOTA = LoggerMessage.Define( LogLevel.Information, - new EventId(247156, "DeleteQuota"), + new EventId(247156, "Quotas.DeleteQuota"), "Successfully deleted individual quota with id: '{individualQuotaId}'." ); diff --git a/Modules/Quotas/src/Quotas.Application/Tiers/Commands/DeleteTierQuotaDefinition/Handler.cs b/Modules/Quotas/src/Quotas.Application/Tiers/Commands/DeleteTierQuotaDefinition/Handler.cs index a6115fa91e..80420071ab 100644 --- a/Modules/Quotas/src/Quotas.Application/Tiers/Commands/DeleteTierQuotaDefinition/Handler.cs +++ b/Modules/Quotas/src/Quotas.Application/Tiers/Commands/DeleteTierQuotaDefinition/Handler.cs @@ -44,7 +44,7 @@ file static class LoggerExtensions private static readonly Action DELETED_TIER_QUOTA = LoggerMessage.Define( LogLevel.Information, - new EventId(519284, "DeletedTierQuota"), + new EventId(519284, "Quotas.DeletedTierQuota"), "Successfully deleted tier quota definition with id: '{tierQuotaDefinitionId}'." ); diff --git a/Modules/Relationships/src/Relationships.Infrastructure/Persistence/Database/Repository/RelationshipsRepository.cs b/Modules/Relationships/src/Relationships.Infrastructure/Persistence/Database/Repository/RelationshipsRepository.cs index 9023b2b89c..ba90544114 100644 --- a/Modules/Relationships/src/Relationships.Infrastructure/Persistence/Database/Repository/RelationshipsRepository.cs +++ b/Modules/Relationships/src/Relationships.Infrastructure/Persistence/Database/Repository/RelationshipsRepository.cs @@ -202,7 +202,7 @@ file static class LoggerExtensions private static readonly Action ERROR_TRYING_TO_SAVE_RELATIONSHIP_CHANGE = LoggerMessage.Define( LogLevel.Error, - new EventId(664861, "RelationshipsRepository.ErrorTryingToSaveRelationshipChange"), + new EventId(664861, "Relationships.RelationshipsRepository.ErrorTryingToSaveRelationshipChange"), "There was an error while trying to save the content of the RelationshipChange with the id '{id}'. The name of the blob was '{name}'." ); diff --git a/Modules/Relationships/src/Relationships.Jobs.SanityCheck.RelationshipChange/Infrastructure/Reporter/LogReporter.cs b/Modules/Relationships/src/Relationships.Jobs.SanityCheck.RelationshipChange/Infrastructure/Reporter/LogReporter.cs index e8745a3905..b5d5222e55 100644 --- a/Modules/Relationships/src/Relationships.Jobs.SanityCheck.RelationshipChange/Infrastructure/Reporter/LogReporter.cs +++ b/Modules/Relationships/src/Relationships.Jobs.SanityCheck.RelationshipChange/Infrastructure/Reporter/LogReporter.cs @@ -45,14 +45,14 @@ file static class LoggerExtensions private static readonly Action NO_BLOB_FOR_RELATIONSHIP_CHANGE_ID = LoggerMessage.Define( LogLevel.Error, - new EventId(349287, "Relationships.SanityCheck.NoBlobForRelationshipChangeId"), + new EventId(349287, "Relationships.LogReporter.NoBlobForRelationshipChangeId"), "No blob found for relationship change id: '{databaseId}'." ); private static readonly Action NO_DATABASE_ENTRY_FOR_BLOB_ID = LoggerMessage.Define( LogLevel.Error, - new EventId(429922, "Messages.SanityCheck.NoDatabaseEntryForBlobId"), + new EventId(429922, "Relationships.LogReporter.NoDatabaseEntryForBlobId"), "No database entry found for blob id: '{blobId}'." ); diff --git a/Modules/Relationships/src/Relationships.Jobs.SanityCheck.RelationshipTemplate/Infrastructure/Reporter/LogReporter.cs b/Modules/Relationships/src/Relationships.Jobs.SanityCheck.RelationshipTemplate/Infrastructure/Reporter/LogReporter.cs index 77adb79994..7d75d8660f 100644 --- a/Modules/Relationships/src/Relationships.Jobs.SanityCheck.RelationshipTemplate/Infrastructure/Reporter/LogReporter.cs +++ b/Modules/Relationships/src/Relationships.Jobs.SanityCheck.RelationshipTemplate/Infrastructure/Reporter/LogReporter.cs @@ -45,14 +45,14 @@ file static class LoggerExtensions private static readonly Action NO_BLOB_FOR_RELATIONSHIP_TEMPLATE_ID = LoggerMessage.Define( LogLevel.Error, - new EventId(231727, "Relationships.SanityCheck.NoBlobForRelationshipTemplateId"), + new EventId(231727, "Relationships.LogReporter.NoBlobForRelationshipTemplateId"), "No blob found for relationship template id: '{databaseId}'." ); private static readonly Action NO_DATABASE_ENTRY_FOR_BLOB_ID = LoggerMessage.Define( LogLevel.Error, - new EventId(232800, "Messages.SanityCheck.NoDatabaseEntryForBlobId"), + new EventId(232800, "Relationships.LogReporter.NoDatabaseEntryForBlobId"), "No database entry found for blob id: '{blobId}'." ); diff --git a/Modules/Synchronization/src/Synchronization.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs b/Modules/Synchronization/src/Synchronization.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs index da847433a8..50cdc0a3f6 100644 --- a/Modules/Synchronization/src/Synchronization.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs +++ b/Modules/Synchronization/src/Synchronization.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs @@ -45,14 +45,14 @@ file static class LoggerExtensions private static readonly Action NO_BLOB_FOR_DATAWALLET_MODIFICATION_ID = LoggerMessage.Define( LogLevel.Error, - new EventId(525684, "Synchronization.SanityCheck.NoBlobForDatawalletModificationId"), + new EventId(525684, "Synchronization.LogReporter.NoBlobForDatawalletModificationId"), "No blob found for datawallet modification id: '{databaseId}'." ); private static readonly Action NO_DATABASE_ENTRY_FOR_BLOB_ID = LoggerMessage.Define( LogLevel.Error, - new EventId(560290, "Synchronization.SanityCheck.NoDatabaseEntryForBlobId"), + new EventId(560290, "Synchronization.LogReporter.NoDatabaseEntryForBlobId"), "No database entry found for blob id: '{blobId}'." ); diff --git a/Modules/Tokens/src/Tokens.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs b/Modules/Tokens/src/Tokens.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs index 2cae594496..fdf8493765 100644 --- a/Modules/Tokens/src/Tokens.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs +++ b/Modules/Tokens/src/Tokens.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs @@ -45,14 +45,14 @@ file static class LoggerExtensions private static readonly Action NO_BLOB_FOR_TOKEN_ID = LoggerMessage.Define( LogLevel.Error, - new EventId(826083, "Tokens.SanityCheck.NoBlobForTokenId"), + new EventId(826083, "Tokens.LogReporter.NoBlobForTokenId"), "No blob found for token id: '{tokenId}'." ); private static readonly Action NO_DATABASE_ENTRY_FOR_BLOB_ID = LoggerMessage.Define( LogLevel.Error, - new EventId(271286, "Tokens.SanityCheck.NoDatabaseEntryForBlobId"), + new EventId(271286, "Tokens.LogReporter.NoDatabaseEntryForBlobId"), "No database entry found for blob id: '{blobId}'." ); From 70790d2470166b552406aa6081761fd9d88032ea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Mon, 16 Oct 2023 10:53:34 +0200 Subject: [PATCH 062/133] chore: updated line endings --- .../ExceptionFilters/CustomExceptionFilter.cs | 516 +++++++++--------- 1 file changed, 258 insertions(+), 258 deletions(-) diff --git a/BuildingBlocks/src/BuildingBlocks.API/Mvc/ExceptionFilters/CustomExceptionFilter.cs b/BuildingBlocks/src/BuildingBlocks.API/Mvc/ExceptionFilters/CustomExceptionFilter.cs index bbbdc0509f..5983806a29 100644 --- a/BuildingBlocks/src/BuildingBlocks.API/Mvc/ExceptionFilters/CustomExceptionFilter.cs +++ b/BuildingBlocks/src/BuildingBlocks.API/Mvc/ExceptionFilters/CustomExceptionFilter.cs @@ -1,259 +1,259 @@ using System; -using System.Net; -using System.Text.Json; -using System.Text.RegularExpressions; -using Enmeshed.BuildingBlocks.API.Extensions; -using Enmeshed.BuildingBlocks.Application.Abstractions.Exceptions; -using Enmeshed.BuildingBlocks.Domain; -using Enmeshed.BuildingBlocks.Domain.Errors; -using Enmeshed.BuildingBlocks.Infrastructure.Exceptions; -using Microsoft.ApplicationInsights.AspNetCore.Extensions; -using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Mvc.Filters; -using Microsoft.Extensions.Hosting; -using Microsoft.Extensions.Logging; -using ApplicationException = Enmeshed.BuildingBlocks.Application.Abstractions.Exceptions.ApplicationException; - -namespace Enmeshed.BuildingBlocks.API.Mvc.ExceptionFilters; - -[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] -public class CustomExceptionFilter : ExceptionFilterAttribute -{ - private const string ERROR_CODE_UNEXPECTED_EXCEPTION = "error.platform.unexpected"; - private const string ERROR_CODE_REQUEST_BODY_TOO_LARGE = "error.platform.requestBodyTooLarge"; - - private readonly IWebHostEnvironment _env; - private readonly ILogger _logger; - - public CustomExceptionFilter(ILogger logger, IWebHostEnvironment env) - { - _logger = logger; - _env = env; - } - - public override void OnException(ExceptionContext context) - { - context.HttpContext.Response.ContentType = "application/json"; - - HttpError httpError; - - switch (context.Exception) - { - case InfrastructureException infrastructureException: - _logger.InvalidUserInput(infrastructureException, infrastructureException.Code, infrastructureException.Message); - - httpError = CreateHttpErrorForInfrastructureException(infrastructureException); - - context.HttpContext.Response.StatusCode = - (int)GetStatusCodeForInfrastructureException(infrastructureException); - - break; - case ApplicationException applicationException: - _logger.InvalidUserInput(applicationException, applicationException.Code, applicationException.Message); - - httpError = CreateHttpErrorForApplicationException(applicationException); - - context.HttpContext.Response.StatusCode = - (int)GetStatusCodeForApplicationException(applicationException); - - break; - - case DomainException domainException: - _logger.InvalidUserInput(domainException, domainException.Code, domainException.Message); - - httpError = CreateHttpErrorForDomainException(domainException); - - context.HttpContext.Response.StatusCode = (int)GetStatusCodeForDomainException(domainException); - - break; - case BadHttpRequestException _: - _logger.RequestBodyTooLarge(ERROR_CODE_REQUEST_BODY_TOO_LARGE); - - httpError = HttpError.ForProduction( - ERROR_CODE_REQUEST_BODY_TOO_LARGE, - "The request body is too large.", - "" // TODO: add documentation link - ); - - context.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest; - - break; - default: - _logger.ErrorWhileProcessingRequestToUri(context.HttpContext.Request.GetUri(), context.Exception); - - httpError = CreateHttpErrorForUnexpectedException(context); - - context.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError; - - break; - } - - context.Result = new JsonResult(HttpResponseEnvelope.CreateError(httpError), - new JsonSerializerOptions - { - PropertyNamingPolicy = JsonNamingPolicy.CamelCase, DictionaryKeyPolicy = JsonNamingPolicy.CamelCase - }); - } - - private HttpError CreateHttpErrorForInfrastructureException(InfrastructureException infrastructureException) - { - var httpError = HttpError.ForProduction( - infrastructureException.Code, - infrastructureException.Message, - "" // TODO: add documentation link - ); - - return httpError; - } - - private HttpError CreateHttpErrorForApplicationException(ApplicationException applicationException) - { - var httpError = HttpError.ForProduction( - applicationException.Code, - applicationException.Message, - "", // TODO: add documentation link - data: GetCustomData(applicationException) - ); - - return httpError; - } - - private HttpError CreateHttpErrorForDomainException(DomainException domainException) - { - var httpError = HttpError.ForProduction( - domainException.Code, - domainException.Message, - "" // TODO: add documentation link - ); - - return httpError; - } - - private dynamic? GetCustomData(ApplicationException applicationException) - { - if (applicationException is QuotaExhaustedException quotaExhautedException) - { - return quotaExhautedException.ExhaustedMetricStatuses.Select(m => new - { -#pragma warning disable IDE0037 - MetricKey = m.MetricKey, - IsExhaustedUntil = m.IsExhaustedUntil -#pragma warning restore IDE0037 - }); - } - - return null; - } - - private HttpStatusCode GetStatusCodeForInfrastructureException(InfrastructureException exception) - { - return HttpStatusCode.BadRequest; - } - - private HttpStatusCode GetStatusCodeForApplicationException(ApplicationException exception) - { - return exception switch - { - NotFoundException _ => HttpStatusCode.NotFound, - ActionForbiddenException _ => HttpStatusCode.Forbidden, - QuotaExhaustedException _ => HttpStatusCode.TooManyRequests, - _ => HttpStatusCode.BadRequest - }; - } - - private HttpStatusCode GetStatusCodeForDomainException(DomainException exception) - { - if (exception.Code == GenericDomainErrors.NotFound().Code) - return HttpStatusCode.NotFound; - - return HttpStatusCode.BadRequest; - } - - private HttpError CreateHttpErrorForUnexpectedException(ExceptionContext context) - { - HttpError httpError; - - if (_env.IsDevelopment() || _env.IsLocal()) - { - var details = context.Exception.Message; - var innerException = context.Exception.InnerException; - - while (innerException != null) - { - details += "\r\n> " + innerException.Message; - innerException = innerException.InnerException; - } - - httpError = HttpError.ForDev( - ERROR_CODE_UNEXPECTED_EXCEPTION, - "An unexpected error occurred.", - "", // TODO: add documentation link - GetFormattedStackTrace(context.Exception), - details - ); - } - else - { - httpError = HttpError.ForProduction( - ERROR_CODE_UNEXPECTED_EXCEPTION, - "An unexpected error occurred.", - "" // TODO: add documentation link - ); - } - - return httpError; - } - - private IEnumerable GetFormattedStackTrace(Exception exception) - { - if (exception.StackTrace == null) - return Enumerable.Empty(); - - return - Regex.Matches(exception.StackTrace, "at .+").Select(m => m.Value.Trim()); - } -} - -file static class LoggerExtensions -{ - private static readonly Action INVALID_USER_INPUT = - LoggerMessage.Define( - LogLevel.Information, - new EventId(799306, "ExceptionFilter.InvalidUserInput"), - "An '{exception}' occurred. Error Code: '{code}'. Error message: '{message}'." - ); - - private static readonly Action REQUEST_BODY_TOO_LARGE = - LoggerMessage.Define( - LogLevel.Information, - new EventId(938218, "ExceptionFilter.RequestBodyTooLarge"), - "'{error_code}': The body of the request is too large." - ); - - private static readonly Action ERROR_WHILE_PROCESSING_REQUEST_TO_URI = - LoggerMessage.Define( - LogLevel.Error, - new EventId(259125, "ExceptionFilter.ErrorWhileProcessingRequestToUri"), - "Unexpected Error while processing request to '{uri}'." - ); - - public static void InvalidUserInput( - this ILogger logger, Exception e, string errorCode, string errorMessage) - { - INVALID_USER_INPUT(logger, nameof(e.GetType), errorCode, errorMessage, default!); - } - - public static void RequestBodyTooLarge( - this ILogger logger, string errorCode) - { - REQUEST_BODY_TOO_LARGE(logger, errorCode, default!); - } - - public static void ErrorWhileProcessingRequestToUri( - this ILogger logger, Uri uri, Exception e) - { - ERROR_WHILE_PROCESSING_REQUEST_TO_URI(logger, uri, e); - } -} +using System.Net; +using System.Text.Json; +using System.Text.RegularExpressions; +using Enmeshed.BuildingBlocks.API.Extensions; +using Enmeshed.BuildingBlocks.Application.Abstractions.Exceptions; +using Enmeshed.BuildingBlocks.Domain; +using Enmeshed.BuildingBlocks.Domain.Errors; +using Enmeshed.BuildingBlocks.Infrastructure.Exceptions; +using Microsoft.ApplicationInsights.AspNetCore.Extensions; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Filters; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using ApplicationException = Enmeshed.BuildingBlocks.Application.Abstractions.Exceptions.ApplicationException; + +namespace Enmeshed.BuildingBlocks.API.Mvc.ExceptionFilters; + +[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] +public class CustomExceptionFilter : ExceptionFilterAttribute +{ + private const string ERROR_CODE_UNEXPECTED_EXCEPTION = "error.platform.unexpected"; + private const string ERROR_CODE_REQUEST_BODY_TOO_LARGE = "error.platform.requestBodyTooLarge"; + + private readonly IWebHostEnvironment _env; + private readonly ILogger _logger; + + public CustomExceptionFilter(ILogger logger, IWebHostEnvironment env) + { + _logger = logger; + _env = env; + } + + public override void OnException(ExceptionContext context) + { + context.HttpContext.Response.ContentType = "application/json"; + + HttpError httpError; + + switch (context.Exception) + { + case InfrastructureException infrastructureException: + _logger.InvalidUserInput(infrastructureException, infrastructureException.Code, infrastructureException.Message); + + httpError = CreateHttpErrorForInfrastructureException(infrastructureException); + + context.HttpContext.Response.StatusCode = + (int)GetStatusCodeForInfrastructureException(infrastructureException); + + break; + case ApplicationException applicationException: + _logger.InvalidUserInput(applicationException, applicationException.Code, applicationException.Message); + + httpError = CreateHttpErrorForApplicationException(applicationException); + + context.HttpContext.Response.StatusCode = + (int)GetStatusCodeForApplicationException(applicationException); + + break; + + case DomainException domainException: + _logger.InvalidUserInput(domainException, domainException.Code, domainException.Message); + + httpError = CreateHttpErrorForDomainException(domainException); + + context.HttpContext.Response.StatusCode = (int)GetStatusCodeForDomainException(domainException); + + break; + case BadHttpRequestException _: + _logger.RequestBodyTooLarge(ERROR_CODE_REQUEST_BODY_TOO_LARGE); + + httpError = HttpError.ForProduction( + ERROR_CODE_REQUEST_BODY_TOO_LARGE, + "The request body is too large.", + "" // TODO: add documentation link + ); + + context.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest; + + break; + default: + _logger.ErrorWhileProcessingRequestToUri(context.HttpContext.Request.GetUri(), context.Exception); + + httpError = CreateHttpErrorForUnexpectedException(context); + + context.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError; + + break; + } + + context.Result = new JsonResult(HttpResponseEnvelope.CreateError(httpError), + new JsonSerializerOptions + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, DictionaryKeyPolicy = JsonNamingPolicy.CamelCase + }); + } + + private HttpError CreateHttpErrorForInfrastructureException(InfrastructureException infrastructureException) + { + var httpError = HttpError.ForProduction( + infrastructureException.Code, + infrastructureException.Message, + "" // TODO: add documentation link + ); + + return httpError; + } + + private HttpError CreateHttpErrorForApplicationException(ApplicationException applicationException) + { + var httpError = HttpError.ForProduction( + applicationException.Code, + applicationException.Message, + "", // TODO: add documentation link + data: GetCustomData(applicationException) + ); + + return httpError; + } + + private HttpError CreateHttpErrorForDomainException(DomainException domainException) + { + var httpError = HttpError.ForProduction( + domainException.Code, + domainException.Message, + "" // TODO: add documentation link + ); + + return httpError; + } + + private dynamic? GetCustomData(ApplicationException applicationException) + { + if (applicationException is QuotaExhaustedException quotaExhautedException) + { + return quotaExhautedException.ExhaustedMetricStatuses.Select(m => new + { +#pragma warning disable IDE0037 + MetricKey = m.MetricKey, + IsExhaustedUntil = m.IsExhaustedUntil +#pragma warning restore IDE0037 + }); + } + + return null; + } + + private HttpStatusCode GetStatusCodeForInfrastructureException(InfrastructureException exception) + { + return HttpStatusCode.BadRequest; + } + + private HttpStatusCode GetStatusCodeForApplicationException(ApplicationException exception) + { + return exception switch + { + NotFoundException _ => HttpStatusCode.NotFound, + ActionForbiddenException _ => HttpStatusCode.Forbidden, + QuotaExhaustedException _ => HttpStatusCode.TooManyRequests, + _ => HttpStatusCode.BadRequest + }; + } + + private HttpStatusCode GetStatusCodeForDomainException(DomainException exception) + { + if (exception.Code == GenericDomainErrors.NotFound().Code) + return HttpStatusCode.NotFound; + + return HttpStatusCode.BadRequest; + } + + private HttpError CreateHttpErrorForUnexpectedException(ExceptionContext context) + { + HttpError httpError; + + if (_env.IsDevelopment() || _env.IsLocal()) + { + var details = context.Exception.Message; + var innerException = context.Exception.InnerException; + + while (innerException != null) + { + details += "\r\n> " + innerException.Message; + innerException = innerException.InnerException; + } + + httpError = HttpError.ForDev( + ERROR_CODE_UNEXPECTED_EXCEPTION, + "An unexpected error occurred.", + "", // TODO: add documentation link + GetFormattedStackTrace(context.Exception), + details + ); + } + else + { + httpError = HttpError.ForProduction( + ERROR_CODE_UNEXPECTED_EXCEPTION, + "An unexpected error occurred.", + "" // TODO: add documentation link + ); + } + + return httpError; + } + + private IEnumerable GetFormattedStackTrace(Exception exception) + { + if (exception.StackTrace == null) + return Enumerable.Empty(); + + return + Regex.Matches(exception.StackTrace, "at .+").Select(m => m.Value.Trim()); + } +} + +file static class LoggerExtensions +{ + private static readonly Action INVALID_USER_INPUT = + LoggerMessage.Define( + LogLevel.Information, + new EventId(799306, "ExceptionFilter.InvalidUserInput"), + "An '{exception}' occurred. Error Code: '{code}'. Error message: '{message}'." + ); + + private static readonly Action REQUEST_BODY_TOO_LARGE = + LoggerMessage.Define( + LogLevel.Information, + new EventId(938218, "ExceptionFilter.RequestBodyTooLarge"), + "'{error_code}': The body of the request is too large." + ); + + private static readonly Action ERROR_WHILE_PROCESSING_REQUEST_TO_URI = + LoggerMessage.Define( + LogLevel.Error, + new EventId(259125, "ExceptionFilter.ErrorWhileProcessingRequestToUri"), + "Unexpected Error while processing request to '{uri}'." + ); + + public static void InvalidUserInput( + this ILogger logger, Exception e, string errorCode, string errorMessage) + { + INVALID_USER_INPUT(logger, nameof(e.GetType), errorCode, errorMessage, default!); + } + + public static void RequestBodyTooLarge( + this ILogger logger, string errorCode) + { + REQUEST_BODY_TOO_LARGE(logger, errorCode, default!); + } + + public static void ErrorWhileProcessingRequestToUri( + this ILogger logger, Uri uri, Exception e) + { + ERROR_WHILE_PROCESSING_REQUEST_TO_URI(logger, uri, e); + } +} From 2db44fea47eb99a1b7702fa5c44273622e60585f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Mon, 16 Oct 2023 10:55:12 +0200 Subject: [PATCH 063/133] chore: delegate names updated --- .../AzureStorageAccount/AzureStorageAccount.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/BuildingBlocks/src/BuildingBlocks.Infrastructure/Persistence/BlobStorage/AzureStorageAccount/AzureStorageAccount.cs b/BuildingBlocks/src/BuildingBlocks.Infrastructure/Persistence/BlobStorage/AzureStorageAccount/AzureStorageAccount.cs index 4b764420e7..9b518d2d4e 100644 --- a/BuildingBlocks/src/BuildingBlocks.Infrastructure/Persistence/BlobStorage/AzureStorageAccount/AzureStorageAccount.cs +++ b/BuildingBlocks/src/BuildingBlocks.Infrastructure/Persistence/BlobStorage/AzureStorageAccount/AzureStorageAccount.cs @@ -137,14 +137,14 @@ private async Task DeleteRemovedBlobs() file static class LoggerExtensions { - private static readonly Action ERROR_LISTING_ALL_THE_BLOBS = + private static readonly Action ERROR_LISTING_ALL_BLOBS = LoggerMessage.Define( LogLevel.Error, new EventId(516591, "AzureStorageAccount.ErrorListingAllBlobs"), "There was an error listing all blobs." ); - private static readonly Action ERROR_DELETING_THE_BLOB = + private static readonly Action ERROR_DELETING_BLOB = LoggerMessage.Define( LogLevel.Error, new EventId(645028, "AzureStorageAccount.ErrorDeletingBlob"), @@ -153,11 +153,11 @@ file static class LoggerExtensions public static void ErrorListingAllBlobs(this ILogger logger, Exception e) { - ERROR_LISTING_ALL_THE_BLOBS(logger, e); + ERROR_LISTING_ALL_BLOBS(logger, e); } public static void ErrorDeletingBlob(this ILogger logger, string cloudBlockBlobName, Exception e) { - ERROR_DELETING_THE_BLOB(logger, cloudBlockBlobName, e, default!); + ERROR_DELETING_BLOB(logger, cloudBlockBlobName, e, default!); } } From d1a835f95866cc7e9f11e55e80bc081128e99d43 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Mon, 16 Oct 2023 10:58:37 +0200 Subject: [PATCH 064/133] chore: delegate and method names updated --- .../GoogleCloudStorage/GoogleCloudStorage.cs | 50 +++++++++---------- 1 file changed, 25 insertions(+), 25 deletions(-) diff --git a/BuildingBlocks/src/BuildingBlocks.Infrastructure/Persistence/BlobStorage/GoogleCloudStorage/GoogleCloudStorage.cs b/BuildingBlocks/src/BuildingBlocks.Infrastructure/Persistence/BlobStorage/GoogleCloudStorage/GoogleCloudStorage.cs index 4d0c836cb5..230da31793 100644 --- a/BuildingBlocks/src/BuildingBlocks.Infrastructure/Persistence/BlobStorage/GoogleCloudStorage/GoogleCloudStorage.cs +++ b/BuildingBlocks/src/BuildingBlocks.Infrastructure/Persistence/BlobStorage/GoogleCloudStorage/GoogleCloudStorage.cs @@ -57,7 +57,7 @@ await _logger.TraceTime(async () => catch (Exception ex) { EliminateNotFound(ex, blobId); - _logger.ErrorDownloadingTheBlobWithName(blobId, ex); + _logger.ErrorDownloadingBlobWithName(blobId, ex); throw; } } @@ -75,7 +75,7 @@ public Task> FindAllAsync(string folder, string? prefix } catch (Exception ex) { - _logger.ErrorListingAllTheBlobs(ex); + _logger.ErrorListingAllBlobs(ex); throw; } } @@ -116,7 +116,7 @@ await _storageClient.UploadObjectAsync(blob.Folder, blob.Name, null, } catch (Exception ex) { - _logger.ErrorUploadingTheBlobWithName(blob.Name, ex); + _logger.ErrorUploadingBlobWithName(blob.Name, ex); throw; } finally @@ -133,7 +133,7 @@ private async Task EnsureKeyDoesNotExist(string folder, string key) await _logger.TraceTime(async () => await _storageClient.GetObjectAsync(folder, key), nameof(_storageClient.GetObjectAsync)); - _logger.ErrorBlobWithTheNameExists(); + _logger.ErrorBlobWithNameExists(); throw new BlobAlreadyExistsException(key); } catch (GoogleApiException ex) @@ -160,7 +160,7 @@ private async Task DeleteRemovedBlobs() catch (Exception ex) { EliminateNotFound(ex, blob.Name); - _logger.ErrorDeletingTheBlobWithName(blob.Name, ex); + _logger.ErrorDeletingBlobWithName(blob.Name, ex); throw; } @@ -174,63 +174,63 @@ private record RemovedBlob(string Folder, string Name); file static class LoggerExtensions { - private static readonly Action ERROR_DOWNLOADING_THE_BLOB_WITH_NAME = + private static readonly Action ERROR_DOWNLOADING_BLOB_WITH_NAME = LoggerMessage.Define( LogLevel.Error, - new EventId(997942, "GoogleCloudStorage.ErrorDownloadingTheBlobWithName"), + new EventId(997942, "GoogleCloudStorage.ErrorDownloadingBlobWithName"), "There was an error downloading the blob with name '{blobId}'. {ex}" ); - private static readonly Action ERROR_LISTING_ALL_THE_BLOBS = + private static readonly Action ERROR_LISTING_ALL_BLOBS = LoggerMessage.Define( LogLevel.Error, - new EventId(998879, "GoogleCloudStorage.ErrorListingAllTheBlobs"), + new EventId(998879, "GoogleCloudStorage.ErrorListingAllBlobs"), "There was an error listing all the blobs." ); - private static readonly Action ERROR_UPLOADING_THE_BLOB_WITH_NAME = + private static readonly Action ERROR_UPLOADING_BLOB_WITH_NAME = LoggerMessage.Define( LogLevel.Error, - new EventId(166344, "GoogleCloudStorage.ErrorUploadingTheBlobWithName"), + new EventId(166344, "GoogleCloudStorage.ErrorUploadingBlobWithName"), "There was an error uploading the blob with name '{blobName}'. {ex}" ); - private static readonly Action ERROR_BLOB_WITH_THE_NAME_EXISTS = + private static readonly Action ERROR_BLOB_WITH_NAME_EXISTS = LoggerMessage.Define( LogLevel.Error, - new EventId(358892, "GoogleCloudStorage.ErrorBlobWithTheNameExists"), + new EventId(358892, "GoogleCloudStorage.ErrorBlobWithNameExists"), "The blob with the given name already exists." ); - private static readonly Action ERROR_DELETING_THE_BLOB_WITH_NAME = + private static readonly Action ERROR_DELETING_BLOB_WITH_NAME = LoggerMessage.Define( LogLevel.Error, - new EventId(304533, "GoogleCloudStorage.ErrorDeletingTheBlobWithName"), + new EventId(304533, "GoogleCloudStorage.ErrorDeletingBlobWithName"), "There was an error downloading the blob with name '{blobName}'. {ex}" ); - public static void ErrorDownloadingTheBlobWithName(this ILogger logger, string blobId, Exception e) + public static void ErrorDownloadingBlobWithName(this ILogger logger, string blobId, Exception e) { - ERROR_DOWNLOADING_THE_BLOB_WITH_NAME(logger, blobId, e, e); + ERROR_DOWNLOADING_BLOB_WITH_NAME(logger, blobId, e, e); } - public static void ErrorListingAllTheBlobs(this ILogger logger, Exception e) + public static void ErrorListingAllBlobs(this ILogger logger, Exception e) { - ERROR_LISTING_ALL_THE_BLOBS(logger, e); + ERROR_LISTING_ALL_BLOBS(logger, e); } - public static void ErrorUploadingTheBlobWithName(this ILogger logger, string blobName, Exception e) + public static void ErrorUploadingBlobWithName(this ILogger logger, string blobName, Exception e) { - ERROR_UPLOADING_THE_BLOB_WITH_NAME(logger, blobName, e, e); + ERROR_UPLOADING_BLOB_WITH_NAME(logger, blobName, e, e); } - public static void ErrorBlobWithTheNameExists(this ILogger logger) + public static void ErrorBlobWithNameExists(this ILogger logger) { - ERROR_BLOB_WITH_THE_NAME_EXISTS(logger, default!); + ERROR_BLOB_WITH_NAME_EXISTS(logger, default!); } - public static void ErrorDeletingTheBlobWithName(this ILogger logger, string blobName, Exception e) + public static void ErrorDeletingBlobWithName(this ILogger logger, string blobName, Exception e) { - ERROR_DELETING_THE_BLOB_WITH_NAME(logger, blobName, e, e); + ERROR_DELETING_BLOB_WITH_NAME(logger, blobName, e, e); } } From a5cc404f2998c9ba557188086cfe1f7f9a350e43 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Mon, 16 Oct 2023 11:03:08 +0200 Subject: [PATCH 065/133] chore: event names updated --- .../Challenges/Commands/DeleteExpiredChallenges/Handler.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Modules/Challenges/src/Challenges.Application/Challenges/Commands/DeleteExpiredChallenges/Handler.cs b/Modules/Challenges/src/Challenges.Application/Challenges/Commands/DeleteExpiredChallenges/Handler.cs index df2105e48c..5aadb8eed3 100644 --- a/Modules/Challenges/src/Challenges.Application/Challenges/Commands/DeleteExpiredChallenges/Handler.cs +++ b/Modules/Challenges/src/Challenges.Application/Challenges/Commands/DeleteExpiredChallenges/Handler.cs @@ -38,14 +38,14 @@ file static class LoggerExtensions private static readonly Action CANCELLATION_REQUESTED = LoggerMessage.Define( LogLevel.Debug, - new EventId(599235, "Enmeshed.Challenges.Application.DeleteExpiredChallenges.Handler.CancellationRequested"), + new EventId(599235, "Challenges.Application.DeleteExpiredChallenges.CancellationRequested"), "Cancellation was requested. Stopping execution..." ); private static readonly Action DELETION_SUCCESSFUL = LoggerMessage.Define( LogLevel.Debug, - new EventId(916630, ".DeleteExpiredChallenges.Handler.DeletionSuccessful"), + new EventId(916630, "Challenges.Application.DeleteExpiredChallenges.DeletionSuccessful"), "Deletion of '{deletedChallengesCount}' challenges successful." ); From 3cc2bc8138dfb22bce0f7aed9fe73a07f3ce4ae9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Mon, 16 Oct 2023 11:04:17 +0200 Subject: [PATCH 066/133] chore: delegate name updated --- .../Devices/Commands/ChangePassword/Handler.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Modules/Devices/src/Devices.Application/Devices/Commands/ChangePassword/Handler.cs b/Modules/Devices/src/Devices.Application/Devices/Commands/ChangePassword/Handler.cs index 43a687e77d..9e02bf1d28 100644 --- a/Modules/Devices/src/Devices.Application/Devices/Commands/ChangePassword/Handler.cs +++ b/Modules/Devices/src/Devices.Application/Devices/Commands/ChangePassword/Handler.cs @@ -39,7 +39,7 @@ public async Task Handle(ChangePasswordCommand request, CancellationToken cancel file static class LoggerExtensions { - private static readonly Action CHANGED_PASSWORD_FOR_DEVICE_WITH_ID = + private static readonly Action CHANGED_PASSWORD_FOR_DEVICE = LoggerMessage.Define( LogLevel.Information, new EventId(277894, "Devices.ChangedPasswordForDeviceWithId"), @@ -48,6 +48,6 @@ file static class LoggerExtensions public static void ChangedPasswordForDeviceWithId(this ILogger logger, DeviceId activeDevice) { - CHANGED_PASSWORD_FOR_DEVICE_WITH_ID(logger, activeDevice, default!); + CHANGED_PASSWORD_FOR_DEVICE(logger, activeDevice, default!); } } From d02d6408b664b66da97b729bbbe9f09d9523d91d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Mon, 16 Oct 2023 11:06:10 +0200 Subject: [PATCH 067/133] chore: delegate name updated --- .../Devices/Commands/DeleteDevice/Handler.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Modules/Devices/src/Devices.Application/Devices/Commands/DeleteDevice/Handler.cs b/Modules/Devices/src/Devices.Application/Devices/Commands/DeleteDevice/Handler.cs index 762ec294e0..864cece440 100644 --- a/Modules/Devices/src/Devices.Application/Devices/Commands/DeleteDevice/Handler.cs +++ b/Modules/Devices/src/Devices.Application/Devices/Commands/DeleteDevice/Handler.cs @@ -46,7 +46,7 @@ public async Task Handle(DeleteDeviceCommand request, CancellationToken cancella file static class LoggerExtensions { - private static readonly Action MARK_DEVICE_WITH_ID_AS_DELETED = + private static readonly Action MARKED_DEVICE_AS_DELETED = LoggerMessage.Define( LogLevel.Information, new EventId(776010, "Devices.MarkDeviceWithIdAsDeleted"), @@ -55,6 +55,6 @@ file static class LoggerExtensions public static void MarkDeviceWithIdAsDeleted(this ILogger logger, DeviceId deviceId) { - MARK_DEVICE_WITH_ID_AS_DELETED(logger, deviceId, default!); + MARKED_DEVICE_AS_DELETED(logger, deviceId, default!); } } From 32cac573057e804111733a0a195f1d026f2c5f9f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Mon, 16 Oct 2023 11:21:35 +0200 Subject: [PATCH 068/133] fix: \r\n replaced by \n in attempt to fix the error causing the formatting ci/cd test to fail --- .../ExceptionFilters/CustomExceptionFilter.cs | 518 +++++++++--------- 1 file changed, 259 insertions(+), 259 deletions(-) diff --git a/BuildingBlocks/src/BuildingBlocks.API/Mvc/ExceptionFilters/CustomExceptionFilter.cs b/BuildingBlocks/src/BuildingBlocks.API/Mvc/ExceptionFilters/CustomExceptionFilter.cs index 5983806a29..cadc86ca68 100644 --- a/BuildingBlocks/src/BuildingBlocks.API/Mvc/ExceptionFilters/CustomExceptionFilter.cs +++ b/BuildingBlocks/src/BuildingBlocks.API/Mvc/ExceptionFilters/CustomExceptionFilter.cs @@ -1,259 +1,259 @@ -using System; -using System.Net; -using System.Text.Json; -using System.Text.RegularExpressions; -using Enmeshed.BuildingBlocks.API.Extensions; -using Enmeshed.BuildingBlocks.Application.Abstractions.Exceptions; -using Enmeshed.BuildingBlocks.Domain; -using Enmeshed.BuildingBlocks.Domain.Errors; -using Enmeshed.BuildingBlocks.Infrastructure.Exceptions; -using Microsoft.ApplicationInsights.AspNetCore.Extensions; -using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Mvc.Filters; -using Microsoft.Extensions.Hosting; -using Microsoft.Extensions.Logging; -using ApplicationException = Enmeshed.BuildingBlocks.Application.Abstractions.Exceptions.ApplicationException; - -namespace Enmeshed.BuildingBlocks.API.Mvc.ExceptionFilters; - -[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] -public class CustomExceptionFilter : ExceptionFilterAttribute -{ - private const string ERROR_CODE_UNEXPECTED_EXCEPTION = "error.platform.unexpected"; - private const string ERROR_CODE_REQUEST_BODY_TOO_LARGE = "error.platform.requestBodyTooLarge"; - - private readonly IWebHostEnvironment _env; - private readonly ILogger _logger; - - public CustomExceptionFilter(ILogger logger, IWebHostEnvironment env) - { - _logger = logger; - _env = env; - } - - public override void OnException(ExceptionContext context) - { - context.HttpContext.Response.ContentType = "application/json"; - - HttpError httpError; - - switch (context.Exception) - { - case InfrastructureException infrastructureException: - _logger.InvalidUserInput(infrastructureException, infrastructureException.Code, infrastructureException.Message); - - httpError = CreateHttpErrorForInfrastructureException(infrastructureException); - - context.HttpContext.Response.StatusCode = - (int)GetStatusCodeForInfrastructureException(infrastructureException); - - break; - case ApplicationException applicationException: - _logger.InvalidUserInput(applicationException, applicationException.Code, applicationException.Message); - - httpError = CreateHttpErrorForApplicationException(applicationException); - - context.HttpContext.Response.StatusCode = - (int)GetStatusCodeForApplicationException(applicationException); - - break; - - case DomainException domainException: - _logger.InvalidUserInput(domainException, domainException.Code, domainException.Message); - - httpError = CreateHttpErrorForDomainException(domainException); - - context.HttpContext.Response.StatusCode = (int)GetStatusCodeForDomainException(domainException); - - break; - case BadHttpRequestException _: - _logger.RequestBodyTooLarge(ERROR_CODE_REQUEST_BODY_TOO_LARGE); - - httpError = HttpError.ForProduction( - ERROR_CODE_REQUEST_BODY_TOO_LARGE, - "The request body is too large.", - "" // TODO: add documentation link - ); - - context.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest; - - break; - default: - _logger.ErrorWhileProcessingRequestToUri(context.HttpContext.Request.GetUri(), context.Exception); - - httpError = CreateHttpErrorForUnexpectedException(context); - - context.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError; - - break; - } - - context.Result = new JsonResult(HttpResponseEnvelope.CreateError(httpError), - new JsonSerializerOptions - { - PropertyNamingPolicy = JsonNamingPolicy.CamelCase, DictionaryKeyPolicy = JsonNamingPolicy.CamelCase - }); - } - - private HttpError CreateHttpErrorForInfrastructureException(InfrastructureException infrastructureException) - { - var httpError = HttpError.ForProduction( - infrastructureException.Code, - infrastructureException.Message, - "" // TODO: add documentation link - ); - - return httpError; - } - - private HttpError CreateHttpErrorForApplicationException(ApplicationException applicationException) - { - var httpError = HttpError.ForProduction( - applicationException.Code, - applicationException.Message, - "", // TODO: add documentation link - data: GetCustomData(applicationException) - ); - - return httpError; - } - - private HttpError CreateHttpErrorForDomainException(DomainException domainException) - { - var httpError = HttpError.ForProduction( - domainException.Code, - domainException.Message, - "" // TODO: add documentation link - ); - - return httpError; - } - - private dynamic? GetCustomData(ApplicationException applicationException) - { - if (applicationException is QuotaExhaustedException quotaExhautedException) - { - return quotaExhautedException.ExhaustedMetricStatuses.Select(m => new - { -#pragma warning disable IDE0037 - MetricKey = m.MetricKey, - IsExhaustedUntil = m.IsExhaustedUntil -#pragma warning restore IDE0037 - }); - } - - return null; - } - - private HttpStatusCode GetStatusCodeForInfrastructureException(InfrastructureException exception) - { - return HttpStatusCode.BadRequest; - } - - private HttpStatusCode GetStatusCodeForApplicationException(ApplicationException exception) - { - return exception switch - { - NotFoundException _ => HttpStatusCode.NotFound, - ActionForbiddenException _ => HttpStatusCode.Forbidden, - QuotaExhaustedException _ => HttpStatusCode.TooManyRequests, - _ => HttpStatusCode.BadRequest - }; - } - - private HttpStatusCode GetStatusCodeForDomainException(DomainException exception) - { - if (exception.Code == GenericDomainErrors.NotFound().Code) - return HttpStatusCode.NotFound; - - return HttpStatusCode.BadRequest; - } - - private HttpError CreateHttpErrorForUnexpectedException(ExceptionContext context) - { - HttpError httpError; - - if (_env.IsDevelopment() || _env.IsLocal()) - { - var details = context.Exception.Message; - var innerException = context.Exception.InnerException; - - while (innerException != null) - { - details += "\r\n> " + innerException.Message; - innerException = innerException.InnerException; - } - - httpError = HttpError.ForDev( - ERROR_CODE_UNEXPECTED_EXCEPTION, - "An unexpected error occurred.", - "", // TODO: add documentation link - GetFormattedStackTrace(context.Exception), - details - ); - } - else - { - httpError = HttpError.ForProduction( - ERROR_CODE_UNEXPECTED_EXCEPTION, - "An unexpected error occurred.", - "" // TODO: add documentation link - ); - } - - return httpError; - } - - private IEnumerable GetFormattedStackTrace(Exception exception) - { - if (exception.StackTrace == null) - return Enumerable.Empty(); - - return - Regex.Matches(exception.StackTrace, "at .+").Select(m => m.Value.Trim()); - } -} - -file static class LoggerExtensions -{ - private static readonly Action INVALID_USER_INPUT = - LoggerMessage.Define( - LogLevel.Information, - new EventId(799306, "ExceptionFilter.InvalidUserInput"), - "An '{exception}' occurred. Error Code: '{code}'. Error message: '{message}'." - ); - - private static readonly Action REQUEST_BODY_TOO_LARGE = - LoggerMessage.Define( - LogLevel.Information, - new EventId(938218, "ExceptionFilter.RequestBodyTooLarge"), - "'{error_code}': The body of the request is too large." - ); - - private static readonly Action ERROR_WHILE_PROCESSING_REQUEST_TO_URI = - LoggerMessage.Define( - LogLevel.Error, - new EventId(259125, "ExceptionFilter.ErrorWhileProcessingRequestToUri"), - "Unexpected Error while processing request to '{uri}'." - ); - - public static void InvalidUserInput( - this ILogger logger, Exception e, string errorCode, string errorMessage) - { - INVALID_USER_INPUT(logger, nameof(e.GetType), errorCode, errorMessage, default!); - } - - public static void RequestBodyTooLarge( - this ILogger logger, string errorCode) - { - REQUEST_BODY_TOO_LARGE(logger, errorCode, default!); - } - - public static void ErrorWhileProcessingRequestToUri( - this ILogger logger, Uri uri, Exception e) - { - ERROR_WHILE_PROCESSING_REQUEST_TO_URI(logger, uri, e); - } -} +using System; +using System.Net; +using System.Text.Json; +using System.Text.RegularExpressions; +using Enmeshed.BuildingBlocks.API.Extensions; +using Enmeshed.BuildingBlocks.Application.Abstractions.Exceptions; +using Enmeshed.BuildingBlocks.Domain; +using Enmeshed.BuildingBlocks.Domain.Errors; +using Enmeshed.BuildingBlocks.Infrastructure.Exceptions; +using Microsoft.ApplicationInsights.AspNetCore.Extensions; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Filters; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using ApplicationException = Enmeshed.BuildingBlocks.Application.Abstractions.Exceptions.ApplicationException; + +namespace Enmeshed.BuildingBlocks.API.Mvc.ExceptionFilters; + +[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] +public class CustomExceptionFilter : ExceptionFilterAttribute +{ + private const string ERROR_CODE_UNEXPECTED_EXCEPTION = "error.platform.unexpected"; + private const string ERROR_CODE_REQUEST_BODY_TOO_LARGE = "error.platform.requestBodyTooLarge"; + + private readonly IWebHostEnvironment _env; + private readonly ILogger _logger; + + public CustomExceptionFilter(ILogger logger, IWebHostEnvironment env) + { + _logger = logger; + _env = env; + } + + public override void OnException(ExceptionContext context) + { + context.HttpContext.Response.ContentType = "application/json"; + + HttpError httpError; + + switch (context.Exception) + { + case InfrastructureException infrastructureException: + _logger.InvalidUserInput(infrastructureException, infrastructureException.Code, infrastructureException.Message); + + httpError = CreateHttpErrorForInfrastructureException(infrastructureException); + + context.HttpContext.Response.StatusCode = + (int)GetStatusCodeForInfrastructureException(infrastructureException); + + break; + case ApplicationException applicationException: + _logger.InvalidUserInput(applicationException, applicationException.Code, applicationException.Message); + + httpError = CreateHttpErrorForApplicationException(applicationException); + + context.HttpContext.Response.StatusCode = + (int)GetStatusCodeForApplicationException(applicationException); + + break; + + case DomainException domainException: + _logger.InvalidUserInput(domainException, domainException.Code, domainException.Message); + + httpError = CreateHttpErrorForDomainException(domainException); + + context.HttpContext.Response.StatusCode = (int)GetStatusCodeForDomainException(domainException); + + break; + case BadHttpRequestException _: + _logger.RequestBodyTooLarge(ERROR_CODE_REQUEST_BODY_TOO_LARGE); + + httpError = HttpError.ForProduction( + ERROR_CODE_REQUEST_BODY_TOO_LARGE, + "The request body is too large.", + "" // TODO: add documentation link + ); + + context.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest; + + break; + default: + _logger.ErrorWhileProcessingRequestToUri(context.HttpContext.Request.GetUri(), context.Exception); + + httpError = CreateHttpErrorForUnexpectedException(context); + + context.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError; + + break; + } + + context.Result = new JsonResult(HttpResponseEnvelope.CreateError(httpError), + new JsonSerializerOptions + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, DictionaryKeyPolicy = JsonNamingPolicy.CamelCase + }); + } + + private HttpError CreateHttpErrorForInfrastructureException(InfrastructureException infrastructureException) + { + var httpError = HttpError.ForProduction( + infrastructureException.Code, + infrastructureException.Message, + "" // TODO: add documentation link + ); + + return httpError; + } + + private HttpError CreateHttpErrorForApplicationException(ApplicationException applicationException) + { + var httpError = HttpError.ForProduction( + applicationException.Code, + applicationException.Message, + "", // TODO: add documentation link + data: GetCustomData(applicationException) + ); + + return httpError; + } + + private HttpError CreateHttpErrorForDomainException(DomainException domainException) + { + var httpError = HttpError.ForProduction( + domainException.Code, + domainException.Message, + "" // TODO: add documentation link + ); + + return httpError; + } + + private dynamic? GetCustomData(ApplicationException applicationException) + { + if (applicationException is QuotaExhaustedException quotaExhautedException) + { + return quotaExhautedException.ExhaustedMetricStatuses.Select(m => new + { +#pragma warning disable IDE0037 + MetricKey = m.MetricKey, + IsExhaustedUntil = m.IsExhaustedUntil +#pragma warning restore IDE0037 + }); + } + + return null; + } + + private HttpStatusCode GetStatusCodeForInfrastructureException(InfrastructureException exception) + { + return HttpStatusCode.BadRequest; + } + + private HttpStatusCode GetStatusCodeForApplicationException(ApplicationException exception) + { + return exception switch + { + NotFoundException _ => HttpStatusCode.NotFound, + ActionForbiddenException _ => HttpStatusCode.Forbidden, + QuotaExhaustedException _ => HttpStatusCode.TooManyRequests, + _ => HttpStatusCode.BadRequest + }; + } + + private HttpStatusCode GetStatusCodeForDomainException(DomainException exception) + { + if (exception.Code == GenericDomainErrors.NotFound().Code) + return HttpStatusCode.NotFound; + + return HttpStatusCode.BadRequest; + } + + private HttpError CreateHttpErrorForUnexpectedException(ExceptionContext context) + { + HttpError httpError; + + if (_env.IsDevelopment() || _env.IsLocal()) + { + var details = context.Exception.Message; + var innerException = context.Exception.InnerException; + + while (innerException != null) + { + details += "\r\n> " + innerException.Message; + innerException = innerException.InnerException; + } + + httpError = HttpError.ForDev( + ERROR_CODE_UNEXPECTED_EXCEPTION, + "An unexpected error occurred.", + "", // TODO: add documentation link + GetFormattedStackTrace(context.Exception), + details + ); + } + else + { + httpError = HttpError.ForProduction( + ERROR_CODE_UNEXPECTED_EXCEPTION, + "An unexpected error occurred.", + "" // TODO: add documentation link + ); + } + + return httpError; + } + + private IEnumerable GetFormattedStackTrace(Exception exception) + { + if (exception.StackTrace == null) + return Enumerable.Empty(); + + return + Regex.Matches(exception.StackTrace, "at .+").Select(m => m.Value.Trim()); + } +} + +file static class LoggerExtensions +{ + private static readonly Action INVALID_USER_INPUT = + LoggerMessage.Define( + LogLevel.Information, + new EventId(799306, "ExceptionFilter.InvalidUserInput"), + "An '{exception}' occurred. Error Code: '{code}'. Error message: '{message}'." + ); + + private static readonly Action REQUEST_BODY_TOO_LARGE = + LoggerMessage.Define( + LogLevel.Information, + new EventId(938218, "ExceptionFilter.RequestBodyTooLarge"), + "'{error_code}': The body of the request is too large." + ); + + private static readonly Action ERROR_WHILE_PROCESSING_REQUEST_TO_URI = + LoggerMessage.Define( + LogLevel.Error, + new EventId(259125, "ExceptionFilter.ErrorWhileProcessingRequestToUri"), + "Unexpected Error while processing request to '{uri}'." + ); + + public static void InvalidUserInput( + this ILogger logger, Exception e, string errorCode, string errorMessage) + { + INVALID_USER_INPUT(logger, nameof(e.GetType), errorCode, errorMessage, default!); + } + + public static void RequestBodyTooLarge( + this ILogger logger, string errorCode) + { + REQUEST_BODY_TOO_LARGE(logger, errorCode, default!); + } + + public static void ErrorWhileProcessingRequestToUri( + this ILogger logger, Uri uri, Exception e) + { + ERROR_WHILE_PROCESSING_REQUEST_TO_URI(logger, uri, e); + } +} From d1d84af0fcbf2abf0cf1cc7e9f493f0df23bdac2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Wed, 18 Oct 2023 08:20:07 +0200 Subject: [PATCH 069/133] chore: refactoring log statements with id and name to use LoggerMessageAttribute --- .../Devices/Commands/DeleteDevice/Handler.cs | 22 ++++++++----------- 1 file changed, 9 insertions(+), 13 deletions(-) diff --git a/Modules/Devices/src/Devices.Application/Devices/Commands/DeleteDevice/Handler.cs b/Modules/Devices/src/Devices.Application/Devices/Commands/DeleteDevice/Handler.cs index 864cece440..d78d0873f8 100644 --- a/Modules/Devices/src/Devices.Application/Devices/Commands/DeleteDevice/Handler.cs +++ b/Modules/Devices/src/Devices.Application/Devices/Commands/DeleteDevice/Handler.cs @@ -40,21 +40,17 @@ public async Task Handle(DeleteDeviceCommand request, CancellationToken cancella await _identitiesRepository.Update(device, cancellationToken); - _logger.MarkDeviceWithIdAsDeleted(request.DeviceId); + DeleteDeviceLogs.MarkDeviceWithIdAsDeleted(_logger, request.DeviceId); } } -file static class LoggerExtensions +internal static partial class DeleteDeviceLogs { - private static readonly Action MARKED_DEVICE_AS_DELETED = - LoggerMessage.Define( - LogLevel.Information, - new EventId(776010, "Devices.MarkDeviceWithIdAsDeleted"), - "Successfully marked device with id '{deviceId}' as deleted." - ); - - public static void MarkDeviceWithIdAsDeleted(this ILogger logger, DeviceId deviceId) - { - MARKED_DEVICE_AS_DELETED(logger, deviceId, default!); - } + [LoggerMessage( + EventId = 776010, + EventName = "Devices.MarkDeviceWithIdAsDeleted", + Level = LogLevel.Information, + Message = "Successfully marked device with id '{deviceId}' as deleted.")] + public static partial void MarkDeviceWithIdAsDeleted( + ILogger logger, string deviceId); } From da18788f7541d1d9da20c567204ba44a97e5a435 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Wed, 18 Oct 2023 08:21:52 +0200 Subject: [PATCH 070/133] chore: refactoring log statements with id and name to use LoggerMessageAttribute --- .../Commands/ChangePassword/Handler.cs | 22 ++++++++----------- 1 file changed, 9 insertions(+), 13 deletions(-) diff --git a/Modules/Devices/src/Devices.Application/Devices/Commands/ChangePassword/Handler.cs b/Modules/Devices/src/Devices.Application/Devices/Commands/ChangePassword/Handler.cs index 9e02bf1d28..29a6345c60 100644 --- a/Modules/Devices/src/Devices.Application/Devices/Commands/ChangePassword/Handler.cs +++ b/Modules/Devices/src/Devices.Application/Devices/Commands/ChangePassword/Handler.cs @@ -33,21 +33,17 @@ public async Task Handle(ChangePasswordCommand request, CancellationToken cancel if (!changePasswordResult.Succeeded) throw new OperationFailedException(ApplicationErrors.Devices.ChangePasswordFailed(changePasswordResult.Errors.First().Description)); - _logger.ChangedPasswordForDeviceWithId(_activeDevice); + ChangePassword.ChangedPasswordForDeviceWithId(_logger, _activeDevice); } } -file static class LoggerExtensions +internal static partial class ChangePassword { - private static readonly Action CHANGED_PASSWORD_FOR_DEVICE = - LoggerMessage.Define( - LogLevel.Information, - new EventId(277894, "Devices.ChangedPasswordForDeviceWithId"), - "Successfully changed password for device with id '{activeDevice}'." - ); - - public static void ChangedPasswordForDeviceWithId(this ILogger logger, DeviceId activeDevice) - { - CHANGED_PASSWORD_FOR_DEVICE(logger, activeDevice, default!); - } + [LoggerMessage( + EventId = 277894, + EventName = "Devices.ChangedPasswordForDeviceWithId", + Level = LogLevel.Information, + Message = "Successfully changed password for device with id '{activeDevice}'.")] + public static partial void ChangedPasswordForDeviceWithId( + ILogger logger, DeviceId activeDevice); } From fd0d2dd5afb003c78a61737c23e9766554cce73f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Wed, 18 Oct 2023 08:24:43 +0200 Subject: [PATCH 071/133] chore: partial class name change --- .../Devices/Commands/ChangePassword/Handler.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Modules/Devices/src/Devices.Application/Devices/Commands/ChangePassword/Handler.cs b/Modules/Devices/src/Devices.Application/Devices/Commands/ChangePassword/Handler.cs index 29a6345c60..f260d8248d 100644 --- a/Modules/Devices/src/Devices.Application/Devices/Commands/ChangePassword/Handler.cs +++ b/Modules/Devices/src/Devices.Application/Devices/Commands/ChangePassword/Handler.cs @@ -33,11 +33,11 @@ public async Task Handle(ChangePasswordCommand request, CancellationToken cancel if (!changePasswordResult.Succeeded) throw new OperationFailedException(ApplicationErrors.Devices.ChangePasswordFailed(changePasswordResult.Errors.First().Description)); - ChangePassword.ChangedPasswordForDeviceWithId(_logger, _activeDevice); + ChangePasswordLogs.ChangedPasswordForDeviceWithId(_logger, _activeDevice); } } -internal static partial class ChangePassword +internal static partial class ChangePasswordLogs { [LoggerMessage( EventId = 277894, From b20fc3db7886d32126db6c03e26bd0b7c278b7f5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Wed, 18 Oct 2023 08:25:44 +0200 Subject: [PATCH 072/133] chore: refactoring log statements with id and name to use LoggerMessageAttribute --- .../DeleteExpiredChallenges/Handler.cs | 22 +++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/Modules/Challenges/src/Challenges.Application/Challenges/Commands/DeleteExpiredChallenges/Handler.cs b/Modules/Challenges/src/Challenges.Application/Challenges/Commands/DeleteExpiredChallenges/Handler.cs index 5aadb8eed3..92fd46a82b 100644 --- a/Modules/Challenges/src/Challenges.Application/Challenges/Commands/DeleteExpiredChallenges/Handler.cs +++ b/Modules/Challenges/src/Challenges.Application/Challenges/Commands/DeleteExpiredChallenges/Handler.cs @@ -1,4 +1,5 @@ using Backbone.Modules.Challenges.Application.Infrastructure.Persistence.Repository; +using Enmeshed.DevelopmentKit.Identity.ValueObjects; using MediatR; using Microsoft.Extensions.Logging; @@ -19,13 +20,13 @@ public async Task Handle(DeleteExpiredChallenge { if (cancellationToken.IsCancellationRequested) { - _logger.CancellationRequested(); + DeleteExpiredChallengesLogs.CancellationRequested(_logger); return DeleteExpiredChallengesResponse.NoDeletedChallenges(); } var deletedChallengesCount = await _challengesRepository.DeleteExpiredChallenges(cancellationToken); - _logger.DeletionSuccessful(deletedChallengesCount); + DeleteExpiredChallengesLogs.DeletionSuccessful(_logger, deletedChallengesCount); var response = new DeleteExpiredChallengesResponse(deletedChallengesCount); @@ -59,3 +60,20 @@ public static void DeletionSuccessful(this ILogger logger, int numberOfDeletedCh DELETION_SUCCESSFUL(logger, numberOfDeletedChallenges, default!); } } + +internal static partial class DeleteExpiredChallengesLogs +{ + [LoggerMessage( + EventId = 599235, + EventName = "Challenges.Application.DeleteExpiredChallenges.CancellationRequested", + Level = LogLevel.Debug, + Message = "Cancellation was requested. Stopping execution...")] + public static partial void CancellationRequested(ILogger logger); + + [LoggerMessage( + EventId = 916630, + EventName = "Challenges.Application.DeleteExpiredChallenges.DeletionSuccessful", + Level = LogLevel.Debug, + Message = "Deletion of '{deletedChallengesCount}' challenges successful.")] + public static partial void DeletionSuccessful(ILogger logger, int deletedChallengesCount); +} From 291b472aebd333bf51888f6b30cdaed2a31c00b3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Wed, 18 Oct 2023 08:26:05 +0200 Subject: [PATCH 073/133] chore: formatting change --- .../Devices/Commands/ChangePassword/Handler.cs | 3 +-- .../Devices/Commands/DeleteDevice/Handler.cs | 3 +-- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/Modules/Devices/src/Devices.Application/Devices/Commands/ChangePassword/Handler.cs b/Modules/Devices/src/Devices.Application/Devices/Commands/ChangePassword/Handler.cs index f260d8248d..eb4b225368 100644 --- a/Modules/Devices/src/Devices.Application/Devices/Commands/ChangePassword/Handler.cs +++ b/Modules/Devices/src/Devices.Application/Devices/Commands/ChangePassword/Handler.cs @@ -44,6 +44,5 @@ internal static partial class ChangePasswordLogs EventName = "Devices.ChangedPasswordForDeviceWithId", Level = LogLevel.Information, Message = "Successfully changed password for device with id '{activeDevice}'.")] - public static partial void ChangedPasswordForDeviceWithId( - ILogger logger, DeviceId activeDevice); + public static partial void ChangedPasswordForDeviceWithId(ILogger logger, DeviceId activeDevice); } diff --git a/Modules/Devices/src/Devices.Application/Devices/Commands/DeleteDevice/Handler.cs b/Modules/Devices/src/Devices.Application/Devices/Commands/DeleteDevice/Handler.cs index d78d0873f8..219e0b5030 100644 --- a/Modules/Devices/src/Devices.Application/Devices/Commands/DeleteDevice/Handler.cs +++ b/Modules/Devices/src/Devices.Application/Devices/Commands/DeleteDevice/Handler.cs @@ -51,6 +51,5 @@ internal static partial class DeleteDeviceLogs EventName = "Devices.MarkDeviceWithIdAsDeleted", Level = LogLevel.Information, Message = "Successfully marked device with id '{deviceId}' as deleted.")] - public static partial void MarkDeviceWithIdAsDeleted( - ILogger logger, string deviceId); + public static partial void MarkDeviceWithIdAsDeleted(ILogger logger, string deviceId); } From e3224768206afe4fd49e19beaa858e356b3b7e64 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Wed, 18 Oct 2023 08:37:23 +0200 Subject: [PATCH 074/133] chore: refactoring log statements with id and name to use LoggerMessageAttribute --- .../Infrastructure/Reporter/LogReporter.cs | 42 +++++++------------ 1 file changed, 16 insertions(+), 26 deletions(-) diff --git a/Modules/Tokens/src/Tokens.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs b/Modules/Tokens/src/Tokens.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs index fdf8493765..109d35b634 100644 --- a/Modules/Tokens/src/Tokens.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs +++ b/Modules/Tokens/src/Tokens.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs @@ -20,12 +20,12 @@ public void Complete() { foreach (var databaseId in _databaseIds) { - _logger.NoBlobForTokenId(databaseId); + TokensLogs.NoBlobForTokenId(_logger, databaseId); } foreach (var blobId in _blobIds) { - _logger.NoDatabaseEntryForBlobId(blobId); + TokensLogs.NoDatabaseEntryForBlobId(_logger, blobId); } } @@ -40,29 +40,19 @@ public void ReportOrphanedDatabaseId(TokenId id) } } -file static class LoggerExtensions +internal static partial class TokensLogs { - private static readonly Action NO_BLOB_FOR_TOKEN_ID = - LoggerMessage.Define( - LogLevel.Error, - new EventId(826083, "Tokens.LogReporter.NoBlobForTokenId"), - "No blob found for token id: '{tokenId}'." - ); - - private static readonly Action NO_DATABASE_ENTRY_FOR_BLOB_ID = - LoggerMessage.Define( - LogLevel.Error, - new EventId(271286, "Tokens.LogReporter.NoDatabaseEntryForBlobId"), - "No database entry found for blob id: '{blobId}'." - ); - - public static void NoBlobForTokenId(this ILogger logger, TokenId tokenId) - { - NO_BLOB_FOR_TOKEN_ID(logger, tokenId, default!); - } - - public static void NoDatabaseEntryForBlobId(this ILogger logger, string blobId) - { - NO_DATABASE_ENTRY_FOR_BLOB_ID(logger, blobId, default!); - } + [LoggerMessage( + EventId = 826083, + EventName = "Tokens.LogReporter.NoBlobForTokenId", + Level = LogLevel.Error, + Message = "No blob found for token id: '{tokenId}'.")] + public static partial void NoBlobForTokenId(ILogger logger, TokenId tokenId); + + [LoggerMessage( + EventId = 271286, + EventName = "Tokens.LogReporter.NoDatabaseEntryForBlobId", + Level = LogLevel.Error, + Message = "No database entry found for blob id: '{blobId}'.")] + public static partial void NoDatabaseEntryForBlobId(ILogger logger, string blobId); } From 497de4cd75f1a146f1c01d08fa34054ffa1ec04f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Wed, 18 Oct 2023 08:44:22 +0200 Subject: [PATCH 075/133] chore: refactoring log statements with id and name to use LoggerMessageAttribute --- .../Infrastructure/Reporter/LogReporter.cs | 42 +++++++------------ 1 file changed, 16 insertions(+), 26 deletions(-) diff --git a/Modules/Synchronization/src/Synchronization.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs b/Modules/Synchronization/src/Synchronization.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs index 50cdc0a3f6..ebc952a90d 100644 --- a/Modules/Synchronization/src/Synchronization.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs +++ b/Modules/Synchronization/src/Synchronization.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs @@ -20,12 +20,12 @@ public void Complete() { foreach (var databaseId in _databaseIds) { - _logger.NoBlobForDatawalletModificationId(databaseId); + SynchronizationLogs.NoBlobForDatawalletModificationId(_logger, databaseId); } foreach (var blobId in _blobIds) { - _logger.NoDatabaseEntryForBlobId(blobId); + SynchronizationLogs.NoDatabaseEntryForBlobId(_logger, blobId); } } @@ -40,29 +40,19 @@ public void ReportOrphanedDatabaseId(DatawalletModificationId id) } } -file static class LoggerExtensions +internal static partial class SynchronizationLogs { - private static readonly Action NO_BLOB_FOR_DATAWALLET_MODIFICATION_ID = - LoggerMessage.Define( - LogLevel.Error, - new EventId(525684, "Synchronization.LogReporter.NoBlobForDatawalletModificationId"), - "No blob found for datawallet modification id: '{databaseId}'." - ); - - private static readonly Action NO_DATABASE_ENTRY_FOR_BLOB_ID = - LoggerMessage.Define( - LogLevel.Error, - new EventId(560290, "Synchronization.LogReporter.NoDatabaseEntryForBlobId"), - "No database entry found for blob id: '{blobId}'." - ); - - public static void NoBlobForDatawalletModificationId(this ILogger logger, DatawalletModificationId datawalletModificationId) - { - NO_BLOB_FOR_DATAWALLET_MODIFICATION_ID(logger, datawalletModificationId, default!); - } - - public static void NoDatabaseEntryForBlobId(this ILogger logger, string blobId) - { - NO_DATABASE_ENTRY_FOR_BLOB_ID(logger, blobId, default!); - } + [LoggerMessage( + EventId = 525684, + EventName = "Synchronization.LogReporter.NoBlobForDatawalletModificationId", + Level = LogLevel.Error, + Message = "No blob found for datawallet modification id: '{databaseId}'.")] + public static partial void NoBlobForDatawalletModificationId(ILogger logger, DatawalletModificationId databaseId); + + [LoggerMessage( + EventId = 560290, + EventName = "Synchronization.LogReporter.NoDatabaseEntryForBlobId", + Level = LogLevel.Error, + Message = "No database entry found for blob id: '{blobId}'.")] + public static partial void NoDatabaseEntryForBlobId(ILogger logger, string blobId); } From f0bf73bf48a5c711a0b6c586b772eb2fb8edb1b4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Wed, 18 Oct 2023 08:47:28 +0200 Subject: [PATCH 076/133] chore: refactoring log statements with id and name to use LoggerMessageAttribute --- .../Infrastructure/Reporter/LogReporter.cs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/Modules/Relationships/src/Relationships.Jobs.SanityCheck.RelationshipTemplate/Infrastructure/Reporter/LogReporter.cs b/Modules/Relationships/src/Relationships.Jobs.SanityCheck.RelationshipTemplate/Infrastructure/Reporter/LogReporter.cs index 7d75d8660f..fc7b01478a 100644 --- a/Modules/Relationships/src/Relationships.Jobs.SanityCheck.RelationshipTemplate/Infrastructure/Reporter/LogReporter.cs +++ b/Modules/Relationships/src/Relationships.Jobs.SanityCheck.RelationshipTemplate/Infrastructure/Reporter/LogReporter.cs @@ -66,3 +66,20 @@ public static void NoDatabaseEntryForBlobId(this ILogger logger, string blobId) NO_DATABASE_ENTRY_FOR_BLOB_ID(logger, blobId, default!); } } + +internal static partial class RelationshipsLogs +{ + [LoggerMessage( + EventId = 231727, + EventName = "Relationships.LogReporter.NoBlobForRelationshipTemplateId", + Level = LogLevel.Error, + Message = "No blob found for relationship template id: '{databaseId}'.")] + public static partial void NoBlobForRelationshipTemplateId(ILogger logger, RelationshipTemplateId databaseId); + + [LoggerMessage( + EventId = 232800, + EventName = "Relationships.LogReporter.NoDatabaseEntryForBlobId", + Level = LogLevel.Error, + Message = "No database entry found for blob id: '{blobId}'.")] + public static partial void NoDatabaseEntryForBlobId(ILogger logger, string blobId); +} From 1b0b7e2ad5b0b9d63072758192f1ddb5426971a9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Wed, 18 Oct 2023 08:48:21 +0200 Subject: [PATCH 077/133] chore: internal class name change --- .../Infrastructure/Reporter/LogReporter.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Modules/Relationships/src/Relationships.Jobs.SanityCheck.RelationshipTemplate/Infrastructure/Reporter/LogReporter.cs b/Modules/Relationships/src/Relationships.Jobs.SanityCheck.RelationshipTemplate/Infrastructure/Reporter/LogReporter.cs index fc7b01478a..a654cba080 100644 --- a/Modules/Relationships/src/Relationships.Jobs.SanityCheck.RelationshipTemplate/Infrastructure/Reporter/LogReporter.cs +++ b/Modules/Relationships/src/Relationships.Jobs.SanityCheck.RelationshipTemplate/Infrastructure/Reporter/LogReporter.cs @@ -67,7 +67,7 @@ public static void NoDatabaseEntryForBlobId(this ILogger logger, string blobId) } } -internal static partial class RelationshipsLogs +internal static partial class RelationshipTemplateLogs { [LoggerMessage( EventId = 231727, From d4da2024b66bb785f8c109e83ddab33b3eb7ed9d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Wed, 18 Oct 2023 08:49:33 +0200 Subject: [PATCH 078/133] chore: refactoring log statements with id and name to use LoggerMessageAttribute --- .../Infrastructure/Reporter/LogReporter.cs | 42 +++++++------------ 1 file changed, 16 insertions(+), 26 deletions(-) diff --git a/Modules/Relationships/src/Relationships.Jobs.SanityCheck.RelationshipChange/Infrastructure/Reporter/LogReporter.cs b/Modules/Relationships/src/Relationships.Jobs.SanityCheck.RelationshipChange/Infrastructure/Reporter/LogReporter.cs index b5d5222e55..36e382ca49 100644 --- a/Modules/Relationships/src/Relationships.Jobs.SanityCheck.RelationshipChange/Infrastructure/Reporter/LogReporter.cs +++ b/Modules/Relationships/src/Relationships.Jobs.SanityCheck.RelationshipChange/Infrastructure/Reporter/LogReporter.cs @@ -20,12 +20,12 @@ public void Complete() { foreach (var databaseId in _databaseIds) { - _logger.NoBlobForRelationshipChangeId(databaseId); + RelationshipChangeLogs.NoBlobForRelationshipChangeId(_logger, databaseId); } foreach (var blobId in _blobIds) { - _logger.NoDatabaseEntryForBlobId(blobId); + RelationshipChangeLogs.NoDatabaseEntryForBlobId(_logger, blobId); } } @@ -40,29 +40,19 @@ public void ReportOrphanedDatabaseId(RelationshipChangeId id) } } -file static class LoggerExtensions +internal static partial class RelationshipChangeLogs { - private static readonly Action NO_BLOB_FOR_RELATIONSHIP_CHANGE_ID = - LoggerMessage.Define( - LogLevel.Error, - new EventId(349287, "Relationships.LogReporter.NoBlobForRelationshipChangeId"), - "No blob found for relationship change id: '{databaseId}'." - ); - - private static readonly Action NO_DATABASE_ENTRY_FOR_BLOB_ID = - LoggerMessage.Define( - LogLevel.Error, - new EventId(429922, "Relationships.LogReporter.NoDatabaseEntryForBlobId"), - "No database entry found for blob id: '{blobId}'." - ); - - public static void NoBlobForRelationshipChangeId(this ILogger logger, RelationshipChangeId relationshipChangeId) - { - NO_BLOB_FOR_RELATIONSHIP_CHANGE_ID(logger, relationshipChangeId, default!); - } - - public static void NoDatabaseEntryForBlobId(this ILogger logger, string blobId) - { - NO_DATABASE_ENTRY_FOR_BLOB_ID(logger, blobId, default!); - } + [LoggerMessage( + EventId = 349287, + EventName = "Relationships.LogReporter.NoBlobForRelationshipChangeId", + Level = LogLevel.Error, + Message = "No blob found for relationship change id: '{databaseId}'.")] + public static partial void NoBlobForRelationshipChangeId(ILogger logger, RelationshipChangeId databaseId); + + [LoggerMessage( + EventId = 429922, + EventName = "Relationships.LogReporter.NoDatabaseEntryForBlobId", + Level = LogLevel.Error, + Message = "No database entry found for blob id: '{blobId}'.")] + public static partial void NoDatabaseEntryForBlobId(ILogger logger, string blobId); } From 6864b3ccb176ed33503cedce5b074421569bd264 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Wed, 18 Oct 2023 08:50:53 +0200 Subject: [PATCH 079/133] chore: refactoring log statements with id and name to use LoggerMessageAttribute --- .../Repository/RelationshipsRepository.cs | 21 +++++++------------ 1 file changed, 8 insertions(+), 13 deletions(-) diff --git a/Modules/Relationships/src/Relationships.Infrastructure/Persistence/Database/Repository/RelationshipsRepository.cs b/Modules/Relationships/src/Relationships.Infrastructure/Persistence/Database/Repository/RelationshipsRepository.cs index ba90544114..5a893b0525 100644 --- a/Modules/Relationships/src/Relationships.Infrastructure/Persistence/Database/Repository/RelationshipsRepository.cs +++ b/Modules/Relationships/src/Relationships.Infrastructure/Persistence/Database/Repository/RelationshipsRepository.cs @@ -172,7 +172,7 @@ private async Task SaveContentOfLatestChange(Relationship relationship) } catch (BlobAlreadyExistsException ex) { - _logger.ErrorTryingToSaveRelationshipChange(latestChange.Id, ex.BlobName, ex); + RelationshipRepositoryLogs.ErrorTryingToSaveRelationshipChange(_logger, latestChange.Id, ex.BlobName); } } @@ -197,17 +197,12 @@ private async Task FillContentOfChanges(IEnumerable changes) } } -file static class LoggerExtensions +internal static partial class RelationshipRepositoryLogs { - private static readonly Action ERROR_TRYING_TO_SAVE_RELATIONSHIP_CHANGE = - LoggerMessage.Define( - LogLevel.Error, - new EventId(664861, "Relationships.RelationshipsRepository.ErrorTryingToSaveRelationshipChange"), - "There was an error while trying to save the content of the RelationshipChange with the id '{id}'. The name of the blob was '{name}'." - ); - - public static void ErrorTryingToSaveRelationshipChange(this ILogger logger, RelationshipChangeId id, string name, Exception e) - { - ERROR_TRYING_TO_SAVE_RELATIONSHIP_CHANGE(logger, id, name, e); - } + [LoggerMessage( + EventId = 664861, + EventName = "Relationships.RelationshipsRepository.ErrorTryingToSaveRelationshipChange", + Level = LogLevel.Error, + Message = "There was an error while trying to save the content of the RelationshipChange with the id '{id}'. The name of the blob was '{name}'.")] + public static partial void ErrorTryingToSaveRelationshipChange(ILogger logger, RelationshipChangeId id, string name); } From 9a563abbb35b459845d9d7d50206ab1c4672b2f7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Wed, 18 Oct 2023 08:51:34 +0200 Subject: [PATCH 080/133] chore: refactoring log statements with id and name to use LoggerMessageAttribute --- .../DeleteTierQuotaDefinition/Handler.cs | 21 +++++++------------ 1 file changed, 8 insertions(+), 13 deletions(-) diff --git a/Modules/Quotas/src/Quotas.Application/Tiers/Commands/DeleteTierQuotaDefinition/Handler.cs b/Modules/Quotas/src/Quotas.Application/Tiers/Commands/DeleteTierQuotaDefinition/Handler.cs index 80420071ab..c6cded12ef 100644 --- a/Modules/Quotas/src/Quotas.Application/Tiers/Commands/DeleteTierQuotaDefinition/Handler.cs +++ b/Modules/Quotas/src/Quotas.Application/Tiers/Commands/DeleteTierQuotaDefinition/Handler.cs @@ -33,23 +33,18 @@ public async Task Handle(DeleteTierQuotaDefinitionCommand request, CancellationT await _tiersRepository.Update(tier, cancellationToken); - _logger.DeletedTierQuota(request.TierQuotaDefinitionId); + DeleteTierQuotaDefinitionLogs.DeletedTierQuota(_logger, request.TierQuotaDefinitionId); _eventBus.Publish(new TierQuotaDefinitionDeletedIntegrationEvent(tier.Id, request.TierQuotaDefinitionId)); } } -file static class LoggerExtensions +internal static partial class DeleteTierQuotaDefinitionLogs { - private static readonly Action DELETED_TIER_QUOTA = - LoggerMessage.Define( - LogLevel.Information, - new EventId(519284, "Quotas.DeletedTierQuota"), - "Successfully deleted tier quota definition with id: '{tierQuotaDefinitionId}'." - ); - - public static void DeletedTierQuota(this ILogger logger, string tierQuotaDefinitionId) - { - DELETED_TIER_QUOTA(logger, tierQuotaDefinitionId, default!); - } + [LoggerMessage( + EventId = 519284, + EventName = "Quotas.DeletedTierQuota", + Level = LogLevel.Information, + Message = "Successfully deleted tier quota definition with id: '{tierQuotaDefinitionId}'.")] + public static partial void DeletedTierQuota(ILogger logger, string tierQuotaDefinitionId); } From cf73218c0ba9fa66d3be68f76b36332190c49939 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Wed, 18 Oct 2023 08:52:25 +0200 Subject: [PATCH 081/133] chore: refactoring log statements with id and name to use LoggerMessageAttribute --- .../DeleteQuotaForIdentity/Handler.cs | 21 +++++++------------ 1 file changed, 8 insertions(+), 13 deletions(-) diff --git a/Modules/Quotas/src/Quotas.Application/Tiers/Commands/DeleteQuotaForIdentity/Handler.cs b/Modules/Quotas/src/Quotas.Application/Tiers/Commands/DeleteQuotaForIdentity/Handler.cs index 018595011c..7fda0a884a 100644 --- a/Modules/Quotas/src/Quotas.Application/Tiers/Commands/DeleteQuotaForIdentity/Handler.cs +++ b/Modules/Quotas/src/Quotas.Application/Tiers/Commands/DeleteQuotaForIdentity/Handler.cs @@ -33,21 +33,16 @@ public async Task Handle(DeleteQuotaForIdentityCommand request, CancellationToke await _identitiesRepository.Update(identity, cancellationToken); - _logger.DeletedQuota(request.IndividualQuotaId); + DeleteQuotaForIdentityLogs.DeletedQuota(_logger, request.IndividualQuotaId); } } -file static class LoggerExtensions +internal static partial class DeleteQuotaForIdentityLogs { - private static readonly Action DELETED_QUOTA = - LoggerMessage.Define( - LogLevel.Information, - new EventId(247156, "Quotas.DeleteQuota"), - "Successfully deleted individual quota with id: '{individualQuotaId}'." - ); - - public static void DeletedQuota(this ILogger logger, string individualQuotaId) - { - DELETED_QUOTA(logger, individualQuotaId, default!); - } + [LoggerMessage( + EventId = 247156, + EventName = "Quotas.DeleteQuota", + Level = LogLevel.Information, + Message = "Successfully deleted individual quota with id: '{individualQuotaId}'.")] + public static partial void DeletedQuota(ILogger logger, string individualQuotaId); } From a30886d842057d1bd760a780cf69acd40e2a14fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Wed, 18 Oct 2023 08:53:35 +0200 Subject: [PATCH 082/133] chore: refactoring log statements with id and name to use LoggerMessageAttribute --- .../Commands/CreateQuotaForTier/Handler.cs | 21 +++++++------------ 1 file changed, 8 insertions(+), 13 deletions(-) diff --git a/Modules/Quotas/src/Quotas.Application/Tiers/Commands/CreateQuotaForTier/Handler.cs b/Modules/Quotas/src/Quotas.Application/Tiers/Commands/CreateQuotaForTier/Handler.cs index 9dbd1e2b5a..c3c1b1a986 100644 --- a/Modules/Quotas/src/Quotas.Application/Tiers/Commands/CreateQuotaForTier/Handler.cs +++ b/Modules/Quotas/src/Quotas.Application/Tiers/Commands/CreateQuotaForTier/Handler.cs @@ -44,7 +44,7 @@ public async Task Handle(CreateQuotaForTierCommand reque await _tiersRepository.Update(tier, cancellationToken); - _logger.CreatedQuotaForTier(tier.Id, tier.Name); + CreateQuotaForTierLogs.CreatedQuotaForTier(_logger, tier.Id, tier.Name); _eventBus.Publish(new QuotaCreatedForTierIntegrationEvent(tier.Id, result.Value.Id)); @@ -53,17 +53,12 @@ public async Task Handle(CreateQuotaForTierCommand reque } } -file static class LoggerExtensions +internal static partial class CreateQuotaForTierLogs { - private static readonly Action CREATED_QUOTA_FOR_TIER = - LoggerMessage.Define( - LogLevel.Information, - new EventId(346835, "Quotas.CreatedQuotaForTier"), - "Successfully created Quota for Tier. Tier ID: '{tierId}', Tier Name: '{tierName}'." - ); - - public static void CreatedQuotaForTier(this ILogger logger, TierId tierId, string identityAddress) - { - CREATED_QUOTA_FOR_TIER(logger, tierId, identityAddress, default!); - } + [LoggerMessage( + EventId = 346835, + EventName = "Quotas.CreatedQuotaForTier", + Level = LogLevel.Information, + Message = "Successfully created Quota for Tier. Tier ID: '{tierId}', Tier Name: '{tierName}'.")] + public static partial void CreatedQuotaForTier(ILogger logger, TierId tierId, string tierName); } From 86d96d6fed2c1e5a08232818c99daa09286dd4d3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Wed, 18 Oct 2023 08:53:40 +0200 Subject: [PATCH 083/133] chore: refactoring log statements with id and name to use LoggerMessageAttribute --- .../CreateQuotaForIdentity/Handler.cs | 21 +++++++------------ 1 file changed, 8 insertions(+), 13 deletions(-) diff --git a/Modules/Quotas/src/Quotas.Application/Tiers/Commands/CreateQuotaForIdentity/Handler.cs b/Modules/Quotas/src/Quotas.Application/Tiers/Commands/CreateQuotaForIdentity/Handler.cs index 5527fafe84..3f706503eb 100644 --- a/Modules/Quotas/src/Quotas.Application/Tiers/Commands/CreateQuotaForIdentity/Handler.cs +++ b/Modules/Quotas/src/Quotas.Application/Tiers/Commands/CreateQuotaForIdentity/Handler.cs @@ -39,7 +39,7 @@ public async Task Handle(CreateQuotaForIdentityCommand reque await _identitiesRepository.Update(identity, cancellationToken); - _logger.CreatedQuotasForIdentities(identity.Address); + CreateQuotaForIdentityLogs.CreatedQuotasForIdentities(_logger, identity.Address); var identityAddresses = new List { identity.Address }; var metrics = new List { metric.Key.Value }; @@ -50,17 +50,12 @@ public async Task Handle(CreateQuotaForIdentityCommand reque } } -file static class LoggerExtensions +internal static partial class CreateQuotaForIdentityLogs { - private static readonly Action CREATED_QUOTAS_FOR_IDENTITY = - LoggerMessage.Define( - LogLevel.Information, - new EventId(868289, "Quotas.CreatedQuotasForIdentities"), - "Successfully created Quota for Identity. Identity Address: '{identityAddress}'." - ); - - public static void CreatedQuotasForIdentities(this ILogger logger, string identityAddress) - { - CREATED_QUOTAS_FOR_IDENTITY(logger, identityAddress, default!); - } + [LoggerMessage( + EventId = 868289, + EventName = "Quotas.CreatedQuotasForIdentities", + Level = LogLevel.Information, + Message = "Successfully created Quota for Identity. Identity Address: '{identityAddress}'.")] + public static partial void CreatedQuotasForIdentities(ILogger logger, string identityAddress); } From 059468f9c07fa602f8edeb38f6bb23ccfc6474aa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Wed, 18 Oct 2023 08:54:38 +0200 Subject: [PATCH 084/133] chore: refactoring log statements with id and name to use LoggerMessageAttribute --- ...efinitionDeletedIntegrationEventHandler.cs | 21 +++++++------------ 1 file changed, 8 insertions(+), 13 deletions(-) diff --git a/Modules/Quotas/src/Quotas.Application/IntegrationEvents/Incoming/TierQuotaDefinitionDeleted/TierQuotaDefinitionDeletedIntegrationEventHandler.cs b/Modules/Quotas/src/Quotas.Application/IntegrationEvents/Incoming/TierQuotaDefinitionDeleted/TierQuotaDefinitionDeletedIntegrationEventHandler.cs index ae430b8d2c..f18439d9e1 100644 --- a/Modules/Quotas/src/Quotas.Application/IntegrationEvents/Incoming/TierQuotaDefinitionDeleted/TierQuotaDefinitionDeletedIntegrationEventHandler.cs +++ b/Modules/Quotas/src/Quotas.Application/IntegrationEvents/Incoming/TierQuotaDefinitionDeleted/TierQuotaDefinitionDeletedIntegrationEventHandler.cs @@ -40,21 +40,16 @@ public async Task Handle(TierQuotaDefinitionDeletedIntegrationEvent @event) await _identitiesRepository.Update(identitiesWithTier, CancellationToken.None); - _logger.DeletedQuotasForIdentities(); + TierQuotaDefinitionDeletedLogs.DeletedQuotasForIdentities(_logger); } } -file static class LoggerExtensions +internal static partial class TierQuotaDefinitionDeletedLogs { - private static readonly Action DELETED_QUOTAS_FOR_IDENTITIES = - LoggerMessage.Define( - LogLevel.Information, - new EventId(942996, "Quotas.TierQuotaDefinitionDeletedIntegrationEventHandler.DeletedQuotasForIdentities"), - "Successfully deleted quotas for Identities." - ); - - public static void DeletedQuotasForIdentities(this ILogger logger) - { - DELETED_QUOTAS_FOR_IDENTITIES(logger, default!); - } + [LoggerMessage( + EventId = 942996, + EventName = "Quotas.TierQuotaDefinitionDeletedIntegrationEventHandler.DeletedQuotasForIdentities", + Level = LogLevel.Information, + Message = "Successfully deleted quotas for Identities.")] + public static partial void DeletedQuotasForIdentities(ILogger logger); } From 5c5ec18ca5eddd21b3ca7dce1a931a584f6d413d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Wed, 18 Oct 2023 08:55:44 +0200 Subject: [PATCH 085/133] chore: refactoring log statements with id and name to use LoggerMessageAttribute --- .../TierDeletedIntegrationEventHandler.cs | 21 +++++++------------ 1 file changed, 8 insertions(+), 13 deletions(-) diff --git a/Modules/Quotas/src/Quotas.Application/IntegrationEvents/Incoming/TierDeleted/TierDeletedIntegrationEventHandler.cs b/Modules/Quotas/src/Quotas.Application/IntegrationEvents/Incoming/TierDeleted/TierDeletedIntegrationEventHandler.cs index 6e9c5deed3..11672115a6 100644 --- a/Modules/Quotas/src/Quotas.Application/IntegrationEvents/Incoming/TierDeleted/TierDeletedIntegrationEventHandler.cs +++ b/Modules/Quotas/src/Quotas.Application/IntegrationEvents/Incoming/TierDeleted/TierDeletedIntegrationEventHandler.cs @@ -21,21 +21,16 @@ public async Task Handle(TierDeletedIntegrationEvent integrationEvent) await _tiersRepository.RemoveById(tier.Id); - _logger.TierDeleted(tier.Id, tier.Name); + TierDeletedLogs.TierDeleted(_logger, tier.Id, tier.Name); } } -file static class LoggerExtensions +internal static partial class TierDeletedLogs { - private static readonly Action TIER_DELETED = - LoggerMessage.Define( - LogLevel.Information, - new EventId(582359, "Quotas.TierDeletedIntegrationEventHandler.TierDeleted"), - "Successfully deleted tier. Tier ID: '{tierId}', Tier Name: '{tierName}'." - ); - - public static void TierDeleted(this ILogger logger, TierId tierId, string name) - { - TIER_DELETED(logger, tierId, name, default!); - } + [LoggerMessage( + EventId = 582359, + EventName = "Quotas.TierDeletedIntegrationEventHandler.TierDeleted", + Level = LogLevel.Information, + Message = "Successfully deleted tier. Tier ID: '{tierId}', Tier Name: '{tierName}'.")] + public static partial void TierDeleted(ILogger logger, TierId tierId, string tierName); } From 9a0934cbb25cd8792df1ea7a6422a7408d8020c4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Wed, 18 Oct 2023 08:56:29 +0200 Subject: [PATCH 086/133] chore: refactoring log statements with id and name to use LoggerMessageAttribute --- .../TierCreatedIntegrationEventHandler.cs | 21 +++++++------------ 1 file changed, 8 insertions(+), 13 deletions(-) diff --git a/Modules/Quotas/src/Quotas.Application/IntegrationEvents/Incoming/TierCreated/TierCreatedIntegrationEventHandler.cs b/Modules/Quotas/src/Quotas.Application/IntegrationEvents/Incoming/TierCreated/TierCreatedIntegrationEventHandler.cs index 937cc0acda..b37190f44e 100644 --- a/Modules/Quotas/src/Quotas.Application/IntegrationEvents/Incoming/TierCreated/TierCreatedIntegrationEventHandler.cs +++ b/Modules/Quotas/src/Quotas.Application/IntegrationEvents/Incoming/TierCreated/TierCreatedIntegrationEventHandler.cs @@ -20,21 +20,16 @@ public async Task Handle(TierCreatedIntegrationEvent integrationEvent) var tier = new Tier(new TierId(integrationEvent.Id), integrationEvent.Name); await _tierRepository.Add(tier, CancellationToken.None); - _logger.TierCreated(tier.Id, tier.Name); + TierCreatedLogs.TierCreated(_logger, tier.Id, tier.Name); } } -file static class LoggerExtensions +internal static partial class TierCreatedLogs { - private static readonly Action TIER_CREATED = - LoggerMessage.Define( - LogLevel.Information, - new EventId(151788, "Quotas.TierCreatedIntegrationEventHandler.TierCreated"), - "Successfully created tier. Tier ID: '{tierId}', Tier Name: '{tierName}'." - ); - - public static void TierCreated(this ILogger logger, TierId tierId, string name) - { - TIER_CREATED(logger, tierId, name, default!); - } + [LoggerMessage( + EventId = 151788, + EventName = "Quotas.TierCreatedIntegrationEventHandler.TierCreated", + Level = LogLevel.Information, + Message = "Successfully created tier. Tier ID: '{tierId}', Tier Name: '{tierName}'.")] + public static partial void TierCreated(ILogger logger, TierId tierId, string tierName); } From 3cf461aa5b890983ba30b33f17462d68a95c460f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Wed, 18 Oct 2023 08:57:12 +0200 Subject: [PATCH 087/133] chore: refactoring log statements with id and name to use LoggerMessageAttribute --- .../IdentityCreatedIntegrationEventHandler.cs | 21 +++++++------------ 1 file changed, 8 insertions(+), 13 deletions(-) diff --git a/Modules/Quotas/src/Quotas.Application/IntegrationEvents/Incoming/IdentityCreated/IdentityCreatedIntegrationEventHandler.cs b/Modules/Quotas/src/Quotas.Application/IntegrationEvents/Incoming/IdentityCreated/IdentityCreatedIntegrationEventHandler.cs index 2162d7bfe9..ac886d79d2 100644 --- a/Modules/Quotas/src/Quotas.Application/IntegrationEvents/Incoming/IdentityCreated/IdentityCreatedIntegrationEventHandler.cs +++ b/Modules/Quotas/src/Quotas.Application/IntegrationEvents/Incoming/IdentityCreated/IdentityCreatedIntegrationEventHandler.cs @@ -39,21 +39,16 @@ public async Task Handle(IdentityCreatedIntegrationEvent integrationEvent) await _identitiesRepository.Add(identity, CancellationToken.None); - _logger.IdentityCreated(identity.Address, identity.TierId); + IdentityCreatedLogs.IdentityCreated(_logger, identity.Address, identity.TierId); } } -file static class LoggerExtensions +internal static partial class IdentityCreatedLogs { - private static readonly Action IDENTITY_CREATED = - LoggerMessage.Define( - LogLevel.Information, - new EventId(811934, "Quotas.IdentityCreatedIntegrationEventHandler.IdentityCreated"), - "Successfully created identity. Identity Address: '{address}', Tier ID: '{tierId}'." - ); - - public static void IdentityCreated(this ILogger logger, string address, TierId tierId) - { - IDENTITY_CREATED(logger, address, tierId, default!); - } + [LoggerMessage( + EventId = 811934, + EventName = "Quotas.IdentityCreatedIntegrationEventHandler.IdentityCreated", + Level = LogLevel.Information, + Message = "Successfully created identity. Identity Address: '{address}', Tier ID: '{tierId}'.")] + public static partial void IdentityCreated(ILogger logger, string address, TierId tierId); } From d2fcb689eac018b39c467d2778f18b7e648dc9b7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Wed, 18 Oct 2023 08:58:24 +0200 Subject: [PATCH 088/133] chore: refactoring log statements with id and name to use LoggerMessageAttribute --- .../Infrastructure/Reporter/LogReporter.cs | 42 +++++++------------ 1 file changed, 16 insertions(+), 26 deletions(-) diff --git a/Modules/Messages/src/Messages.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs b/Modules/Messages/src/Messages.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs index bf5fc2dd7b..026c789ad2 100644 --- a/Modules/Messages/src/Messages.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs +++ b/Modules/Messages/src/Messages.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs @@ -20,12 +20,12 @@ public void Complete() { foreach (var databaseId in _databaseIds) { - _logger.NoBlobForMessageId(databaseId); + MessagesLogs.NoBlobForMessageId(_logger, databaseId); } foreach (var blobId in _blobIds) { - _logger.NoDatabaseEntryForBlobId(blobId); + MessagesLogs.NoDatabaseEntryForBlobId(_logger, blobId); } } @@ -40,29 +40,19 @@ public void ReportOrphanedDatabaseId(MessageId id) } } -file static class LoggerExtensions +internal static partial class MessagesLogs { - private static readonly Action NO_BLOB_FOR_MESSAGE_ID = - LoggerMessage.Define( - LogLevel.Error, - new EventId(859729, "Messages.LogReporter.NoBlobForMessageId"), - "No blob found for file id: '{databaseId}'." - ); - - private static readonly Action NO_DATABASE_ENTRY_FOR_BLOB_ID = - LoggerMessage.Define( - LogLevel.Error, - new EventId(809167, "Messages.LogReporter.NoDatabaseEntryForBlobId"), - "No database entry found for blob id: '{blobId}'." - ); - - public static void NoBlobForMessageId(this ILogger logger, MessageId messageId) - { - NO_BLOB_FOR_MESSAGE_ID(logger, messageId, default!); - } - - public static void NoDatabaseEntryForBlobId(this ILogger logger, string blobId) - { - NO_DATABASE_ENTRY_FOR_BLOB_ID(logger, blobId, default!); - } + [LoggerMessage( + EventId = 859729, + EventName = "Messages.LogReporter.NoBlobForMessageId", + Level = LogLevel.Error, + Message = "No blob found for file id: '{databaseId}'.")] + public static partial void NoBlobForMessageId(ILogger logger, MessageId databaseId); + + [LoggerMessage( + EventId = 809167, + EventName = "Messages.LogReporter.NoDatabaseEntryForBlobId", + Level = LogLevel.Error, + Message = "No database entry found for blob id: '{blobId}'.")] + public static partial void NoDatabaseEntryForBlobId(ILogger logger, string blobId); } From a8aa453fa28ceb80f332f4b4bf0412a4cf415713 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Wed, 18 Oct 2023 08:59:24 +0200 Subject: [PATCH 089/133] chore: refactoring log statements with id and name to use LoggerMessageAttribute --- .../Infrastructure/Reporter/LogReporter.cs | 42 +++++++------------ 1 file changed, 16 insertions(+), 26 deletions(-) diff --git a/Modules/Files/src/Files.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs b/Modules/Files/src/Files.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs index 6a5133568f..05278de1d7 100644 --- a/Modules/Files/src/Files.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs +++ b/Modules/Files/src/Files.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs @@ -20,12 +20,12 @@ public void Complete() { foreach (var databaseId in _databaseIds) { - _logger.NoBlobForFileId(databaseId); + FilesLogs.NoBlobForFileId(_logger, databaseId); } foreach (var blobId in _blobIds) { - _logger.NoDatabaseEntryForBlobId(blobId); + FilesLogs.NoDatabaseEntryForBlobId(_logger, blobId); } } @@ -40,29 +40,19 @@ public void ReportOrphanedDatabaseId(FileId id) } } -file static class LoggerExtensions +internal static partial class FilesLogs { - private static readonly Action NO_BLOB_FOR_FILE_ID = - LoggerMessage.Define( - LogLevel.Error, - new EventId(629592, "Files.LogReporter.NoBlobForFileId"), - "No blob found for file id: '{databaseId}'." - ); - - private static readonly Action NO_DATABASE_ENTRY_FOR_BLOB_ID = - LoggerMessage.Define( - LogLevel.Error, - new EventId(487180, "Files.LogReporter.NoDatabaseEntryForBlobId"), - "No database entry found for blob id: '{blobId}'." - ); - - public static void NoBlobForFileId(this ILogger logger, FileId fileId) - { - NO_BLOB_FOR_FILE_ID(logger, fileId, default!); - } - - public static void NoDatabaseEntryForBlobId(this ILogger logger, string blobId) - { - NO_DATABASE_ENTRY_FOR_BLOB_ID(logger, blobId, default!); - } + [LoggerMessage( + EventId = 629592, + EventName = "Files.LogReporter.NoBlobForFileId", + Level = LogLevel.Error, + Message = "No blob found for file id: '{databaseId}'.")] + public static partial void NoBlobForFileId(ILogger logger, FileId databaseId); + + [LoggerMessage( + EventId = 487180, + EventName = "Files.LogReporter.NoDatabaseEntryForBlobId", + Level = LogLevel.Error, + Message = "No database entry found for blob id: '{blobId}'.")] + public static partial void NoDatabaseEntryForBlobId(ILogger logger, string blobId); } From 83bdfd206d22e9f1dafb0c22b095527923c290d3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Wed, 18 Oct 2023 09:01:52 +0200 Subject: [PATCH 090/133] chore: refactoring log statements with id and name to use LoggerMessageAttribute --- .../GoogleCloudStorage/GoogleCloudStorage.cs | 105 +++++++----------- 1 file changed, 40 insertions(+), 65 deletions(-) diff --git a/BuildingBlocks/src/BuildingBlocks.Infrastructure/Persistence/BlobStorage/GoogleCloudStorage/GoogleCloudStorage.cs b/BuildingBlocks/src/BuildingBlocks.Infrastructure/Persistence/BlobStorage/GoogleCloudStorage/GoogleCloudStorage.cs index 230da31793..4bcb3fe45a 100644 --- a/BuildingBlocks/src/BuildingBlocks.Infrastructure/Persistence/BlobStorage/GoogleCloudStorage/GoogleCloudStorage.cs +++ b/BuildingBlocks/src/BuildingBlocks.Infrastructure/Persistence/BlobStorage/GoogleCloudStorage/GoogleCloudStorage.cs @@ -57,7 +57,7 @@ await _logger.TraceTime(async () => catch (Exception ex) { EliminateNotFound(ex, blobId); - _logger.ErrorDownloadingBlobWithName(blobId, ex); + GoogleCloudStorageLogs.ErrorDownloadingBlobWithName(_logger, blobId, ex); throw; } } @@ -75,7 +75,7 @@ public Task> FindAllAsync(string folder, string? prefix } catch (Exception ex) { - _logger.ErrorListingAllBlobs(ex); + GoogleCloudStorageLogs.ErrorListingAllBlobs(_logger, ex); throw; } } @@ -116,7 +116,7 @@ await _storageClient.UploadObjectAsync(blob.Folder, blob.Name, null, } catch (Exception ex) { - _logger.ErrorUploadingBlobWithName(blob.Name, ex); + GoogleCloudStorageLogs.ErrorUploadingBlobWithName(_logger, blob.Name, ex); throw; } finally @@ -133,7 +133,7 @@ private async Task EnsureKeyDoesNotExist(string folder, string key) await _logger.TraceTime(async () => await _storageClient.GetObjectAsync(folder, key), nameof(_storageClient.GetObjectAsync)); - _logger.ErrorBlobWithNameExists(); + GoogleCloudStorageLogs.ErrorBlobWithNameExists(_logger); throw new BlobAlreadyExistsException(key); } catch (GoogleApiException ex) @@ -160,7 +160,7 @@ private async Task DeleteRemovedBlobs() catch (Exception ex) { EliminateNotFound(ex, blob.Name); - _logger.ErrorDeletingBlobWithName(blob.Name, ex); + GoogleCloudStorageLogs.ErrorDeletingBlobWithName(_logger, blob.Name, ex); throw; } @@ -172,65 +172,40 @@ private record ChangedBlob(string Folder, string Name, byte[] Content); private record RemovedBlob(string Folder, string Name); } -file static class LoggerExtensions +internal static partial class GoogleCloudStorageLogs { - private static readonly Action ERROR_DOWNLOADING_BLOB_WITH_NAME = - LoggerMessage.Define( - LogLevel.Error, - new EventId(997942, "GoogleCloudStorage.ErrorDownloadingBlobWithName"), - "There was an error downloading the blob with name '{blobId}'. {ex}" - ); - - private static readonly Action ERROR_LISTING_ALL_BLOBS = - LoggerMessage.Define( - LogLevel.Error, - new EventId(998879, "GoogleCloudStorage.ErrorListingAllBlobs"), - "There was an error listing all the blobs." - ); - - private static readonly Action ERROR_UPLOADING_BLOB_WITH_NAME = - LoggerMessage.Define( - LogLevel.Error, - new EventId(166344, "GoogleCloudStorage.ErrorUploadingBlobWithName"), - "There was an error uploading the blob with name '{blobName}'. {ex}" - ); - - private static readonly Action ERROR_BLOB_WITH_NAME_EXISTS = - LoggerMessage.Define( - LogLevel.Error, - new EventId(358892, "GoogleCloudStorage.ErrorBlobWithNameExists"), - "The blob with the given name already exists." - ); - - private static readonly Action ERROR_DELETING_BLOB_WITH_NAME = - LoggerMessage.Define( - LogLevel.Error, - new EventId(304533, "GoogleCloudStorage.ErrorDeletingBlobWithName"), - "There was an error downloading the blob with name '{blobName}'. {ex}" - ); - - public static void ErrorDownloadingBlobWithName(this ILogger logger, string blobId, Exception e) - { - ERROR_DOWNLOADING_BLOB_WITH_NAME(logger, blobId, e, e); - } - - public static void ErrorListingAllBlobs(this ILogger logger, Exception e) - { - ERROR_LISTING_ALL_BLOBS(logger, e); - } - - public static void ErrorUploadingBlobWithName(this ILogger logger, string blobName, Exception e) - { - ERROR_UPLOADING_BLOB_WITH_NAME(logger, blobName, e, e); - } - - public static void ErrorBlobWithNameExists(this ILogger logger) - { - ERROR_BLOB_WITH_NAME_EXISTS(logger, default!); - } - - public static void ErrorDeletingBlobWithName(this ILogger logger, string blobName, Exception e) - { - ERROR_DELETING_BLOB_WITH_NAME(logger, blobName, e, e); - } + [LoggerMessage( + EventId = 997942, + EventName = "GoogleCloudStorage.ErrorDownloadingBlobWithName", + Level = LogLevel.Error, + Message = "There was an error downloading the blob with name '{blobId}'. {ex}")] + public static partial void ErrorDownloadingBlobWithName(ILogger logger, string blobId, Exception ex); + + [LoggerMessage( + EventId = 998879, + EventName = "GoogleCloudStorage.ErrorListingAllBlobs", + Level = LogLevel.Error, + Message = "There was an error listing all the blobs.")] + public static partial void ErrorListingAllBlobs(ILogger logger, Exception ex); + + [LoggerMessage( + EventId = 166344, + EventName = "GoogleCloudStorage.ErrorUploadingBlobWithName", + Level = LogLevel.Error, + Message = "There was an error uploading the blob with name '{blobName}'. {ex}")] + public static partial void ErrorUploadingBlobWithName(ILogger logger, string blobName, Exception ex); + + [LoggerMessage( + EventId = 358892, + EventName = "GoogleCloudStorage.ErrorBlobWithNameExists", + Level = LogLevel.Error, + Message = "The blob with the given name already exists.")] + public static partial void ErrorBlobWithNameExists(ILogger logger); + + [LoggerMessage( + EventId = 304533, + EventName = "GoogleCloudStorage.ErrorDeletingBlobWithName", + Level = LogLevel.Error, + Message = "There was an error downloading the blob with name '{blobName}'. {ex}")] + public static partial void ErrorDeletingBlobWithName(ILogger logger, string blobName, Exception ex); } From 56f51a2fc2ac5f30167b5d59728ada93c1afec2f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Wed, 18 Oct 2023 09:03:04 +0200 Subject: [PATCH 091/133] chore: refactoring log statements with id and name to use LoggerMessageAttribute --- .../AzureStorageAccount.cs | 42 +++++++------------ 1 file changed, 16 insertions(+), 26 deletions(-) diff --git a/BuildingBlocks/src/BuildingBlocks.Infrastructure/Persistence/BlobStorage/AzureStorageAccount/AzureStorageAccount.cs b/BuildingBlocks/src/BuildingBlocks.Infrastructure/Persistence/BlobStorage/AzureStorageAccount/AzureStorageAccount.cs index 9b518d2d4e..5011744809 100644 --- a/BuildingBlocks/src/BuildingBlocks.Infrastructure/Persistence/BlobStorage/AzureStorageAccount/AzureStorageAccount.cs +++ b/BuildingBlocks/src/BuildingBlocks.Infrastructure/Persistence/BlobStorage/AzureStorageAccount/AzureStorageAccount.cs @@ -74,7 +74,7 @@ public Task> FindAllAsync(string folder, string? prefix } catch (Exception ex) { - _logger.ErrorListingAllBlobs(ex); + AzureStorageAccountLogs.ErrorListingAllBlobs(_logger, ex); throw; } } @@ -127,7 +127,7 @@ private async Task DeleteRemovedBlobs() } catch (Exception ex) { - _logger.ErrorDeletingBlob(cloudBlockBlob.Name, ex); + AzureStorageAccountLogs.ErrorDeletingBlob(_logger, cloudBlockBlob.Name, ex); throw new NotFoundException(); } @@ -135,29 +135,19 @@ private async Task DeleteRemovedBlobs() } } -file static class LoggerExtensions +internal static partial class AzureStorageAccountLogs { - private static readonly Action ERROR_LISTING_ALL_BLOBS = - LoggerMessage.Define( - LogLevel.Error, - new EventId(516591, "AzureStorageAccount.ErrorListingAllBlobs"), - "There was an error listing all blobs." - ); - - private static readonly Action ERROR_DELETING_BLOB = - LoggerMessage.Define( - LogLevel.Error, - new EventId(645028, "AzureStorageAccount.ErrorDeletingBlob"), - "There was an error deleting the blob with id '{cloudBlockBlobName}'. {ex}" - ); - - public static void ErrorListingAllBlobs(this ILogger logger, Exception e) - { - ERROR_LISTING_ALL_BLOBS(logger, e); - } - - public static void ErrorDeletingBlob(this ILogger logger, string cloudBlockBlobName, Exception e) - { - ERROR_DELETING_BLOB(logger, cloudBlockBlobName, e, default!); - } + [LoggerMessage( + EventId = 516591, + EventName = "AzureStorageAccount.ErrorListingAllBlobs", + Level = LogLevel.Error, + Message = "There was an error listing all blobs.")] + public static partial void ErrorListingAllBlobs(ILogger logger, Exception e); + + [LoggerMessage( + EventId = 645028, + EventName = "AzureStorageAccount.ErrorDeletingBlob", + Level = LogLevel.Error, + Message = "There was an error deleting the blob with id '{cloudBlockBlobName}'. {e}")] + public static partial void ErrorDeletingBlob(ILogger logger, string cloudBlockBlobName, Exception e); } From 2600069c6dc250549d6c6ffa6b9d1b69456ebe55 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Wed, 18 Oct 2023 09:05:06 +0200 Subject: [PATCH 092/133] chore: refactoring log statements with id and name to use LoggerMessageAttribute --- .../DefaultRabbitMQPersisterConnection.cs | 84 +++++++------------ 1 file changed, 32 insertions(+), 52 deletions(-) diff --git a/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/RabbitMQ/DefaultRabbitMQPersisterConnection.cs b/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/RabbitMQ/DefaultRabbitMQPersisterConnection.cs index dc7169a063..33877fa511 100644 --- a/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/RabbitMQ/DefaultRabbitMQPersisterConnection.cs +++ b/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/RabbitMQ/DefaultRabbitMQPersisterConnection.cs @@ -62,7 +62,7 @@ public bool TryConnect() .Or() .WaitAndRetry(_retryCount, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), - (ex, _) => _logger.BrokerUnreachableException(ex.ToString())); + (ex, _) => DefaultRabbitMqPersistentConnectionLogs.BrokerUnreachableException(_logger, ex.ToString())); policy.Execute(() => _connection = _connectionFactory .CreateConnection()); @@ -87,72 +87,52 @@ public bool TryConnect() private void OnConnectionBlocked(object? sender, ConnectionBlockedEventArgs e) { if (_disposed) return; - _logger.ConnectionIsShutdown(); + DefaultRabbitMqPersistentConnectionLogs.ConnectionIsOnShutdown(_logger); TryConnect(); } private void OnCallbackException(object? sender, CallbackExceptionEventArgs e) { if (_disposed) return; - _logger.ConnectionThrewAnException(); + DefaultRabbitMqPersistentConnectionLogs.ConnectionThrewAnException(_logger); TryConnect(); } private void OnConnectionShutdown(object? sender, ShutdownEventArgs reason) { if (_disposed) return; - _logger.ConnectionIsOnShutdown(); + DefaultRabbitMqPersistentConnectionLogs.ConnectionIsShutdown(_logger); TryConnect(); } } -file static class LoggerExtensions +internal static partial class DefaultRabbitMqPersistentConnectionLogs { - private static readonly Action BROKER_UNREACHABLE_EXCEPTION = - LoggerMessage.Define( - LogLevel.Warning, - new EventId(715507, "DefaultRabbitMqPersistentConnection.BrokerUnreachableException"), - "{exceptionString}" - ); - - private static readonly Action CONNECTION_IS_SHUTDOWN = - LoggerMessage.Define( - LogLevel.Warning, - new EventId(119836, "DefaultRabbitMqPersistentConnection.ConnectionIsShutdown"), - "A RabbitMQ connection is shutdown. Trying to re-connect..." - ); - - private static readonly Action CONNECTION_THREW_AN_EXCEPTION = - LoggerMessage.Define( - LogLevel.Warning, - new EventId(143946, "DefaultRabbitMqPersistentConnection.ConnectionThrewAnException"), - "A RabbitMQ connection threw an exception. Trying to re-connect..." - ); - - private static readonly Action CONNECTION_IS_ON_SHUTDOWN = - LoggerMessage.Define( - LogLevel.Warning, - new EventId(454129, "DefaultRabbitMqPersistentConnection.ConnectionIsOnShutdown"), - "A RabbitMQ connection is on shutdown. Trying to re-connect..." - ); - - public static void BrokerUnreachableException(this ILogger logger, string exceptionString) - { - BROKER_UNREACHABLE_EXCEPTION(logger, exceptionString, default!); - } - - public static void ConnectionIsShutdown(this ILogger logger) - { - CONNECTION_IS_SHUTDOWN(logger, default!); - } - - public static void ConnectionThrewAnException(this ILogger logger) - { - CONNECTION_THREW_AN_EXCEPTION(logger, default!); - } - - public static void ConnectionIsOnShutdown(this ILogger logger) - { - CONNECTION_IS_ON_SHUTDOWN(logger, default!); - } + [LoggerMessage( + EventId = 715507, + EventName = "DefaultRabbitMqPersistentConnection.BrokerUnreachableException", + Level = LogLevel.Warning, + Message = "{exceptionString}")] + public static partial void BrokerUnreachableException(ILogger logger, string exceptionString); + + [LoggerMessage( + EventId = 119836, + EventName = "DefaultRabbitMqPersistentConnection.ConnectionIsShutdown", + Level = LogLevel.Warning, + Message = "A RabbitMQ connection is shutdown. Trying to re-connect...")] + public static partial void ConnectionIsShutdown(ILogger logger); + + [LoggerMessage( + EventId = 143946, + EventName = "DefaultRabbitMqPersistentConnection.ConnectionThrewAnException", + Level = LogLevel.Warning, + Message = "A RabbitMQ connection threw an exception. Trying to re-connect...")] + public static partial void ConnectionThrewAnException(ILogger logger); + + [LoggerMessage( + EventId = 454129, + EventName = "DefaultRabbitMqPersistentConnection.ConnectionIsOnShutdown", + Level = LogLevel.Warning, + Message = "A RabbitMQ connection is on shutdown. Trying to re-connect...")] + public static partial void ConnectionIsOnShutdown(ILogger logger); } From 5a602ad1d63f8e57fed0379026534ffba5cb9672 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Wed, 18 Oct 2023 09:11:44 +0200 Subject: [PATCH 093/133] chore: refactoring log statements with id and name to use LoggerMessageAttribute --- .../EventBus/RabbitMQ/EventBusRabbitMQ.cs | 105 +++++++----------- 1 file changed, 40 insertions(+), 65 deletions(-) diff --git a/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/RabbitMQ/EventBusRabbitMQ.cs b/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/RabbitMQ/EventBusRabbitMQ.cs index 598ccacea2..5e1b78d08f 100644 --- a/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/RabbitMQ/EventBusRabbitMQ.cs +++ b/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/RabbitMQ/EventBusRabbitMQ.cs @@ -70,7 +70,7 @@ public void Publish(IntegrationEvent @event) .Or() .WaitAndRetry(_connectionRetryCount, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), - (ex, _) => _logger.SocketException(ex)); + (ex, _) => EventBusRabbitMQLogs.SocketException(_logger, ex.ToString())); var eventName = @event.GetType().Name; @@ -102,7 +102,7 @@ public void Publish(IntegrationEvent @event) properties, body); - _logger.PublishedIntegrationEvent(@event.IntegrationEventId); + EventBusRabbitMQLogs.PublishedIntegrationEvent(_logger, @event.IntegrationEventId); }); } @@ -171,7 +171,7 @@ private IModel CreateConsumerChannel() { channel.BasicReject(eventArgs.DeliveryTag, true); - _logger.ErrorWhileProcessingIntegrationEvent(eventName, ex); + EventBusRabbitMQLogs.ErrorWhileProcessingIntegrationEvent(_logger, eventName); } }; @@ -210,77 +210,52 @@ private async Task ProcessEvent(string eventName, string message) var concreteType = typeof(IIntegrationEventHandler<>).MakeGenericType(eventType); var policy = EventBusRetryPolicyFactory.Create( - _handlerRetryBehavior, (ex, _) => _logger.ErrorWhileExecutingEventHandlerType(eventName, ex.Message, ex.StackTrace!, ex)); + _handlerRetryBehavior, (ex, _) => EventBusRabbitMQLogs.ErrorWhileExecutingEventHandlerType(_logger, eventName, ex.Message, ex.StackTrace!)); await policy.ExecuteAsync(() => (Task)concreteType.GetMethod("Handle")!.Invoke(handler, new[] { integrationEvent })!); } } else { - _logger.NoSubscriptionForEvent(eventName); + EventBusRabbitMQLogs.NoSubscriptionForEvent(_logger, eventName); } } } -file static class LoggerExtensions +internal static partial class EventBusRabbitMQLogs { - private static readonly Action SOCKET_EXCEPTION = - LoggerMessage.Define( - LogLevel.Warning, - new EventId(411326, "EventBusRabbitMQ.SocketException"), - "{exceptionString}" - ); - - private static readonly Action PUBLISHED_INTEGERATION_EVENT = - LoggerMessage.Define( - LogLevel.Debug, - new EventId(585231, "EventBusRabbitMQ.PublishedIntegrationEvent"), - "Successfully published event with id '{integrationEventId}'." - ); - - private static readonly Action ERROR_WHILE_PROCESSING_INTEGRATION_EVENT = - LoggerMessage.Define( - LogLevel.Error, - new EventId(702822, "EventBusRabbitMQ.ErrorWhileProcessingIntegrationEvent"), - "An error occurred while processing the integration event of type '{eventName}'." - ); - - private static readonly Action NO_SUBSCRIPTION_FOR_EVENT = - LoggerMessage.Define( - LogLevel.Warning, - new EventId(980768, "EventBusRabbitMQ.NoSubscriptionForEvent"), - "No subscription for event: '{eventName}'." - ); - - private static readonly Action ERROR_WHILE_EXECUTING_EVENT_HANDLER_TYPE = - LoggerMessage.Define( - LogLevel.Warning, - new EventId(288394, "EventBusRabbitMQ.ErrorWhileExecutingEventHandlerType"), - "The following error was thrown while executing '{eventHandlerType}':\n'{errorMessage}'\n{stackTrace}.\nAttempting to retry..." - ); - - public static void SocketException(this ILogger logger, Exception e) - { - SOCKET_EXCEPTION(logger, e.Message, e); - } - - public static void PublishedIntegrationEvent(this ILogger logger, string integrationEventId) - { - PUBLISHED_INTEGERATION_EVENT(logger, integrationEventId, default!); - } - - public static void NoSubscriptionForEvent(this ILogger logger, string eventName) - { - NO_SUBSCRIPTION_FOR_EVENT(logger, eventName, default!); - } - - public static void ErrorWhileExecutingEventHandlerType(this ILogger logger, string eventHandlerType, string errorMessage, string stackTrace, Exception e) - { - ERROR_WHILE_EXECUTING_EVENT_HANDLER_TYPE(logger, eventHandlerType, errorMessage, stackTrace, e); - } - - public static void ErrorWhileProcessingIntegrationEvent(this ILogger logger, string eventName, Exception e) - { - ERROR_WHILE_PROCESSING_INTEGRATION_EVENT(logger, eventName, e); - } + [LoggerMessage( + EventId = 411326, + EventName = "EventBusRabbitMQ.SocketException", + Level = LogLevel.Warning, + Message = "{exceptionString}")] + public static partial void SocketException(ILogger logger, string exceptionString); + + [LoggerMessage( + EventId = 585231, + EventName = "EventBusRabbitMQ.PublishedIntegrationEvent", + Level = LogLevel.Debug, + Message = "Successfully published event with id '{integrationEventId}'.")] + public static partial void PublishedIntegrationEvent(ILogger logger, string integrationEventId); + + [LoggerMessage( + EventId = 702822, + EventName = "EventBusRabbitMQ.ErrorWhileProcessingIntegrationEvent", + Level = LogLevel.Error, + Message = "An error occurred while processing the integration event of type '{eventName}'.")] + public static partial void ErrorWhileProcessingIntegrationEvent(ILogger logger, string eventName); + + [LoggerMessage( + EventId = 980768, + EventName = "EventBusRabbitMQ.NoSubscriptionForEvent", + Level = LogLevel.Warning, + Message = "No subscription for event: '{eventName}'.")] + public static partial void NoSubscriptionForEvent(ILogger logger, string eventName); + + [LoggerMessage( + EventId = 288394, + EventName = "EventBusRabbitMQ.ErrorWhileExecutingEventHandlerType", + Level = LogLevel.Warning, + Message = "The following error was thrown while executing '{eventHandlerType}':\n'{errorMessage}'\n{stackTrace}.\nAttempting to retry...")] + public static partial void ErrorWhileExecutingEventHandlerType(ILogger logger, string eventHandlerType, string errorMessage, string stackTrace); } From 5e5113cfc7b2b6c979fcb0aaf425f4306cf11d8c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Wed, 18 Oct 2023 09:14:51 +0200 Subject: [PATCH 094/133] chore: refactoring log statements with id and name to use LoggerMessageAttribute --- .../EventBusGoogleCloudPubSub.cs | 83 +++++++------------ 1 file changed, 32 insertions(+), 51 deletions(-) diff --git a/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/GoogleCloudPubSub/EventBusGoogleCloudPubSub.cs b/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/GoogleCloudPubSub/EventBusGoogleCloudPubSub.cs index 5d1101b075..10ce7d0de4 100644 --- a/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/GoogleCloudPubSub/EventBusGoogleCloudPubSub.cs +++ b/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/GoogleCloudPubSub/EventBusGoogleCloudPubSub.cs @@ -65,7 +65,7 @@ public async void Publish(IntegrationEvent @event) var messageId = await _logger.TraceTime( () => _connection.PublisherClient.PublishAsync(message), nameof(_connection.PublisherClient.PublishAsync)); - _logger.EventWasNotProcessed(messageId); + EventBusGoogleCloudPubSubLogs.EventWasNotProcessed(_logger, messageId); } public void Subscribe() @@ -101,7 +101,7 @@ private static string RemoveIntegrationEventSuffix(string typeName) } catch (Exception ex) { - _logger.ErrorHandlingMessage(ex); + EventBusGoogleCloudPubSubLogs.ErrorHandlingMessage(_logger, ex.Message, ex.StackTrace!); return SubscriberClient.Reply.Nack; } @@ -113,7 +113,7 @@ private async Task ProcessEvent(string eventName, string message) { if (!_subscriptionManager.HasSubscriptionsForEvent(eventName)) { - _logger.NoSubscriptionForEvent(eventName); + EventBusGoogleCloudPubSubLogs.NoSubscriptionForEvent(_logger, eventName); return; } @@ -135,59 +135,40 @@ private async Task ProcessEvent(string eventName, string message) var handleMethod = handler.GetType().GetMethod("Handle"); var policy = EventBusRetryPolicyFactory.Create( - _handlerRetryBehavior, (ex, _) => _logger.ErrorWhileExecutingEventHandlerType(eventName, ex.Message, ex.StackTrace!, ex)); + _handlerRetryBehavior, (ex, _) => EventBusGoogleCloudPubSubLogs.ErrorWhileExecutingEventHandlerType(_logger, eventName, ex.Message, ex.StackTrace!)); await policy.ExecuteAsync(() => (Task)handleMethod!.Invoke(handler, new object[] { integrationEvent })!); } } } -file static class LoggerExtensions +internal static partial class EventBusGoogleCloudPubSubLogs { - private static readonly Action SENDING_INTEGRATION_EVENT = - LoggerMessage.Define( - LogLevel.Debug, - new EventId(830408, "EventBusGoogleCloudPubSub.SendingIntegrationEvent"), - "Successfully sent integration event with id '{messageId}'." - ); - - private static readonly Action ERROR_HANDLING_MESSAGE = - LoggerMessage.Define( - LogLevel.Error, - new EventId(712382, "EventBusGoogleCloudPubSub.ErrorHandlingMessage"), - "ERROR handling message: '{exceptionMessage}' - Context: '{@exceptionSource}'." - ); - - private static readonly Action NO_SUBSCRIPTION_FOR_EVENT = - LoggerMessage.Define( - LogLevel.Warning, - new EventId(590747, "EventBusGoogleCloudPubSub.NoSubscriptionForEvent"), - "No subscription for event: '{eventName}'." - ); - - private static readonly Action ERROR_WHILE_EXECUTING_EVENT_HANDLER_TYPE = - LoggerMessage.Define( - LogLevel.Warning, - new EventId(304842, "EventBusGoogleCloudPubSub.ErrorWhileExecutingEventHandlerType"), - "The following error was thrown while executing '{eventHandlerType}':\n'{errorMessage}'\n{stackTrace}.\nAttempting to retry..." - ); - - public static void EventWasNotProcessed(this ILogger logger, string messageId) - { - SENDING_INTEGRATION_EVENT(logger, messageId, default!); - } - - public static void ErrorHandlingMessage(this ILogger logger, Exception e) - { - ERROR_HANDLING_MESSAGE(logger, e.Message, e.Source!, e); - } - public static void NoSubscriptionForEvent(this ILogger logger, string eventName) - { - NO_SUBSCRIPTION_FOR_EVENT(logger, eventName, default!); - } - - public static void ErrorWhileExecutingEventHandlerType(this ILogger logger, string eventHandlerType, string errorMessage, string stackTrace, Exception e) - { - ERROR_WHILE_EXECUTING_EVENT_HANDLER_TYPE(logger, eventHandlerType, errorMessage, stackTrace, e); - } + [LoggerMessage( + EventId = 830408, + EventName = "EventBusGoogleCloudPubSub.SendingIntegrationEvent", + Level = LogLevel.Debug, + Message = "Successfully sent integration event with id '{messageId}'.")] + public static partial void EventWasNotProcessed(ILogger logger, string messageId); + + [LoggerMessage( + EventId = 712382, + EventName = "EventBusGoogleCloudPubSub.ErrorHandlingMessage", + Level = LogLevel.Error, + Message = "ERROR handling message: '{exceptionMessage}' - Context: '{exceptionSource}'.")] + public static partial void ErrorHandlingMessage(ILogger logger, string exceptionMessage, string exceptionSource); + + [LoggerMessage( + EventId = 590747, + EventName = "EventBusGoogleCloudPubSub.NoSubscriptionForEvent", + Level = LogLevel.Warning, + Message = "No subscription for event: '{eventName}'.")] + public static partial void NoSubscriptionForEvent(ILogger logger, string eventName); + + [LoggerMessage( + EventId = 304842, + EventName = "EventBusGoogleCloudPubSub.ErrorWhileExecutingEventHandlerType", + Level = LogLevel.Warning, + Message = "The following error was thrown while executing '{eventHandlerType}':\n'{errorMessage}'\n{stackTrace}.\nAttempting to retry...")] + public static partial void ErrorWhileExecutingEventHandlerType(ILogger logger, string eventHandlerType, string errorMessage, string stackTrace); } From 1bd7943d15069acd8ad2cbb85d8cb4a882720c77 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Wed, 18 Oct 2023 09:24:03 +0200 Subject: [PATCH 095/133] chore: refactoring log statements with id and name to use LoggerMessageAttribute --- .../MediatR/LoggingBehavior.cs | 42 +++++++++---------- 1 file changed, 19 insertions(+), 23 deletions(-) diff --git a/BuildingBlocks/src/BuildingBlocks.Application/MediatR/LoggingBehavior.cs b/BuildingBlocks/src/BuildingBlocks.Application/MediatR/LoggingBehavior.cs index dccc27c2c3..9a072c9d4b 100644 --- a/BuildingBlocks/src/BuildingBlocks.Application/MediatR/LoggingBehavior.cs +++ b/BuildingBlocks/src/BuildingBlocks.Application/MediatR/LoggingBehavior.cs @@ -36,31 +36,27 @@ private void Before() private void After() { _watch!.Stop(); - _logger.HandledMediatorRequest(typeof(TRequest).Name, _watch.ElapsedMilliseconds); + + if (_watch.ElapsedMilliseconds > 1000) + LoggingBehaviorLogs.HandledMediatorRequestWarning(_logger, typeof(TRequest).Name, _watch.ElapsedMilliseconds); + else + LoggingBehaviorLogs.HandledMediatorRequestInformation(_logger, typeof(TRequest).Name, _watch.ElapsedMilliseconds); } } -file static class LoggerExtensions +internal static partial class LoggingBehaviorLogs { - private static readonly Action HANDLED_REQUEST_WARNING = - LoggerMessage.Define( - LogLevel.Warning, - new EventId(724322, "LoggingBehavior.HandledRequestInformation"), - "Handled '{requestName}' ('{timeElapsed}' ms)." - ); - - private static readonly Action HANDLED_REQUEST_INFORMATION = - LoggerMessage.Define( - LogLevel.Information, - new EventId(724322, "LoggingBehavior.HandledRequestInformation"), - "Handled '{requestName}' ('{timeElapsed}' ms)." - ); - - public static void HandledMediatorRequest(this ILogger logger, string requestName, long timeElapsed) - { - if (timeElapsed > 1000) - HANDLED_REQUEST_WARNING(logger, requestName, timeElapsed, default!); - else - HANDLED_REQUEST_INFORMATION(logger, requestName, timeElapsed, default!); - } + [LoggerMessage( + EventId = 724322, + EventName = "LoggingBehavior.HandledRequestInformation", + Level = LogLevel.Information, + Message = "Handled '{requestName}' ('{timeElapsed}' ms).")] + public static partial void HandledMediatorRequestInformation(ILogger logger, string requestName, long timeElapsed); + + [LoggerMessage( + EventId = 724322, + EventName = "LoggingBehavior.HandledRequestInformation", + Level = LogLevel.Warning, + Message = "Handled '{requestName}' ('{timeElapsed}' ms).")] + public static partial void HandledMediatorRequestWarning(ILogger logger, string requestName, long timeElapsed); } From d520f023edfe07802800f5facd63b85006e8a2a7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Wed, 18 Oct 2023 09:41:55 +0200 Subject: [PATCH 096/133] chore: refactoring log statements with id and name to use LoggerMessageAttribute --- .../EventBusAzureServiceBus.cs | 126 +++++++----------- 1 file changed, 48 insertions(+), 78 deletions(-) diff --git a/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/AzureServiceBus/EventBusAzureServiceBus.cs b/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/AzureServiceBus/EventBusAzureServiceBus.cs index 95f9a1d958..cdcfe3a0e1 100644 --- a/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/AzureServiceBus/EventBusAzureServiceBus.cs +++ b/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/AzureServiceBus/EventBusAzureServiceBus.cs @@ -65,7 +65,7 @@ public async void Publish(IntegrationEvent @event) Subject = eventName }; - _logger.SendingIntegrationEvent(message.MessageId); + EventBusAzureServiceBusLogs.SendingIntegrationEvent(_logger, message.MessageId); await _logger.TraceTime(async () => await _sender.SendMessageAsync(message), nameof(_sender.SendMessageAsync)); @@ -121,7 +121,7 @@ private async Task RegisterSubscriptionClientMessageHandlerAsync() if (await ProcessEvent(eventName, messageData)) await args.CompleteMessageAsync(args.Message); else - _logger.EventWasNotProcessed(args.Message.MessageId); + EventBusAzureServiceBusLogs.EventWasNotProcessed(_logger, args.Message.MessageId); }; _processor.ProcessErrorAsync += ErrorHandler; @@ -133,7 +133,7 @@ private Task ErrorHandler(ProcessErrorEventArgs args) var ex = args.Exception; var context = args.ErrorSource; - _logger.ErrorHandlingMessage(ex.Message, context, ex); + EventBusAzureServiceBusLogs.ErrorHandlingMessage(_logger, ex.Message, context); return Task.CompletedTask; } @@ -142,7 +142,7 @@ private async Task ProcessEvent(string eventName, string message) { if (!_subscriptionManager.HasSubscriptionsForEvent(eventName)) { - _logger.NoSubscriptionForEvent(eventName); + EventBusAzureServiceBusLogs.NoSubscriptionForEvent(_logger, eventName); return false; } @@ -164,13 +164,13 @@ private async Task ProcessEvent(string eventName, string message) try { var policy = EventBusRetryPolicyFactory.Create( - _handlerRetryBehavior, (ex, _) => _logger.ErrorWhileExecutingEventHandlerType(eventType.Name, ex.Message, ex.StackTrace!, ex)); + _handlerRetryBehavior, (ex, _) => EventBusAzureServiceBusLogs.ErrorWhileExecutingEventHandlerType(_logger, eventType.Name, ex.Message, ex.StackTrace!)); await policy.ExecuteAsync(() => (Task)concreteType.GetMethod("Handle")!.Invoke(handler, new[] { integrationEvent })!); } catch (Exception ex) { - _logger.ErrorWhileProcessingIntegrationEvent(integrationEvent.IntegrationEventId, ex); + EventBusAzureServiceBusLogs.ErrorWhileProcessingIntegrationEvent(_logger, integrationEvent.IntegrationEventId); return false; } } @@ -179,77 +179,47 @@ private async Task ProcessEvent(string eventName, string message) } } -file static class LoggerExtensions +internal static partial class EventBusAzureServiceBusLogs { - private static readonly Action SENDING_INTEGRATION_EVENT = - LoggerMessage.Define( - LogLevel.Debug, - new EventId(302940, "EventBusAzureServiceBus.SendingIntegrationEvent"), - "Sending integration event with id '{messageId}'..." - ); - - private static readonly Action EVENT_WAS_NOT_PROCESSED = - LoggerMessage.Define( - LogLevel.Information, - new EventId(630568, "EventBusAzureServiceBus.EventWasNotProcessed"), - "The event with the MessageId '{messageId}' wasn't processed and will therefore not be completed." - ); - - private static readonly Action ERROR_HANDLING_MESSAGE = - LoggerMessage.Define( - LogLevel.Error, - new EventId(949322, "EventBusAzureServiceBus.ErrorHandlingMessage"), - "ERROR handling message: '{exceptionMessage}' - Context: '{@exceptionContext}'." - ); - - private static readonly Action NO_SUBSCRIPTION_FOR_EVENT = - LoggerMessage.Define( - LogLevel.Warning, - new EventId(341537, "EventBusAzureServiceBus.NoSubscriptionForEvent"), - "No subscription for event: '{eventName}'." - ); - - private static readonly Action ERROR_WHILE_EXECUTING_EVENT_HANDLER_TYPE = - LoggerMessage.Define( - LogLevel.Warning, - new EventId(726744, "EventBusAzureServiceBus.ErrorWhileExecutingEventHandlerCausingRetry"), - "The following error was thrown while executing '{eventHandlerType}':\n'{errorMessage}'\n{stackTrace}.\nAttempting to retry..." - ); - - private static readonly Action ERROR_WHILE_PROCESSING_INTEGRATION_EVENT = - LoggerMessage.Define( - LogLevel.Error, - new EventId(146670, "EventBusAzureServiceBus.ErrorWhileProcessingIntegrationEvent"), - "An error occurred while processing the integration event with id '{integrationEventId}'." - ); - - public static void SendingIntegrationEvent(this ILogger logger, string messageId) - { - SENDING_INTEGRATION_EVENT(logger, messageId, default!); - } - - public static void EventWasNotProcessed(this ILogger logger, string messageId) - { - EVENT_WAS_NOT_PROCESSED(logger, messageId, default!); - } - - public static void ErrorHandlingMessage(this ILogger logger, string exceptionMessage, ServiceBusErrorSource exceptionContext, Exception e) - { - ERROR_HANDLING_MESSAGE(logger, exceptionMessage, exceptionContext, e); - } - - public static void NoSubscriptionForEvent(this ILogger logger, string eventName) - { - NO_SUBSCRIPTION_FOR_EVENT(logger, eventName, default!); - } - - public static void ErrorWhileExecutingEventHandlerType(this ILogger logger, string eventHandlerType, string errorMessage, string stackTrace, Exception e) - { - ERROR_WHILE_EXECUTING_EVENT_HANDLER_TYPE(logger, eventHandlerType, errorMessage, stackTrace, e); - } - - public static void ErrorWhileProcessingIntegrationEvent(this ILogger logger, string integrationEventId, Exception e) - { - ERROR_WHILE_PROCESSING_INTEGRATION_EVENT(logger, integrationEventId, e); - } + [LoggerMessage( + EventId = 302940, + EventName = "EventBusAzureServiceBus.SendingIntegrationEvent", + Level = LogLevel.Debug, + Message = "Sending integration event with id '{messageId}'...")] + public static partial void SendingIntegrationEvent(ILogger logger, string messageId); + + [LoggerMessage( + EventId = 630568, + EventName = "EventBusAzureServiceBus.EventWasNotProcessed", + Level = LogLevel.Information, + Message = "The event with the MessageId '{messageId}' wasn't processed and will therefore not be completed.")] + public static partial void EventWasNotProcessed(ILogger logger, string messageId); + + [LoggerMessage( + EventId = 949322, + EventName = "EventBusAzureServiceBus.ErrorHandlingMessage", + Level = LogLevel.Error, + Message = "ERROR handling message: '{exceptionMessage}' - Context: '{exceptionContext}'.")] + public static partial void ErrorHandlingMessage(ILogger logger, string exceptionMessage, ServiceBusErrorSource exceptionContext); + + [LoggerMessage( + EventId = 341537, + EventName = "EventBusAzureServiceBus.NoSubscriptionForEvent", + Level = LogLevel.Warning, + Message = "No subscription for event: '{eventName}'.")] + public static partial void NoSubscriptionForEvent(ILogger logger, string eventName); + + [LoggerMessage( + EventId = 726744, + EventName = "EventBusAzureServiceBus.ErrorWhileExecutingEventHandlerCausingRetry", + Level = LogLevel.Warning, + Message = "The following error was thrown while executing '{eventHandlerType}':\n'{errorMessage}'\n{stackTrace}.\nAttempting to retry...")] + public static partial void ErrorWhileExecutingEventHandlerType(ILogger logger, string eventHandlerType, string errorMessage, string stackTrace); + + [LoggerMessage( + EventId = 146670, + EventName = "EventBusAzureServiceBus.ErrorWhileProcessingIntegrationEvent", + Level = LogLevel.Error, + Message = "An error occurred while processing the integration event with id '{integrationEventId}'.")] + public static partial void ErrorWhileProcessingIntegrationEvent(ILogger logger, string integrationEventId); } From 98a03c4d5465c5a9f19273a51b49703529d89cb7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Wed, 18 Oct 2023 09:44:00 +0200 Subject: [PATCH 097/133] chore: refactoring log statements with id and name to use LoggerMessageAttribute --- .../ExceptionFilters/CustomExceptionFilter.cs | 70 +++++++------------ 1 file changed, 26 insertions(+), 44 deletions(-) diff --git a/BuildingBlocks/src/BuildingBlocks.API/Mvc/ExceptionFilters/CustomExceptionFilter.cs b/BuildingBlocks/src/BuildingBlocks.API/Mvc/ExceptionFilters/CustomExceptionFilter.cs index cadc86ca68..2bc9bca7c8 100644 --- a/BuildingBlocks/src/BuildingBlocks.API/Mvc/ExceptionFilters/CustomExceptionFilter.cs +++ b/BuildingBlocks/src/BuildingBlocks.API/Mvc/ExceptionFilters/CustomExceptionFilter.cs @@ -42,7 +42,7 @@ public override void OnException(ExceptionContext context) switch (context.Exception) { case InfrastructureException infrastructureException: - _logger.InvalidUserInput(infrastructureException, infrastructureException.Code, infrastructureException.Message); + ExceptionFilterLogs.InvalidUserInput(_logger, infrastructureException.ToString(), infrastructureException.Code, infrastructureException.Message); httpError = CreateHttpErrorForInfrastructureException(infrastructureException); @@ -51,7 +51,7 @@ public override void OnException(ExceptionContext context) break; case ApplicationException applicationException: - _logger.InvalidUserInput(applicationException, applicationException.Code, applicationException.Message); + ExceptionFilterLogs.InvalidUserInput(_logger, applicationException.ToString(), applicationException.Code, applicationException.Message); httpError = CreateHttpErrorForApplicationException(applicationException); @@ -61,7 +61,7 @@ public override void OnException(ExceptionContext context) break; case DomainException domainException: - _logger.InvalidUserInput(domainException, domainException.Code, domainException.Message); + ExceptionFilterLogs.InvalidUserInput(_logger, domainException.ToString(), domainException.Code, domainException.Message); httpError = CreateHttpErrorForDomainException(domainException); @@ -69,7 +69,7 @@ public override void OnException(ExceptionContext context) break; case BadHttpRequestException _: - _logger.RequestBodyTooLarge(ERROR_CODE_REQUEST_BODY_TOO_LARGE); + ExceptionFilterLogs.RequestBodyTooLarge(_logger, ERROR_CODE_REQUEST_BODY_TOO_LARGE); httpError = HttpError.ForProduction( ERROR_CODE_REQUEST_BODY_TOO_LARGE, @@ -81,7 +81,7 @@ public override void OnException(ExceptionContext context) break; default: - _logger.ErrorWhileProcessingRequestToUri(context.HttpContext.Request.GetUri(), context.Exception); + ExceptionFilterLogs.ErrorWhileProcessingRequestToUri(_logger, context.HttpContext.Request.GetUri()); httpError = CreateHttpErrorForUnexpectedException(context); @@ -216,44 +216,26 @@ private IEnumerable GetFormattedStackTrace(Exception exception) } } -file static class LoggerExtensions +internal static partial class ExceptionFilterLogs { - private static readonly Action INVALID_USER_INPUT = - LoggerMessage.Define( - LogLevel.Information, - new EventId(799306, "ExceptionFilter.InvalidUserInput"), - "An '{exception}' occurred. Error Code: '{code}'. Error message: '{message}'." - ); - - private static readonly Action REQUEST_BODY_TOO_LARGE = - LoggerMessage.Define( - LogLevel.Information, - new EventId(938218, "ExceptionFilter.RequestBodyTooLarge"), - "'{error_code}': The body of the request is too large." - ); - - private static readonly Action ERROR_WHILE_PROCESSING_REQUEST_TO_URI = - LoggerMessage.Define( - LogLevel.Error, - new EventId(259125, "ExceptionFilter.ErrorWhileProcessingRequestToUri"), - "Unexpected Error while processing request to '{uri}'." - ); - - public static void InvalidUserInput( - this ILogger logger, Exception e, string errorCode, string errorMessage) - { - INVALID_USER_INPUT(logger, nameof(e.GetType), errorCode, errorMessage, default!); - } - - public static void RequestBodyTooLarge( - this ILogger logger, string errorCode) - { - REQUEST_BODY_TOO_LARGE(logger, errorCode, default!); - } - - public static void ErrorWhileProcessingRequestToUri( - this ILogger logger, Uri uri, Exception e) - { - ERROR_WHILE_PROCESSING_REQUEST_TO_URI(logger, uri, e); - } + [LoggerMessage( + EventId = 799306, + EventName = "ExceptionFilter.InvalidUserInput", + Level = LogLevel.Information, + Message = "An '{exception}' occurred. Error Code: '{code}'. Error message: '{message}'.")] + public static partial void InvalidUserInput(ILogger logger, string exception, string code, string message); + + [LoggerMessage( + EventId = 938218, + EventName = "ExceptionFilter.RequestBodyTooLarge", + Level = LogLevel.Information, + Message = "'{error_code}': The body of the request is too large.")] + public static partial void RequestBodyTooLarge(ILogger logger, string error_code); + + [LoggerMessage( + EventId = 259125, + EventName = "ExceptionFilter.ErrorWhileProcessingRequestToUri", + Level = LogLevel.Error, + Message = "Unexpected Error while processing request to '{uri}'.")] + public static partial void ErrorWhileProcessingRequestToUri(ILogger logger, Uri uri); } From ec71f33bddbd9417b5786f04bc3a912798643158 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Wed, 18 Oct 2023 16:08:24 +0200 Subject: [PATCH 098/133] chore: README updated with description on how to use the random number generator --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 0f9f6b8f24..61e3feefa9 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ Contribution to this project is highly appreciated. Head over to our [contributi ### Logging -TODO: describe how to generate event ids (min: 100,000, max: 999,999) +Log event IDs are random 6-digit numbers and can be generated using `./scripts/linux/get_random_event_id.sh` or `./scripts/windows/get_random_event_id.ps1`. Simply run the scripts to generate a random 6-digit positive integer. ## License From 849a9d454175d9a87c333578ec55684a5770cae8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Wed, 18 Oct 2023 16:20:36 +0200 Subject: [PATCH 099/133] chore: logs defined as extension methods --- .../ExceptionFilters/CustomExceptionFilter.cs | 12 +++---- .../MediatR/LoggingBehavior.cs | 8 ++--- .../EventBusAzureServiceBus.cs | 24 ++++++------- .../EventBusGoogleCloudPubSub.cs | 16 ++++----- .../DefaultRabbitMQPersisterConnection.cs | 16 ++++----- .../EventBus/RabbitMQ/EventBusRabbitMQ.cs | 20 +++++------ .../AzureStorageAccount.cs | 8 ++--- .../GoogleCloudStorage/GoogleCloudStorage.cs | 20 +++++------ .../DeleteExpiredChallenges/Handler.cs | 35 +++---------------- .../Commands/ChangePassword/Handler.cs | 4 +-- .../Devices/Commands/DeleteDevice/Handler.cs | 4 +-- .../Infrastructure/Reporter/LogReporter.cs | 8 ++--- .../Infrastructure/Reporter/LogReporter.cs | 8 ++--- .../IdentityCreatedIntegrationEventHandler.cs | 4 +-- .../TierCreatedIntegrationEventHandler.cs | 4 +-- .../TierDeletedIntegrationEventHandler.cs | 4 +-- .../CreateQuotaForIdentity/Handler.cs | 4 +-- .../Commands/CreateQuotaForTier/Handler.cs | 4 +-- .../DeleteQuotaForIdentity/Handler.cs | 4 +-- .../DeleteTierQuotaDefinition/Handler.cs | 4 +-- .../Repository/RelationshipsRepository.cs | 4 +-- .../Infrastructure/Reporter/LogReporter.cs | 8 ++--- .../Infrastructure/Reporter/LogReporter.cs | 31 ++-------------- .../Infrastructure/Reporter/LogReporter.cs | 8 ++--- .../Infrastructure/Reporter/LogReporter.cs | 8 ++--- 25 files changed, 108 insertions(+), 162 deletions(-) diff --git a/BuildingBlocks/src/BuildingBlocks.API/Mvc/ExceptionFilters/CustomExceptionFilter.cs b/BuildingBlocks/src/BuildingBlocks.API/Mvc/ExceptionFilters/CustomExceptionFilter.cs index 2bc9bca7c8..6fd528843f 100644 --- a/BuildingBlocks/src/BuildingBlocks.API/Mvc/ExceptionFilters/CustomExceptionFilter.cs +++ b/BuildingBlocks/src/BuildingBlocks.API/Mvc/ExceptionFilters/CustomExceptionFilter.cs @@ -61,7 +61,7 @@ public override void OnException(ExceptionContext context) break; case DomainException domainException: - ExceptionFilterLogs.InvalidUserInput(_logger, domainException.ToString(), domainException.Code, domainException.Message); + _logger.InvalidUserInput(domainException.ToString(), domainException.Code, domainException.Message); httpError = CreateHttpErrorForDomainException(domainException); @@ -69,7 +69,7 @@ public override void OnException(ExceptionContext context) break; case BadHttpRequestException _: - ExceptionFilterLogs.RequestBodyTooLarge(_logger, ERROR_CODE_REQUEST_BODY_TOO_LARGE); + _logger.RequestBodyTooLarge(ERROR_CODE_REQUEST_BODY_TOO_LARGE); httpError = HttpError.ForProduction( ERROR_CODE_REQUEST_BODY_TOO_LARGE, @@ -81,7 +81,7 @@ public override void OnException(ExceptionContext context) break; default: - ExceptionFilterLogs.ErrorWhileProcessingRequestToUri(_logger, context.HttpContext.Request.GetUri()); + _logger.ErrorWhileProcessingRequestToUri(context.HttpContext.Request.GetUri()); httpError = CreateHttpErrorForUnexpectedException(context); @@ -223,19 +223,19 @@ internal static partial class ExceptionFilterLogs EventName = "ExceptionFilter.InvalidUserInput", Level = LogLevel.Information, Message = "An '{exception}' occurred. Error Code: '{code}'. Error message: '{message}'.")] - public static partial void InvalidUserInput(ILogger logger, string exception, string code, string message); + public static partial void InvalidUserInput(this ILogger logger, string exception, string code, string message); [LoggerMessage( EventId = 938218, EventName = "ExceptionFilter.RequestBodyTooLarge", Level = LogLevel.Information, Message = "'{error_code}': The body of the request is too large.")] - public static partial void RequestBodyTooLarge(ILogger logger, string error_code); + public static partial void RequestBodyTooLarge(this ILogger logger, string error_code); [LoggerMessage( EventId = 259125, EventName = "ExceptionFilter.ErrorWhileProcessingRequestToUri", Level = LogLevel.Error, Message = "Unexpected Error while processing request to '{uri}'.")] - public static partial void ErrorWhileProcessingRequestToUri(ILogger logger, Uri uri); + public static partial void ErrorWhileProcessingRequestToUri(this ILogger logger, Uri uri); } diff --git a/BuildingBlocks/src/BuildingBlocks.Application/MediatR/LoggingBehavior.cs b/BuildingBlocks/src/BuildingBlocks.Application/MediatR/LoggingBehavior.cs index 9a072c9d4b..4f5953da04 100644 --- a/BuildingBlocks/src/BuildingBlocks.Application/MediatR/LoggingBehavior.cs +++ b/BuildingBlocks/src/BuildingBlocks.Application/MediatR/LoggingBehavior.cs @@ -38,9 +38,9 @@ private void After() _watch!.Stop(); if (_watch.ElapsedMilliseconds > 1000) - LoggingBehaviorLogs.HandledMediatorRequestWarning(_logger, typeof(TRequest).Name, _watch.ElapsedMilliseconds); + _logger.HandledMediatorRequestWarning(typeof(TRequest).Name, _watch.ElapsedMilliseconds); else - LoggingBehaviorLogs.HandledMediatorRequestInformation(_logger, typeof(TRequest).Name, _watch.ElapsedMilliseconds); + _logger.HandledMediatorRequestInformation(typeof(TRequest).Name, _watch.ElapsedMilliseconds); } } @@ -51,12 +51,12 @@ internal static partial class LoggingBehaviorLogs EventName = "LoggingBehavior.HandledRequestInformation", Level = LogLevel.Information, Message = "Handled '{requestName}' ('{timeElapsed}' ms).")] - public static partial void HandledMediatorRequestInformation(ILogger logger, string requestName, long timeElapsed); + public static partial void HandledMediatorRequestInformation(this ILogger logger, string requestName, long timeElapsed); [LoggerMessage( EventId = 724322, EventName = "LoggingBehavior.HandledRequestInformation", Level = LogLevel.Warning, Message = "Handled '{requestName}' ('{timeElapsed}' ms).")] - public static partial void HandledMediatorRequestWarning(ILogger logger, string requestName, long timeElapsed); + public static partial void HandledMediatorRequestWarning(this ILogger logger, string requestName, long timeElapsed); } diff --git a/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/AzureServiceBus/EventBusAzureServiceBus.cs b/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/AzureServiceBus/EventBusAzureServiceBus.cs index cdcfe3a0e1..61268d776e 100644 --- a/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/AzureServiceBus/EventBusAzureServiceBus.cs +++ b/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/AzureServiceBus/EventBusAzureServiceBus.cs @@ -65,7 +65,7 @@ public async void Publish(IntegrationEvent @event) Subject = eventName }; - EventBusAzureServiceBusLogs.SendingIntegrationEvent(_logger, message.MessageId); + _logger.SendingIntegrationEvent(message.MessageId); await _logger.TraceTime(async () => await _sender.SendMessageAsync(message), nameof(_sender.SendMessageAsync)); @@ -121,7 +121,7 @@ private async Task RegisterSubscriptionClientMessageHandlerAsync() if (await ProcessEvent(eventName, messageData)) await args.CompleteMessageAsync(args.Message); else - EventBusAzureServiceBusLogs.EventWasNotProcessed(_logger, args.Message.MessageId); + _logger.EventWasNotProcessed(args.Message.MessageId); }; _processor.ProcessErrorAsync += ErrorHandler; @@ -133,7 +133,7 @@ private Task ErrorHandler(ProcessErrorEventArgs args) var ex = args.Exception; var context = args.ErrorSource; - EventBusAzureServiceBusLogs.ErrorHandlingMessage(_logger, ex.Message, context); + _logger.ErrorHandlingMessage(ex.Message, context); return Task.CompletedTask; } @@ -142,7 +142,7 @@ private async Task ProcessEvent(string eventName, string message) { if (!_subscriptionManager.HasSubscriptionsForEvent(eventName)) { - EventBusAzureServiceBusLogs.NoSubscriptionForEvent(_logger, eventName); + _logger.NoSubscriptionForEvent(eventName); return false; } @@ -164,13 +164,13 @@ private async Task ProcessEvent(string eventName, string message) try { var policy = EventBusRetryPolicyFactory.Create( - _handlerRetryBehavior, (ex, _) => EventBusAzureServiceBusLogs.ErrorWhileExecutingEventHandlerType(_logger, eventType.Name, ex.Message, ex.StackTrace!)); + _handlerRetryBehavior, (ex, _) => _logger.ErrorWhileExecutingEventHandlerType(eventType.Name, ex.Message, ex.StackTrace!)); await policy.ExecuteAsync(() => (Task)concreteType.GetMethod("Handle")!.Invoke(handler, new[] { integrationEvent })!); } catch (Exception ex) { - EventBusAzureServiceBusLogs.ErrorWhileProcessingIntegrationEvent(_logger, integrationEvent.IntegrationEventId); + _logger.ErrorWhileProcessingIntegrationEvent(integrationEvent.IntegrationEventId); return false; } } @@ -186,40 +186,40 @@ internal static partial class EventBusAzureServiceBusLogs EventName = "EventBusAzureServiceBus.SendingIntegrationEvent", Level = LogLevel.Debug, Message = "Sending integration event with id '{messageId}'...")] - public static partial void SendingIntegrationEvent(ILogger logger, string messageId); + public static partial void SendingIntegrationEvent(this ILogger logger, string messageId); [LoggerMessage( EventId = 630568, EventName = "EventBusAzureServiceBus.EventWasNotProcessed", Level = LogLevel.Information, Message = "The event with the MessageId '{messageId}' wasn't processed and will therefore not be completed.")] - public static partial void EventWasNotProcessed(ILogger logger, string messageId); + public static partial void EventWasNotProcessed(this ILogger logger, string messageId); [LoggerMessage( EventId = 949322, EventName = "EventBusAzureServiceBus.ErrorHandlingMessage", Level = LogLevel.Error, Message = "ERROR handling message: '{exceptionMessage}' - Context: '{exceptionContext}'.")] - public static partial void ErrorHandlingMessage(ILogger logger, string exceptionMessage, ServiceBusErrorSource exceptionContext); + public static partial void ErrorHandlingMessage(this ILogger logger, string exceptionMessage, ServiceBusErrorSource exceptionContext); [LoggerMessage( EventId = 341537, EventName = "EventBusAzureServiceBus.NoSubscriptionForEvent", Level = LogLevel.Warning, Message = "No subscription for event: '{eventName}'.")] - public static partial void NoSubscriptionForEvent(ILogger logger, string eventName); + public static partial void NoSubscriptionForEvent(this ILogger logger, string eventName); [LoggerMessage( EventId = 726744, EventName = "EventBusAzureServiceBus.ErrorWhileExecutingEventHandlerCausingRetry", Level = LogLevel.Warning, Message = "The following error was thrown while executing '{eventHandlerType}':\n'{errorMessage}'\n{stackTrace}.\nAttempting to retry...")] - public static partial void ErrorWhileExecutingEventHandlerType(ILogger logger, string eventHandlerType, string errorMessage, string stackTrace); + public static partial void ErrorWhileExecutingEventHandlerType(this ILogger logger, string eventHandlerType, string errorMessage, string stackTrace); [LoggerMessage( EventId = 146670, EventName = "EventBusAzureServiceBus.ErrorWhileProcessingIntegrationEvent", Level = LogLevel.Error, Message = "An error occurred while processing the integration event with id '{integrationEventId}'.")] - public static partial void ErrorWhileProcessingIntegrationEvent(ILogger logger, string integrationEventId); + public static partial void ErrorWhileProcessingIntegrationEvent(this ILogger logger, string integrationEventId); } diff --git a/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/GoogleCloudPubSub/EventBusGoogleCloudPubSub.cs b/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/GoogleCloudPubSub/EventBusGoogleCloudPubSub.cs index 10ce7d0de4..c9085582fd 100644 --- a/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/GoogleCloudPubSub/EventBusGoogleCloudPubSub.cs +++ b/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/GoogleCloudPubSub/EventBusGoogleCloudPubSub.cs @@ -65,7 +65,7 @@ public async void Publish(IntegrationEvent @event) var messageId = await _logger.TraceTime( () => _connection.PublisherClient.PublishAsync(message), nameof(_connection.PublisherClient.PublishAsync)); - EventBusGoogleCloudPubSubLogs.EventWasNotProcessed(_logger, messageId); + _logger.EventWasNotProcessed(messageId); } public void Subscribe() @@ -101,7 +101,7 @@ private static string RemoveIntegrationEventSuffix(string typeName) } catch (Exception ex) { - EventBusGoogleCloudPubSubLogs.ErrorHandlingMessage(_logger, ex.Message, ex.StackTrace!); + _logger.ErrorHandlingMessage(ex.Message, ex.StackTrace!); return SubscriberClient.Reply.Nack; } @@ -113,7 +113,7 @@ private async Task ProcessEvent(string eventName, string message) { if (!_subscriptionManager.HasSubscriptionsForEvent(eventName)) { - EventBusGoogleCloudPubSubLogs.NoSubscriptionForEvent(_logger, eventName); + _logger.NoSubscriptionForEvent(eventName); return; } @@ -135,7 +135,7 @@ private async Task ProcessEvent(string eventName, string message) var handleMethod = handler.GetType().GetMethod("Handle"); var policy = EventBusRetryPolicyFactory.Create( - _handlerRetryBehavior, (ex, _) => EventBusGoogleCloudPubSubLogs.ErrorWhileExecutingEventHandlerType(_logger, eventName, ex.Message, ex.StackTrace!)); + _handlerRetryBehavior, (ex, _) => _logger.ErrorWhileExecutingEventHandlerType(eventName, ex.Message, ex.StackTrace!)); await policy.ExecuteAsync(() => (Task)handleMethod!.Invoke(handler, new object[] { integrationEvent })!); } @@ -149,26 +149,26 @@ internal static partial class EventBusGoogleCloudPubSubLogs EventName = "EventBusGoogleCloudPubSub.SendingIntegrationEvent", Level = LogLevel.Debug, Message = "Successfully sent integration event with id '{messageId}'.")] - public static partial void EventWasNotProcessed(ILogger logger, string messageId); + public static partial void EventWasNotProcessed(this ILogger logger, string messageId); [LoggerMessage( EventId = 712382, EventName = "EventBusGoogleCloudPubSub.ErrorHandlingMessage", Level = LogLevel.Error, Message = "ERROR handling message: '{exceptionMessage}' - Context: '{exceptionSource}'.")] - public static partial void ErrorHandlingMessage(ILogger logger, string exceptionMessage, string exceptionSource); + public static partial void ErrorHandlingMessage(this ILogger logger, string exceptionMessage, string exceptionSource); [LoggerMessage( EventId = 590747, EventName = "EventBusGoogleCloudPubSub.NoSubscriptionForEvent", Level = LogLevel.Warning, Message = "No subscription for event: '{eventName}'.")] - public static partial void NoSubscriptionForEvent(ILogger logger, string eventName); + public static partial void NoSubscriptionForEvent(this ILogger logger, string eventName); [LoggerMessage( EventId = 304842, EventName = "EventBusGoogleCloudPubSub.ErrorWhileExecutingEventHandlerType", Level = LogLevel.Warning, Message = "The following error was thrown while executing '{eventHandlerType}':\n'{errorMessage}'\n{stackTrace}.\nAttempting to retry...")] - public static partial void ErrorWhileExecutingEventHandlerType(ILogger logger, string eventHandlerType, string errorMessage, string stackTrace); + public static partial void ErrorWhileExecutingEventHandlerType(this ILogger logger, string eventHandlerType, string errorMessage, string stackTrace); } diff --git a/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/RabbitMQ/DefaultRabbitMQPersisterConnection.cs b/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/RabbitMQ/DefaultRabbitMQPersisterConnection.cs index 33877fa511..678085b426 100644 --- a/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/RabbitMQ/DefaultRabbitMQPersisterConnection.cs +++ b/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/RabbitMQ/DefaultRabbitMQPersisterConnection.cs @@ -62,7 +62,7 @@ public bool TryConnect() .Or() .WaitAndRetry(_retryCount, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), - (ex, _) => DefaultRabbitMqPersistentConnectionLogs.BrokerUnreachableException(_logger, ex.ToString())); + (ex, _) => _logger.BrokerUnreachableException(ex.ToString())); policy.Execute(() => _connection = _connectionFactory .CreateConnection()); @@ -87,21 +87,21 @@ public bool TryConnect() private void OnConnectionBlocked(object? sender, ConnectionBlockedEventArgs e) { if (_disposed) return; - DefaultRabbitMqPersistentConnectionLogs.ConnectionIsOnShutdown(_logger); + _logger.ConnectionIsOnShutdown(); TryConnect(); } private void OnCallbackException(object? sender, CallbackExceptionEventArgs e) { if (_disposed) return; - DefaultRabbitMqPersistentConnectionLogs.ConnectionThrewAnException(_logger); + _logger.ConnectionThrewAnException(); TryConnect(); } private void OnConnectionShutdown(object? sender, ShutdownEventArgs reason) { if (_disposed) return; - DefaultRabbitMqPersistentConnectionLogs.ConnectionIsShutdown(_logger); + _logger.ConnectionIsShutdown(); TryConnect(); } } @@ -113,26 +113,26 @@ internal static partial class DefaultRabbitMqPersistentConnectionLogs EventName = "DefaultRabbitMqPersistentConnection.BrokerUnreachableException", Level = LogLevel.Warning, Message = "{exceptionString}")] - public static partial void BrokerUnreachableException(ILogger logger, string exceptionString); + public static partial void BrokerUnreachableException(this ILogger logger, string exceptionString); [LoggerMessage( EventId = 119836, EventName = "DefaultRabbitMqPersistentConnection.ConnectionIsShutdown", Level = LogLevel.Warning, Message = "A RabbitMQ connection is shutdown. Trying to re-connect...")] - public static partial void ConnectionIsShutdown(ILogger logger); + public static partial void ConnectionIsShutdown(this ILogger logger); [LoggerMessage( EventId = 143946, EventName = "DefaultRabbitMqPersistentConnection.ConnectionThrewAnException", Level = LogLevel.Warning, Message = "A RabbitMQ connection threw an exception. Trying to re-connect...")] - public static partial void ConnectionThrewAnException(ILogger logger); + public static partial void ConnectionThrewAnException(this ILogger logger); [LoggerMessage( EventId = 454129, EventName = "DefaultRabbitMqPersistentConnection.ConnectionIsOnShutdown", Level = LogLevel.Warning, Message = "A RabbitMQ connection is on shutdown. Trying to re-connect...")] - public static partial void ConnectionIsOnShutdown(ILogger logger); + public static partial void ConnectionIsOnShutdown(this ILogger logger); } diff --git a/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/RabbitMQ/EventBusRabbitMQ.cs b/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/RabbitMQ/EventBusRabbitMQ.cs index 5e1b78d08f..52518e57f6 100644 --- a/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/RabbitMQ/EventBusRabbitMQ.cs +++ b/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/RabbitMQ/EventBusRabbitMQ.cs @@ -70,7 +70,7 @@ public void Publish(IntegrationEvent @event) .Or() .WaitAndRetry(_connectionRetryCount, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), - (ex, _) => EventBusRabbitMQLogs.SocketException(_logger, ex.ToString())); + (ex, _) => _logger.SocketException(ex.ToString())); var eventName = @event.GetType().Name; @@ -102,7 +102,7 @@ public void Publish(IntegrationEvent @event) properties, body); - EventBusRabbitMQLogs.PublishedIntegrationEvent(_logger, @event.IntegrationEventId); + _logger.PublishedIntegrationEvent(@event.IntegrationEventId); }); } @@ -171,7 +171,7 @@ private IModel CreateConsumerChannel() { channel.BasicReject(eventArgs.DeliveryTag, true); - EventBusRabbitMQLogs.ErrorWhileProcessingIntegrationEvent(_logger, eventName); + _logger.ErrorWhileProcessingIntegrationEvent(eventName); } }; @@ -210,14 +210,14 @@ private async Task ProcessEvent(string eventName, string message) var concreteType = typeof(IIntegrationEventHandler<>).MakeGenericType(eventType); var policy = EventBusRetryPolicyFactory.Create( - _handlerRetryBehavior, (ex, _) => EventBusRabbitMQLogs.ErrorWhileExecutingEventHandlerType(_logger, eventName, ex.Message, ex.StackTrace!)); + _handlerRetryBehavior, (ex, _) => _logger.ErrorWhileExecutingEventHandlerType(eventName, ex.Message, ex.StackTrace!)); await policy.ExecuteAsync(() => (Task)concreteType.GetMethod("Handle")!.Invoke(handler, new[] { integrationEvent })!); } } else { - EventBusRabbitMQLogs.NoSubscriptionForEvent(_logger, eventName); + _logger.NoSubscriptionForEvent(eventName); } } } @@ -229,33 +229,33 @@ internal static partial class EventBusRabbitMQLogs EventName = "EventBusRabbitMQ.SocketException", Level = LogLevel.Warning, Message = "{exceptionString}")] - public static partial void SocketException(ILogger logger, string exceptionString); + public static partial void SocketException(this ILogger logger, string exceptionString); [LoggerMessage( EventId = 585231, EventName = "EventBusRabbitMQ.PublishedIntegrationEvent", Level = LogLevel.Debug, Message = "Successfully published event with id '{integrationEventId}'.")] - public static partial void PublishedIntegrationEvent(ILogger logger, string integrationEventId); + public static partial void PublishedIntegrationEvent(this ILogger logger, string integrationEventId); [LoggerMessage( EventId = 702822, EventName = "EventBusRabbitMQ.ErrorWhileProcessingIntegrationEvent", Level = LogLevel.Error, Message = "An error occurred while processing the integration event of type '{eventName}'.")] - public static partial void ErrorWhileProcessingIntegrationEvent(ILogger logger, string eventName); + public static partial void ErrorWhileProcessingIntegrationEvent(this ILogger logger, string eventName); [LoggerMessage( EventId = 980768, EventName = "EventBusRabbitMQ.NoSubscriptionForEvent", Level = LogLevel.Warning, Message = "No subscription for event: '{eventName}'.")] - public static partial void NoSubscriptionForEvent(ILogger logger, string eventName); + public static partial void NoSubscriptionForEvent(this ILogger logger, string eventName); [LoggerMessage( EventId = 288394, EventName = "EventBusRabbitMQ.ErrorWhileExecutingEventHandlerType", Level = LogLevel.Warning, Message = "The following error was thrown while executing '{eventHandlerType}':\n'{errorMessage}'\n{stackTrace}.\nAttempting to retry...")] - public static partial void ErrorWhileExecutingEventHandlerType(ILogger logger, string eventHandlerType, string errorMessage, string stackTrace); + public static partial void ErrorWhileExecutingEventHandlerType(this ILogger logger, string eventHandlerType, string errorMessage, string stackTrace); } diff --git a/BuildingBlocks/src/BuildingBlocks.Infrastructure/Persistence/BlobStorage/AzureStorageAccount/AzureStorageAccount.cs b/BuildingBlocks/src/BuildingBlocks.Infrastructure/Persistence/BlobStorage/AzureStorageAccount/AzureStorageAccount.cs index 5011744809..48a1ab6a80 100644 --- a/BuildingBlocks/src/BuildingBlocks.Infrastructure/Persistence/BlobStorage/AzureStorageAccount/AzureStorageAccount.cs +++ b/BuildingBlocks/src/BuildingBlocks.Infrastructure/Persistence/BlobStorage/AzureStorageAccount/AzureStorageAccount.cs @@ -74,7 +74,7 @@ public Task> FindAllAsync(string folder, string? prefix } catch (Exception ex) { - AzureStorageAccountLogs.ErrorListingAllBlobs(_logger, ex); + _logger.ErrorListingAllBlobs(ex); throw; } } @@ -127,7 +127,7 @@ private async Task DeleteRemovedBlobs() } catch (Exception ex) { - AzureStorageAccountLogs.ErrorDeletingBlob(_logger, cloudBlockBlob.Name, ex); + _logger.ErrorDeletingBlob(cloudBlockBlob.Name, ex); throw new NotFoundException(); } @@ -142,12 +142,12 @@ internal static partial class AzureStorageAccountLogs EventName = "AzureStorageAccount.ErrorListingAllBlobs", Level = LogLevel.Error, Message = "There was an error listing all blobs.")] - public static partial void ErrorListingAllBlobs(ILogger logger, Exception e); + public static partial void ErrorListingAllBlobs(this ILogger logger, Exception e); [LoggerMessage( EventId = 645028, EventName = "AzureStorageAccount.ErrorDeletingBlob", Level = LogLevel.Error, Message = "There was an error deleting the blob with id '{cloudBlockBlobName}'. {e}")] - public static partial void ErrorDeletingBlob(ILogger logger, string cloudBlockBlobName, Exception e); + public static partial void ErrorDeletingBlob(this ILogger logger, string cloudBlockBlobName, Exception e); } diff --git a/BuildingBlocks/src/BuildingBlocks.Infrastructure/Persistence/BlobStorage/GoogleCloudStorage/GoogleCloudStorage.cs b/BuildingBlocks/src/BuildingBlocks.Infrastructure/Persistence/BlobStorage/GoogleCloudStorage/GoogleCloudStorage.cs index 4bcb3fe45a..a2b9733687 100644 --- a/BuildingBlocks/src/BuildingBlocks.Infrastructure/Persistence/BlobStorage/GoogleCloudStorage/GoogleCloudStorage.cs +++ b/BuildingBlocks/src/BuildingBlocks.Infrastructure/Persistence/BlobStorage/GoogleCloudStorage/GoogleCloudStorage.cs @@ -57,7 +57,7 @@ await _logger.TraceTime(async () => catch (Exception ex) { EliminateNotFound(ex, blobId); - GoogleCloudStorageLogs.ErrorDownloadingBlobWithName(_logger, blobId, ex); + _logger.ErrorDownloadingBlobWithName(blobId, ex); throw; } } @@ -75,7 +75,7 @@ public Task> FindAllAsync(string folder, string? prefix } catch (Exception ex) { - GoogleCloudStorageLogs.ErrorListingAllBlobs(_logger, ex); + _logger.ErrorListingAllBlobs(ex); throw; } } @@ -116,7 +116,7 @@ await _storageClient.UploadObjectAsync(blob.Folder, blob.Name, null, } catch (Exception ex) { - GoogleCloudStorageLogs.ErrorUploadingBlobWithName(_logger, blob.Name, ex); + _logger.ErrorUploadingBlobWithName(blob.Name, ex); throw; } finally @@ -133,7 +133,7 @@ private async Task EnsureKeyDoesNotExist(string folder, string key) await _logger.TraceTime(async () => await _storageClient.GetObjectAsync(folder, key), nameof(_storageClient.GetObjectAsync)); - GoogleCloudStorageLogs.ErrorBlobWithNameExists(_logger); + _logger.ErrorBlobWithNameExists(); throw new BlobAlreadyExistsException(key); } catch (GoogleApiException ex) @@ -160,7 +160,7 @@ private async Task DeleteRemovedBlobs() catch (Exception ex) { EliminateNotFound(ex, blob.Name); - GoogleCloudStorageLogs.ErrorDeletingBlobWithName(_logger, blob.Name, ex); + _logger.ErrorDeletingBlobWithName(blob.Name, ex); throw; } @@ -179,33 +179,33 @@ internal static partial class GoogleCloudStorageLogs EventName = "GoogleCloudStorage.ErrorDownloadingBlobWithName", Level = LogLevel.Error, Message = "There was an error downloading the blob with name '{blobId}'. {ex}")] - public static partial void ErrorDownloadingBlobWithName(ILogger logger, string blobId, Exception ex); + public static partial void ErrorDownloadingBlobWithName(this ILogger logger, string blobId, Exception ex); [LoggerMessage( EventId = 998879, EventName = "GoogleCloudStorage.ErrorListingAllBlobs", Level = LogLevel.Error, Message = "There was an error listing all the blobs.")] - public static partial void ErrorListingAllBlobs(ILogger logger, Exception ex); + public static partial void ErrorListingAllBlobs(this ILogger logger, Exception ex); [LoggerMessage( EventId = 166344, EventName = "GoogleCloudStorage.ErrorUploadingBlobWithName", Level = LogLevel.Error, Message = "There was an error uploading the blob with name '{blobName}'. {ex}")] - public static partial void ErrorUploadingBlobWithName(ILogger logger, string blobName, Exception ex); + public static partial void ErrorUploadingBlobWithName(this ILogger logger, string blobName, Exception ex); [LoggerMessage( EventId = 358892, EventName = "GoogleCloudStorage.ErrorBlobWithNameExists", Level = LogLevel.Error, Message = "The blob with the given name already exists.")] - public static partial void ErrorBlobWithNameExists(ILogger logger); + public static partial void ErrorBlobWithNameExists(this ILogger logger); [LoggerMessage( EventId = 304533, EventName = "GoogleCloudStorage.ErrorDeletingBlobWithName", Level = LogLevel.Error, Message = "There was an error downloading the blob with name '{blobName}'. {ex}")] - public static partial void ErrorDeletingBlobWithName(ILogger logger, string blobName, Exception ex); + public static partial void ErrorDeletingBlobWithName(this ILogger logger, string blobName, Exception ex); } diff --git a/Modules/Challenges/src/Challenges.Application/Challenges/Commands/DeleteExpiredChallenges/Handler.cs b/Modules/Challenges/src/Challenges.Application/Challenges/Commands/DeleteExpiredChallenges/Handler.cs index 92fd46a82b..e620c9f931 100644 --- a/Modules/Challenges/src/Challenges.Application/Challenges/Commands/DeleteExpiredChallenges/Handler.cs +++ b/Modules/Challenges/src/Challenges.Application/Challenges/Commands/DeleteExpiredChallenges/Handler.cs @@ -20,13 +20,13 @@ public async Task Handle(DeleteExpiredChallenge { if (cancellationToken.IsCancellationRequested) { - DeleteExpiredChallengesLogs.CancellationRequested(_logger); + _logger.CancellationRequested(); return DeleteExpiredChallengesResponse.NoDeletedChallenges(); } var deletedChallengesCount = await _challengesRepository.DeleteExpiredChallenges(cancellationToken); - DeleteExpiredChallengesLogs.DeletionSuccessful(_logger, deletedChallengesCount); + _logger.DeletionSuccessful(deletedChallengesCount); var response = new DeleteExpiredChallengesResponse(deletedChallengesCount); @@ -34,33 +34,6 @@ public async Task Handle(DeleteExpiredChallenge } } -file static class LoggerExtensions -{ - private static readonly Action CANCELLATION_REQUESTED = - LoggerMessage.Define( - LogLevel.Debug, - new EventId(599235, "Challenges.Application.DeleteExpiredChallenges.CancellationRequested"), - "Cancellation was requested. Stopping execution..." - ); - - private static readonly Action DELETION_SUCCESSFUL = - LoggerMessage.Define( - LogLevel.Debug, - new EventId(916630, "Challenges.Application.DeleteExpiredChallenges.DeletionSuccessful"), - "Deletion of '{deletedChallengesCount}' challenges successful." - ); - - public static void CancellationRequested(this ILogger logger) - { - CANCELLATION_REQUESTED(logger, default!); - } - - public static void DeletionSuccessful(this ILogger logger, int numberOfDeletedChallenges) - { - DELETION_SUCCESSFUL(logger, numberOfDeletedChallenges, default!); - } -} - internal static partial class DeleteExpiredChallengesLogs { [LoggerMessage( @@ -68,12 +41,12 @@ internal static partial class DeleteExpiredChallengesLogs EventName = "Challenges.Application.DeleteExpiredChallenges.CancellationRequested", Level = LogLevel.Debug, Message = "Cancellation was requested. Stopping execution...")] - public static partial void CancellationRequested(ILogger logger); + public static partial void CancellationRequested(this ILogger logger); [LoggerMessage( EventId = 916630, EventName = "Challenges.Application.DeleteExpiredChallenges.DeletionSuccessful", Level = LogLevel.Debug, Message = "Deletion of '{deletedChallengesCount}' challenges successful.")] - public static partial void DeletionSuccessful(ILogger logger, int deletedChallengesCount); + public static partial void DeletionSuccessful(this ILogger logger, int deletedChallengesCount); } diff --git a/Modules/Devices/src/Devices.Application/Devices/Commands/ChangePassword/Handler.cs b/Modules/Devices/src/Devices.Application/Devices/Commands/ChangePassword/Handler.cs index eb4b225368..b44dc6fa92 100644 --- a/Modules/Devices/src/Devices.Application/Devices/Commands/ChangePassword/Handler.cs +++ b/Modules/Devices/src/Devices.Application/Devices/Commands/ChangePassword/Handler.cs @@ -33,7 +33,7 @@ public async Task Handle(ChangePasswordCommand request, CancellationToken cancel if (!changePasswordResult.Succeeded) throw new OperationFailedException(ApplicationErrors.Devices.ChangePasswordFailed(changePasswordResult.Errors.First().Description)); - ChangePasswordLogs.ChangedPasswordForDeviceWithId(_logger, _activeDevice); + _logger.ChangedPasswordForDeviceWithId(_activeDevice); } } @@ -44,5 +44,5 @@ internal static partial class ChangePasswordLogs EventName = "Devices.ChangedPasswordForDeviceWithId", Level = LogLevel.Information, Message = "Successfully changed password for device with id '{activeDevice}'.")] - public static partial void ChangedPasswordForDeviceWithId(ILogger logger, DeviceId activeDevice); + public static partial void ChangedPasswordForDeviceWithId(this ILogger logger, DeviceId activeDevice); } diff --git a/Modules/Devices/src/Devices.Application/Devices/Commands/DeleteDevice/Handler.cs b/Modules/Devices/src/Devices.Application/Devices/Commands/DeleteDevice/Handler.cs index 219e0b5030..b0b9682041 100644 --- a/Modules/Devices/src/Devices.Application/Devices/Commands/DeleteDevice/Handler.cs +++ b/Modules/Devices/src/Devices.Application/Devices/Commands/DeleteDevice/Handler.cs @@ -40,7 +40,7 @@ public async Task Handle(DeleteDeviceCommand request, CancellationToken cancella await _identitiesRepository.Update(device, cancellationToken); - DeleteDeviceLogs.MarkDeviceWithIdAsDeleted(_logger, request.DeviceId); + _logger.MarkDeviceWithIdAsDeleted(request.DeviceId); } } @@ -51,5 +51,5 @@ internal static partial class DeleteDeviceLogs EventName = "Devices.MarkDeviceWithIdAsDeleted", Level = LogLevel.Information, Message = "Successfully marked device with id '{deviceId}' as deleted.")] - public static partial void MarkDeviceWithIdAsDeleted(ILogger logger, string deviceId); + public static partial void MarkDeviceWithIdAsDeleted(this ILogger logger, string deviceId); } diff --git a/Modules/Files/src/Files.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs b/Modules/Files/src/Files.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs index 05278de1d7..64ea42b006 100644 --- a/Modules/Files/src/Files.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs +++ b/Modules/Files/src/Files.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs @@ -20,12 +20,12 @@ public void Complete() { foreach (var databaseId in _databaseIds) { - FilesLogs.NoBlobForFileId(_logger, databaseId); + _logger.NoBlobForFileId(databaseId); } foreach (var blobId in _blobIds) { - FilesLogs.NoDatabaseEntryForBlobId(_logger, blobId); + _logger.NoDatabaseEntryForBlobId(blobId); } } @@ -47,12 +47,12 @@ internal static partial class FilesLogs EventName = "Files.LogReporter.NoBlobForFileId", Level = LogLevel.Error, Message = "No blob found for file id: '{databaseId}'.")] - public static partial void NoBlobForFileId(ILogger logger, FileId databaseId); + public static partial void NoBlobForFileId(this ILogger logger, FileId databaseId); [LoggerMessage( EventId = 487180, EventName = "Files.LogReporter.NoDatabaseEntryForBlobId", Level = LogLevel.Error, Message = "No database entry found for blob id: '{blobId}'.")] - public static partial void NoDatabaseEntryForBlobId(ILogger logger, string blobId); + public static partial void NoDatabaseEntryForBlobId(this ILogger logger, string blobId); } diff --git a/Modules/Messages/src/Messages.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs b/Modules/Messages/src/Messages.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs index 026c789ad2..870a8548d6 100644 --- a/Modules/Messages/src/Messages.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs +++ b/Modules/Messages/src/Messages.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs @@ -20,12 +20,12 @@ public void Complete() { foreach (var databaseId in _databaseIds) { - MessagesLogs.NoBlobForMessageId(_logger, databaseId); + _logger.NoBlobForMessageId(databaseId); } foreach (var blobId in _blobIds) { - MessagesLogs.NoDatabaseEntryForBlobId(_logger, blobId); + _logger.NoDatabaseEntryForBlobId(blobId); } } @@ -47,12 +47,12 @@ internal static partial class MessagesLogs EventName = "Messages.LogReporter.NoBlobForMessageId", Level = LogLevel.Error, Message = "No blob found for file id: '{databaseId}'.")] - public static partial void NoBlobForMessageId(ILogger logger, MessageId databaseId); + public static partial void NoBlobForMessageId(this ILogger logger, MessageId databaseId); [LoggerMessage( EventId = 809167, EventName = "Messages.LogReporter.NoDatabaseEntryForBlobId", Level = LogLevel.Error, Message = "No database entry found for blob id: '{blobId}'.")] - public static partial void NoDatabaseEntryForBlobId(ILogger logger, string blobId); + public static partial void NoDatabaseEntryForBlobId(this ILogger logger, string blobId); } diff --git a/Modules/Quotas/src/Quotas.Application/IntegrationEvents/Incoming/IdentityCreated/IdentityCreatedIntegrationEventHandler.cs b/Modules/Quotas/src/Quotas.Application/IntegrationEvents/Incoming/IdentityCreated/IdentityCreatedIntegrationEventHandler.cs index ac886d79d2..369fb29b3a 100644 --- a/Modules/Quotas/src/Quotas.Application/IntegrationEvents/Incoming/IdentityCreated/IdentityCreatedIntegrationEventHandler.cs +++ b/Modules/Quotas/src/Quotas.Application/IntegrationEvents/Incoming/IdentityCreated/IdentityCreatedIntegrationEventHandler.cs @@ -39,7 +39,7 @@ public async Task Handle(IdentityCreatedIntegrationEvent integrationEvent) await _identitiesRepository.Add(identity, CancellationToken.None); - IdentityCreatedLogs.IdentityCreated(_logger, identity.Address, identity.TierId); + _logger.IdentityCreated(identity.Address, identity.TierId); } } @@ -50,5 +50,5 @@ internal static partial class IdentityCreatedLogs EventName = "Quotas.IdentityCreatedIntegrationEventHandler.IdentityCreated", Level = LogLevel.Information, Message = "Successfully created identity. Identity Address: '{address}', Tier ID: '{tierId}'.")] - public static partial void IdentityCreated(ILogger logger, string address, TierId tierId); + public static partial void IdentityCreated(this ILogger logger, string address, TierId tierId); } diff --git a/Modules/Quotas/src/Quotas.Application/IntegrationEvents/Incoming/TierCreated/TierCreatedIntegrationEventHandler.cs b/Modules/Quotas/src/Quotas.Application/IntegrationEvents/Incoming/TierCreated/TierCreatedIntegrationEventHandler.cs index b37190f44e..737457e98b 100644 --- a/Modules/Quotas/src/Quotas.Application/IntegrationEvents/Incoming/TierCreated/TierCreatedIntegrationEventHandler.cs +++ b/Modules/Quotas/src/Quotas.Application/IntegrationEvents/Incoming/TierCreated/TierCreatedIntegrationEventHandler.cs @@ -20,7 +20,7 @@ public async Task Handle(TierCreatedIntegrationEvent integrationEvent) var tier = new Tier(new TierId(integrationEvent.Id), integrationEvent.Name); await _tierRepository.Add(tier, CancellationToken.None); - TierCreatedLogs.TierCreated(_logger, tier.Id, tier.Name); + _logger.TierCreated(tier.Id, tier.Name); } } @@ -31,5 +31,5 @@ internal static partial class TierCreatedLogs EventName = "Quotas.TierCreatedIntegrationEventHandler.TierCreated", Level = LogLevel.Information, Message = "Successfully created tier. Tier ID: '{tierId}', Tier Name: '{tierName}'.")] - public static partial void TierCreated(ILogger logger, TierId tierId, string tierName); + public static partial void TierCreated(this ILogger logger, TierId tierId, string tierName); } diff --git a/Modules/Quotas/src/Quotas.Application/IntegrationEvents/Incoming/TierDeleted/TierDeletedIntegrationEventHandler.cs b/Modules/Quotas/src/Quotas.Application/IntegrationEvents/Incoming/TierDeleted/TierDeletedIntegrationEventHandler.cs index 11672115a6..6a756989ff 100644 --- a/Modules/Quotas/src/Quotas.Application/IntegrationEvents/Incoming/TierDeleted/TierDeletedIntegrationEventHandler.cs +++ b/Modules/Quotas/src/Quotas.Application/IntegrationEvents/Incoming/TierDeleted/TierDeletedIntegrationEventHandler.cs @@ -21,7 +21,7 @@ public async Task Handle(TierDeletedIntegrationEvent integrationEvent) await _tiersRepository.RemoveById(tier.Id); - TierDeletedLogs.TierDeleted(_logger, tier.Id, tier.Name); + _logger.TierDeleted(tier.Id, tier.Name); } } @@ -32,5 +32,5 @@ internal static partial class TierDeletedLogs EventName = "Quotas.TierDeletedIntegrationEventHandler.TierDeleted", Level = LogLevel.Information, Message = "Successfully deleted tier. Tier ID: '{tierId}', Tier Name: '{tierName}'.")] - public static partial void TierDeleted(ILogger logger, TierId tierId, string tierName); + public static partial void TierDeleted(this ILogger logger, TierId tierId, string tierName); } diff --git a/Modules/Quotas/src/Quotas.Application/Tiers/Commands/CreateQuotaForIdentity/Handler.cs b/Modules/Quotas/src/Quotas.Application/Tiers/Commands/CreateQuotaForIdentity/Handler.cs index 3f706503eb..adfe6c8c80 100644 --- a/Modules/Quotas/src/Quotas.Application/Tiers/Commands/CreateQuotaForIdentity/Handler.cs +++ b/Modules/Quotas/src/Quotas.Application/Tiers/Commands/CreateQuotaForIdentity/Handler.cs @@ -39,7 +39,7 @@ public async Task Handle(CreateQuotaForIdentityCommand reque await _identitiesRepository.Update(identity, cancellationToken); - CreateQuotaForIdentityLogs.CreatedQuotasForIdentities(_logger, identity.Address); + _logger.CreatedQuotasForIdentities(identity.Address); var identityAddresses = new List { identity.Address }; var metrics = new List { metric.Key.Value }; @@ -57,5 +57,5 @@ internal static partial class CreateQuotaForIdentityLogs EventName = "Quotas.CreatedQuotasForIdentities", Level = LogLevel.Information, Message = "Successfully created Quota for Identity. Identity Address: '{identityAddress}'.")] - public static partial void CreatedQuotasForIdentities(ILogger logger, string identityAddress); + public static partial void CreatedQuotasForIdentities(this ILogger logger, string identityAddress); } diff --git a/Modules/Quotas/src/Quotas.Application/Tiers/Commands/CreateQuotaForTier/Handler.cs b/Modules/Quotas/src/Quotas.Application/Tiers/Commands/CreateQuotaForTier/Handler.cs index c3c1b1a986..801f2e4358 100644 --- a/Modules/Quotas/src/Quotas.Application/Tiers/Commands/CreateQuotaForTier/Handler.cs +++ b/Modules/Quotas/src/Quotas.Application/Tiers/Commands/CreateQuotaForTier/Handler.cs @@ -44,7 +44,7 @@ public async Task Handle(CreateQuotaForTierCommand reque await _tiersRepository.Update(tier, cancellationToken); - CreateQuotaForTierLogs.CreatedQuotaForTier(_logger, tier.Id, tier.Name); + _logger.CreatedQuotaForTier(tier.Id, tier.Name); _eventBus.Publish(new QuotaCreatedForTierIntegrationEvent(tier.Id, result.Value.Id)); @@ -60,5 +60,5 @@ internal static partial class CreateQuotaForTierLogs EventName = "Quotas.CreatedQuotaForTier", Level = LogLevel.Information, Message = "Successfully created Quota for Tier. Tier ID: '{tierId}', Tier Name: '{tierName}'.")] - public static partial void CreatedQuotaForTier(ILogger logger, TierId tierId, string tierName); + public static partial void CreatedQuotaForTier(this ILogger logger, TierId tierId, string tierName); } diff --git a/Modules/Quotas/src/Quotas.Application/Tiers/Commands/DeleteQuotaForIdentity/Handler.cs b/Modules/Quotas/src/Quotas.Application/Tiers/Commands/DeleteQuotaForIdentity/Handler.cs index 7fda0a884a..c525f16ed1 100644 --- a/Modules/Quotas/src/Quotas.Application/Tiers/Commands/DeleteQuotaForIdentity/Handler.cs +++ b/Modules/Quotas/src/Quotas.Application/Tiers/Commands/DeleteQuotaForIdentity/Handler.cs @@ -33,7 +33,7 @@ public async Task Handle(DeleteQuotaForIdentityCommand request, CancellationToke await _identitiesRepository.Update(identity, cancellationToken); - DeleteQuotaForIdentityLogs.DeletedQuota(_logger, request.IndividualQuotaId); + _logger.DeletedQuota(request.IndividualQuotaId); } } @@ -44,5 +44,5 @@ internal static partial class DeleteQuotaForIdentityLogs EventName = "Quotas.DeleteQuota", Level = LogLevel.Information, Message = "Successfully deleted individual quota with id: '{individualQuotaId}'.")] - public static partial void DeletedQuota(ILogger logger, string individualQuotaId); + public static partial void DeletedQuota(this ILogger logger, string individualQuotaId); } diff --git a/Modules/Quotas/src/Quotas.Application/Tiers/Commands/DeleteTierQuotaDefinition/Handler.cs b/Modules/Quotas/src/Quotas.Application/Tiers/Commands/DeleteTierQuotaDefinition/Handler.cs index 0c922bbc8b..56f1945388 100644 --- a/Modules/Quotas/src/Quotas.Application/Tiers/Commands/DeleteTierQuotaDefinition/Handler.cs +++ b/Modules/Quotas/src/Quotas.Application/Tiers/Commands/DeleteTierQuotaDefinition/Handler.cs @@ -31,7 +31,7 @@ public async Task Handle(DeleteTierQuotaDefinitionCommand request, CancellationT await _tiersRepository.Update(tier, cancellationToken); - DeleteTierQuotaDefinitionLogs.DeletedTierQuota(_logger, request.TierQuotaDefinitionId); + _logger.DeletedTierQuota(request.TierQuotaDefinitionId); _eventBus.Publish(new TierQuotaDefinitionDeletedIntegrationEvent(tier.Id, request.TierQuotaDefinitionId)); } @@ -44,5 +44,5 @@ internal static partial class DeleteTierQuotaDefinitionLogs EventName = "Quotas.DeletedTierQuota", Level = LogLevel.Information, Message = "Successfully deleted tier quota definition with id: '{tierQuotaDefinitionId}'.")] - public static partial void DeletedTierQuota(ILogger logger, string tierQuotaDefinitionId); + public static partial void DeletedTierQuota(this ILogger logger, string tierQuotaDefinitionId); } diff --git a/Modules/Relationships/src/Relationships.Infrastructure/Persistence/Database/Repository/RelationshipsRepository.cs b/Modules/Relationships/src/Relationships.Infrastructure/Persistence/Database/Repository/RelationshipsRepository.cs index 5a893b0525..9dbe42489d 100644 --- a/Modules/Relationships/src/Relationships.Infrastructure/Persistence/Database/Repository/RelationshipsRepository.cs +++ b/Modules/Relationships/src/Relationships.Infrastructure/Persistence/Database/Repository/RelationshipsRepository.cs @@ -172,7 +172,7 @@ private async Task SaveContentOfLatestChange(Relationship relationship) } catch (BlobAlreadyExistsException ex) { - RelationshipRepositoryLogs.ErrorTryingToSaveRelationshipChange(_logger, latestChange.Id, ex.BlobName); + _logger.ErrorTryingToSaveRelationshipChange(latestChange.Id, ex.BlobName); } } @@ -204,5 +204,5 @@ internal static partial class RelationshipRepositoryLogs EventName = "Relationships.RelationshipsRepository.ErrorTryingToSaveRelationshipChange", Level = LogLevel.Error, Message = "There was an error while trying to save the content of the RelationshipChange with the id '{id}'. The name of the blob was '{name}'.")] - public static partial void ErrorTryingToSaveRelationshipChange(ILogger logger, RelationshipChangeId id, string name); + public static partial void ErrorTryingToSaveRelationshipChange(this ILogger logger, RelationshipChangeId id, string name); } diff --git a/Modules/Relationships/src/Relationships.Jobs.SanityCheck.RelationshipChange/Infrastructure/Reporter/LogReporter.cs b/Modules/Relationships/src/Relationships.Jobs.SanityCheck.RelationshipChange/Infrastructure/Reporter/LogReporter.cs index 36e382ca49..aab9f3a34d 100644 --- a/Modules/Relationships/src/Relationships.Jobs.SanityCheck.RelationshipChange/Infrastructure/Reporter/LogReporter.cs +++ b/Modules/Relationships/src/Relationships.Jobs.SanityCheck.RelationshipChange/Infrastructure/Reporter/LogReporter.cs @@ -20,12 +20,12 @@ public void Complete() { foreach (var databaseId in _databaseIds) { - RelationshipChangeLogs.NoBlobForRelationshipChangeId(_logger, databaseId); + _logger.NoBlobForRelationshipChangeId(databaseId); } foreach (var blobId in _blobIds) { - RelationshipChangeLogs.NoDatabaseEntryForBlobId(_logger, blobId); + _logger.NoDatabaseEntryForBlobId(blobId); } } @@ -47,12 +47,12 @@ internal static partial class RelationshipChangeLogs EventName = "Relationships.LogReporter.NoBlobForRelationshipChangeId", Level = LogLevel.Error, Message = "No blob found for relationship change id: '{databaseId}'.")] - public static partial void NoBlobForRelationshipChangeId(ILogger logger, RelationshipChangeId databaseId); + public static partial void NoBlobForRelationshipChangeId(this ILogger logger, RelationshipChangeId databaseId); [LoggerMessage( EventId = 429922, EventName = "Relationships.LogReporter.NoDatabaseEntryForBlobId", Level = LogLevel.Error, Message = "No database entry found for blob id: '{blobId}'.")] - public static partial void NoDatabaseEntryForBlobId(ILogger logger, string blobId); + public static partial void NoDatabaseEntryForBlobId(this ILogger logger, string blobId); } diff --git a/Modules/Relationships/src/Relationships.Jobs.SanityCheck.RelationshipTemplate/Infrastructure/Reporter/LogReporter.cs b/Modules/Relationships/src/Relationships.Jobs.SanityCheck.RelationshipTemplate/Infrastructure/Reporter/LogReporter.cs index a654cba080..08282ccb09 100644 --- a/Modules/Relationships/src/Relationships.Jobs.SanityCheck.RelationshipTemplate/Infrastructure/Reporter/LogReporter.cs +++ b/Modules/Relationships/src/Relationships.Jobs.SanityCheck.RelationshipTemplate/Infrastructure/Reporter/LogReporter.cs @@ -40,33 +40,6 @@ public void ReportOrphanedDatabaseId(RelationshipTemplateId id) } } -file static class LoggerExtensions -{ - private static readonly Action NO_BLOB_FOR_RELATIONSHIP_TEMPLATE_ID = - LoggerMessage.Define( - LogLevel.Error, - new EventId(231727, "Relationships.LogReporter.NoBlobForRelationshipTemplateId"), - "No blob found for relationship template id: '{databaseId}'." - ); - - private static readonly Action NO_DATABASE_ENTRY_FOR_BLOB_ID = - LoggerMessage.Define( - LogLevel.Error, - new EventId(232800, "Relationships.LogReporter.NoDatabaseEntryForBlobId"), - "No database entry found for blob id: '{blobId}'." - ); - - public static void NoBlobForRelationshipTemplateId(this ILogger logger, RelationshipTemplateId relationshipTemplateId) - { - NO_BLOB_FOR_RELATIONSHIP_TEMPLATE_ID(logger, relationshipTemplateId, default!); - } - - public static void NoDatabaseEntryForBlobId(this ILogger logger, string blobId) - { - NO_DATABASE_ENTRY_FOR_BLOB_ID(logger, blobId, default!); - } -} - internal static partial class RelationshipTemplateLogs { [LoggerMessage( @@ -74,12 +47,12 @@ internal static partial class RelationshipTemplateLogs EventName = "Relationships.LogReporter.NoBlobForRelationshipTemplateId", Level = LogLevel.Error, Message = "No blob found for relationship template id: '{databaseId}'.")] - public static partial void NoBlobForRelationshipTemplateId(ILogger logger, RelationshipTemplateId databaseId); + public static partial void NoBlobForRelationshipTemplateId(this ILogger logger, RelationshipTemplateId databaseId); [LoggerMessage( EventId = 232800, EventName = "Relationships.LogReporter.NoDatabaseEntryForBlobId", Level = LogLevel.Error, Message = "No database entry found for blob id: '{blobId}'.")] - public static partial void NoDatabaseEntryForBlobId(ILogger logger, string blobId); + public static partial void NoDatabaseEntryForBlobId(this ILogger logger, string blobId); } diff --git a/Modules/Synchronization/src/Synchronization.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs b/Modules/Synchronization/src/Synchronization.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs index ebc952a90d..85a8fc2ddb 100644 --- a/Modules/Synchronization/src/Synchronization.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs +++ b/Modules/Synchronization/src/Synchronization.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs @@ -20,12 +20,12 @@ public void Complete() { foreach (var databaseId in _databaseIds) { - SynchronizationLogs.NoBlobForDatawalletModificationId(_logger, databaseId); + _logger.NoBlobForDatawalletModificationId(databaseId); } foreach (var blobId in _blobIds) { - SynchronizationLogs.NoDatabaseEntryForBlobId(_logger, blobId); + _logger.NoDatabaseEntryForBlobId(blobId); } } @@ -47,12 +47,12 @@ internal static partial class SynchronizationLogs EventName = "Synchronization.LogReporter.NoBlobForDatawalletModificationId", Level = LogLevel.Error, Message = "No blob found for datawallet modification id: '{databaseId}'.")] - public static partial void NoBlobForDatawalletModificationId(ILogger logger, DatawalletModificationId databaseId); + public static partial void NoBlobForDatawalletModificationId(this ILogger logger, DatawalletModificationId databaseId); [LoggerMessage( EventId = 560290, EventName = "Synchronization.LogReporter.NoDatabaseEntryForBlobId", Level = LogLevel.Error, Message = "No database entry found for blob id: '{blobId}'.")] - public static partial void NoDatabaseEntryForBlobId(ILogger logger, string blobId); + public static partial void NoDatabaseEntryForBlobId(this ILogger logger, string blobId); } diff --git a/Modules/Tokens/src/Tokens.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs b/Modules/Tokens/src/Tokens.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs index 109d35b634..0894ec3142 100644 --- a/Modules/Tokens/src/Tokens.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs +++ b/Modules/Tokens/src/Tokens.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs @@ -20,12 +20,12 @@ public void Complete() { foreach (var databaseId in _databaseIds) { - TokensLogs.NoBlobForTokenId(_logger, databaseId); + _logger.NoBlobForTokenId(databaseId); } foreach (var blobId in _blobIds) { - TokensLogs.NoDatabaseEntryForBlobId(_logger, blobId); + _logger.NoDatabaseEntryForBlobId(blobId); } } @@ -47,12 +47,12 @@ internal static partial class TokensLogs EventName = "Tokens.LogReporter.NoBlobForTokenId", Level = LogLevel.Error, Message = "No blob found for token id: '{tokenId}'.")] - public static partial void NoBlobForTokenId(ILogger logger, TokenId tokenId); + public static partial void NoBlobForTokenId(this ILogger logger, TokenId tokenId); [LoggerMessage( EventId = 271286, EventName = "Tokens.LogReporter.NoDatabaseEntryForBlobId", Level = LogLevel.Error, Message = "No database entry found for blob id: '{blobId}'.")] - public static partial void NoDatabaseEntryForBlobId(ILogger logger, string blobId); + public static partial void NoDatabaseEntryForBlobId(this ILogger logger, string blobId); } From e0f59f525effed18f76a9fa4f8dcf1f6b9a8f1a2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Wed, 18 Oct 2023 16:22:20 +0200 Subject: [PATCH 100/133] fix: after defining logs as extension methods some log statement calls were left as were --- .../Mvc/ExceptionFilters/CustomExceptionFilter.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/BuildingBlocks/src/BuildingBlocks.API/Mvc/ExceptionFilters/CustomExceptionFilter.cs b/BuildingBlocks/src/BuildingBlocks.API/Mvc/ExceptionFilters/CustomExceptionFilter.cs index 6fd528843f..3bb1c5aa2a 100644 --- a/BuildingBlocks/src/BuildingBlocks.API/Mvc/ExceptionFilters/CustomExceptionFilter.cs +++ b/BuildingBlocks/src/BuildingBlocks.API/Mvc/ExceptionFilters/CustomExceptionFilter.cs @@ -42,7 +42,7 @@ public override void OnException(ExceptionContext context) switch (context.Exception) { case InfrastructureException infrastructureException: - ExceptionFilterLogs.InvalidUserInput(_logger, infrastructureException.ToString(), infrastructureException.Code, infrastructureException.Message); + _logger.InvalidUserInput(infrastructureException.ToString(), infrastructureException.Code, infrastructureException.Message); httpError = CreateHttpErrorForInfrastructureException(infrastructureException); @@ -51,7 +51,7 @@ public override void OnException(ExceptionContext context) break; case ApplicationException applicationException: - ExceptionFilterLogs.InvalidUserInput(_logger, applicationException.ToString(), applicationException.Code, applicationException.Message); + _logger.InvalidUserInput(applicationException.ToString(), applicationException.Code, applicationException.Message); httpError = CreateHttpErrorForApplicationException(applicationException); From 4af572ccc8b18ea32246f42e142d67ad98d9dd6d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Wed, 18 Oct 2023 16:25:50 +0200 Subject: [PATCH 101/133] chore: exception.ToString() replaced by nameof(exception) in logging statements --- .../Mvc/ExceptionFilters/CustomExceptionFilter.cs | 6 +++--- .../EventBus/RabbitMQ/DefaultRabbitMQPersisterConnection.cs | 2 +- .../EventBus/RabbitMQ/EventBusRabbitMQ.cs | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/BuildingBlocks/src/BuildingBlocks.API/Mvc/ExceptionFilters/CustomExceptionFilter.cs b/BuildingBlocks/src/BuildingBlocks.API/Mvc/ExceptionFilters/CustomExceptionFilter.cs index 3bb1c5aa2a..fcb4c5bde3 100644 --- a/BuildingBlocks/src/BuildingBlocks.API/Mvc/ExceptionFilters/CustomExceptionFilter.cs +++ b/BuildingBlocks/src/BuildingBlocks.API/Mvc/ExceptionFilters/CustomExceptionFilter.cs @@ -42,7 +42,7 @@ public override void OnException(ExceptionContext context) switch (context.Exception) { case InfrastructureException infrastructureException: - _logger.InvalidUserInput(infrastructureException.ToString(), infrastructureException.Code, infrastructureException.Message); + _logger.InvalidUserInput(nameof(infrastructureException), infrastructureException.Code, infrastructureException.Message); httpError = CreateHttpErrorForInfrastructureException(infrastructureException); @@ -51,7 +51,7 @@ public override void OnException(ExceptionContext context) break; case ApplicationException applicationException: - _logger.InvalidUserInput(applicationException.ToString(), applicationException.Code, applicationException.Message); + _logger.InvalidUserInput(nameof(applicationException), applicationException.Code, applicationException.Message); httpError = CreateHttpErrorForApplicationException(applicationException); @@ -61,7 +61,7 @@ public override void OnException(ExceptionContext context) break; case DomainException domainException: - _logger.InvalidUserInput(domainException.ToString(), domainException.Code, domainException.Message); + _logger.InvalidUserInput(nameof(domainException), domainException.Code, domainException.Message); httpError = CreateHttpErrorForDomainException(domainException); diff --git a/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/RabbitMQ/DefaultRabbitMQPersisterConnection.cs b/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/RabbitMQ/DefaultRabbitMQPersisterConnection.cs index 678085b426..1a8b2dfdcc 100644 --- a/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/RabbitMQ/DefaultRabbitMQPersisterConnection.cs +++ b/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/RabbitMQ/DefaultRabbitMQPersisterConnection.cs @@ -62,7 +62,7 @@ public bool TryConnect() .Or() .WaitAndRetry(_retryCount, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), - (ex, _) => _logger.BrokerUnreachableException(ex.ToString())); + (ex, _) => _logger.BrokerUnreachableException(nameof(ex))); policy.Execute(() => _connection = _connectionFactory .CreateConnection()); diff --git a/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/RabbitMQ/EventBusRabbitMQ.cs b/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/RabbitMQ/EventBusRabbitMQ.cs index 52518e57f6..2fa62371ea 100644 --- a/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/RabbitMQ/EventBusRabbitMQ.cs +++ b/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/RabbitMQ/EventBusRabbitMQ.cs @@ -70,7 +70,7 @@ public void Publish(IntegrationEvent @event) .Or() .WaitAndRetry(_connectionRetryCount, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), - (ex, _) => _logger.SocketException(ex.ToString())); + (ex, _) => _logger.SocketException(nameof(ex))); var eventName = @event.GetType().Name; From bf7e6af258e5816b6630eb322a8dd746cb9fa027 Mon Sep 17 00:00:00 2001 From: Timo Notheisen Date: Wed, 18 Oct 2023 16:46:35 +0200 Subject: [PATCH 102/133] chore: remove comments --- Backbone.Infrastructure/Logging/LogHelper.cs | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/Backbone.Infrastructure/Logging/LogHelper.cs b/Backbone.Infrastructure/Logging/LogHelper.cs index 358baf6824..4e9b9a8db6 100644 --- a/Backbone.Infrastructure/Logging/LogHelper.cs +++ b/Backbone.Infrastructure/Logging/LogHelper.cs @@ -12,8 +12,8 @@ public static LogEventLevel GetLevel(HttpContext ctx, double _, Exception? ex) ? LogEventLevel.Error : ctx.Response.StatusCode > 499 ? LogEventLevel.Error - : IsHealthCheckEndpoint(ctx) // Not an error, check if it was a health check - ? LogEventLevel.Verbose // Was a health check, use Verbose + : IsHealthCheckEndpoint(ctx) + ? LogEventLevel.Verbose : LogEventLevel.Information; } @@ -27,8 +27,7 @@ private static bool IsHealthCheckEndpoint(HttpContext ctx) "Health checks", StringComparison.Ordinal); } - - // No endpoint, so not a health check endpoint + return false; } From a34ee4886280fd22a6a5d1c06a4077182f372016 Mon Sep 17 00:00:00 2001 From: Timo Notheisen Date: Wed, 18 Oct 2023 16:46:55 +0200 Subject: [PATCH 103/133] chore: set log levels --- ConsumerApi/appsettings.json | 1 + ConsumerApi/appsettings.override.json | 4 +--- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/ConsumerApi/appsettings.json b/ConsumerApi/appsettings.json index 3ceb1f3336..6b6aeb4424 100644 --- a/ConsumerApi/appsettings.json +++ b/ConsumerApi/appsettings.json @@ -86,6 +86,7 @@ "ConsumerApi": "Information", "Microsoft": "Information", + "Microsoft.AspNetCore": "Warning" } }, "WriteTo": { diff --git a/ConsumerApi/appsettings.override.json b/ConsumerApi/appsettings.override.json index 26d7573c08..238f797a9a 100644 --- a/ConsumerApi/appsettings.override.json +++ b/ConsumerApi/appsettings.override.json @@ -132,9 +132,7 @@ "Override": { "Backbone": "Debug", "Enmeshed": "Debug", - "ConsumerApi": "Debug", - - "Microsoft.AspNetCore": "Warning" + "ConsumerApi": "Debug" } }, "WriteTo": { From 8e054987512ebf873e5a63e85ea776852cede732 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Thu, 19 Oct 2023 14:46:03 +0200 Subject: [PATCH 104/133] chore: name passed to ErrorBlobWithNameExists method --- .../BlobStorage/GoogleCloudStorage/GoogleCloudStorage.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/BuildingBlocks/src/BuildingBlocks.Infrastructure/Persistence/BlobStorage/GoogleCloudStorage/GoogleCloudStorage.cs b/BuildingBlocks/src/BuildingBlocks.Infrastructure/Persistence/BlobStorage/GoogleCloudStorage/GoogleCloudStorage.cs index a2b9733687..e5926a9325 100644 --- a/BuildingBlocks/src/BuildingBlocks.Infrastructure/Persistence/BlobStorage/GoogleCloudStorage/GoogleCloudStorage.cs +++ b/BuildingBlocks/src/BuildingBlocks.Infrastructure/Persistence/BlobStorage/GoogleCloudStorage/GoogleCloudStorage.cs @@ -133,7 +133,7 @@ private async Task EnsureKeyDoesNotExist(string folder, string key) await _logger.TraceTime(async () => await _storageClient.GetObjectAsync(folder, key), nameof(_storageClient.GetObjectAsync)); - _logger.ErrorBlobWithNameExists(); + _logger.ErrorBlobWithNameExists(key); throw new BlobAlreadyExistsException(key); } catch (GoogleApiException ex) @@ -199,8 +199,8 @@ internal static partial class GoogleCloudStorageLogs EventId = 358892, EventName = "GoogleCloudStorage.ErrorBlobWithNameExists", Level = LogLevel.Error, - Message = "The blob with the given name already exists.")] - public static partial void ErrorBlobWithNameExists(this ILogger logger); + Message = "The blob with the name {blobName} already exists.")] + public static partial void ErrorBlobWithNameExists(this ILogger logger, string blobName); [LoggerMessage( EventId = 304533, From 67420829e7bd8f32f7a78510ad3df0a640aa737e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Thu, 19 Oct 2023 14:45:49 +0200 Subject: [PATCH 105/133] chore: extension class renamed --- BuildingBlocks/src/Tooling/Extensions/ILoggerExtensions.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/BuildingBlocks/src/Tooling/Extensions/ILoggerExtensions.cs b/BuildingBlocks/src/Tooling/Extensions/ILoggerExtensions.cs index 2e25653e98..1c165c58eb 100644 --- a/BuildingBlocks/src/Tooling/Extensions/ILoggerExtensions.cs +++ b/BuildingBlocks/src/Tooling/Extensions/ILoggerExtensions.cs @@ -44,7 +44,7 @@ public static async Task TraceTime(this ILogger logger, Func> acti } } -file static class Logs +internal static partial class ILoggerExtensionsLogs { private static readonly Action EXECUTED_ACTION = LoggerMessage.Define( From e7f1ab64a59021cb8f2ebf4e57e35f0dfe3c7f5d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Thu, 19 Oct 2023 14:44:01 +0200 Subject: [PATCH 106/133] chore: ILoggerExtensionsLogs refactored --- .../Tooling/Extensions/ILoggerExtensions.cs | 19 +++++++------------ 1 file changed, 7 insertions(+), 12 deletions(-) diff --git a/BuildingBlocks/src/Tooling/Extensions/ILoggerExtensions.cs b/BuildingBlocks/src/Tooling/Extensions/ILoggerExtensions.cs index 1c165c58eb..36e792e24a 100644 --- a/BuildingBlocks/src/Tooling/Extensions/ILoggerExtensions.cs +++ b/BuildingBlocks/src/Tooling/Extensions/ILoggerExtensions.cs @@ -44,17 +44,12 @@ public static async Task TraceTime(this ILogger logger, Func> acti } } -internal static partial class ILoggerExtensionsLogs +internal static partial class SaveChangesTimeInterceptorLogs { - private static readonly Action EXECUTED_ACTION = - LoggerMessage.Define( - LogLevel.Debug, - LogEventIds.EXECUTION_TIME, - "Executed '{action}' in {elapsedMilliseconds}ms." - ); - - public static void ExecutedAction(this ILogger logger, string actionName, long elapsedMilliseconds) - { - EXECUTED_ACTION(logger, actionName, elapsedMilliseconds, default!); - } + [LoggerMessage( + EventId = 293800, + EventName = "ExecutionTime", + Level = LogLevel.Information, + Message = "Executed '{actionName}' in {elapsedMilliseconds}ms.")] + public static partial void ExecutedAction(this ILogger logger, string actionName, long elapsedMilliseconds); } From bff1e55cd888642d4962581d93b43e6332e50b08 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Thu, 19 Oct 2023 14:42:10 +0200 Subject: [PATCH 107/133] chore: refactored the SaveChangesTimeInterceptor logs --- .../Database/SaveChangesTimeInterceptor.cs | 19 +++++++------------ .../src/Tooling/Extensions/LogEventIds.cs | 7 ------- 2 files changed, 7 insertions(+), 19 deletions(-) delete mode 100644 BuildingBlocks/src/Tooling/Extensions/LogEventIds.cs diff --git a/BuildingBlocks/src/BuildingBlocks.Infrastructure/Persistence/Database/SaveChangesTimeInterceptor.cs b/BuildingBlocks/src/BuildingBlocks.Infrastructure/Persistence/Database/SaveChangesTimeInterceptor.cs index 7e860b8d1b..b4ca75fe4f 100644 --- a/BuildingBlocks/src/BuildingBlocks.Infrastructure/Persistence/Database/SaveChangesTimeInterceptor.cs +++ b/BuildingBlocks/src/BuildingBlocks.Infrastructure/Persistence/Database/SaveChangesTimeInterceptor.cs @@ -35,17 +35,12 @@ public override async ValueTask SavedChangesAsync( } } -file static class Logs +internal static partial class SaveChangesTimeInterceptorLogs { - private static readonly Action EXECUTED_ACTION = - LoggerMessage.Define( - LogLevel.Debug, - LogEventIds.EXECUTION_TIME, - "Executed '{action}' in {elapsedMilliseconds}ms." - ); - - public static void ExecutedAction(this ILogger logger, string actionName, long elapsedMilliseconds) - { - EXECUTED_ACTION(logger, actionName, elapsedMilliseconds, default!); - } + [LoggerMessage( + EventId = 293800, + EventName = "ExecutionTime", + Level = LogLevel.Information, + Message = "Executed '{actionName}' in {elapsedMilliseconds}ms.")] + public static partial void ExecutedAction(this ILogger logger, string actionName, long elapsedMilliseconds); } diff --git a/BuildingBlocks/src/Tooling/Extensions/LogEventIds.cs b/BuildingBlocks/src/Tooling/Extensions/LogEventIds.cs deleted file mode 100644 index ccdc6cb3a4..0000000000 --- a/BuildingBlocks/src/Tooling/Extensions/LogEventIds.cs +++ /dev/null @@ -1,7 +0,0 @@ -using Microsoft.Extensions.Logging; - -namespace Enmeshed.Tooling.Extensions; -public static class LogEventIds -{ - public static readonly EventId EXECUTION_TIME = new(293800, "ExecutionTime"); -} From 3f7b34c7c37767b198d9fe83f3306f656a2cca2e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Thu, 19 Oct 2023 14:33:24 +0200 Subject: [PATCH 108/133] chore: messages refactored and method parameters renamed --- .../BlobStorage/GoogleCloudStorage/GoogleCloudStorage.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/BuildingBlocks/src/BuildingBlocks.Infrastructure/Persistence/BlobStorage/GoogleCloudStorage/GoogleCloudStorage.cs b/BuildingBlocks/src/BuildingBlocks.Infrastructure/Persistence/BlobStorage/GoogleCloudStorage/GoogleCloudStorage.cs index e5926a9325..1d48394a10 100644 --- a/BuildingBlocks/src/BuildingBlocks.Infrastructure/Persistence/BlobStorage/GoogleCloudStorage/GoogleCloudStorage.cs +++ b/BuildingBlocks/src/BuildingBlocks.Infrastructure/Persistence/BlobStorage/GoogleCloudStorage/GoogleCloudStorage.cs @@ -178,8 +178,8 @@ internal static partial class GoogleCloudStorageLogs EventId = 997942, EventName = "GoogleCloudStorage.ErrorDownloadingBlobWithName", Level = LogLevel.Error, - Message = "There was an error downloading the blob with name '{blobId}'. {ex}")] - public static partial void ErrorDownloadingBlobWithName(this ILogger logger, string blobId, Exception ex); + Message = "There was an error downloading the blob with name '{blobName}'.")] + public static partial void ErrorDownloadingBlobWithName(this ILogger logger, string blobName, Exception ex); [LoggerMessage( EventId = 998879, @@ -192,7 +192,7 @@ internal static partial class GoogleCloudStorageLogs EventId = 166344, EventName = "GoogleCloudStorage.ErrorUploadingBlobWithName", Level = LogLevel.Error, - Message = "There was an error uploading the blob with name '{blobName}'. {ex}")] + Message = "There was an error uploading the blob with name '{blobName}'.")] public static partial void ErrorUploadingBlobWithName(this ILogger logger, string blobName, Exception ex); [LoggerMessage( @@ -206,6 +206,6 @@ internal static partial class GoogleCloudStorageLogs EventId = 304533, EventName = "GoogleCloudStorage.ErrorDeletingBlobWithName", Level = LogLevel.Error, - Message = "There was an error downloading the blob with name '{blobName}'. {ex}")] + Message = "There was an error downloading the blob with name '{blobName}'.")] public static partial void ErrorDeletingBlobWithName(this ILogger logger, string blobName, Exception ex); } From 37a189334b8d5958a62edc83bf4f3229121fe346 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Thu, 19 Oct 2023 14:31:12 +0200 Subject: [PATCH 109/133] chore: method parameter renamed --- .../BlobStorage/AzureStorageAccount/AzureStorageAccount.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/BuildingBlocks/src/BuildingBlocks.Infrastructure/Persistence/BlobStorage/AzureStorageAccount/AzureStorageAccount.cs b/BuildingBlocks/src/BuildingBlocks.Infrastructure/Persistence/BlobStorage/AzureStorageAccount/AzureStorageAccount.cs index 48a1ab6a80..ea20c29ab7 100644 --- a/BuildingBlocks/src/BuildingBlocks.Infrastructure/Persistence/BlobStorage/AzureStorageAccount/AzureStorageAccount.cs +++ b/BuildingBlocks/src/BuildingBlocks.Infrastructure/Persistence/BlobStorage/AzureStorageAccount/AzureStorageAccount.cs @@ -148,6 +148,6 @@ internal static partial class AzureStorageAccountLogs EventId = 645028, EventName = "AzureStorageAccount.ErrorDeletingBlob", Level = LogLevel.Error, - Message = "There was an error deleting the blob with id '{cloudBlockBlobName}'. {e}")] - public static partial void ErrorDeletingBlob(this ILogger logger, string cloudBlockBlobName, Exception e); + Message = "There was an error deleting the blob with id '{cloudBlockBlobName}'.")] + public static partial void ErrorDeletingBlob(this ILogger logger, string cloudBlockBlobName, Exception ex); } From 43f993f6b0077d333c6e33d765da8d04e1fadb4b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Thu, 19 Oct 2023 14:30:40 +0200 Subject: [PATCH 110/133] chore: method parameter renamed --- .../BlobStorage/AzureStorageAccount/AzureStorageAccount.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/BuildingBlocks/src/BuildingBlocks.Infrastructure/Persistence/BlobStorage/AzureStorageAccount/AzureStorageAccount.cs b/BuildingBlocks/src/BuildingBlocks.Infrastructure/Persistence/BlobStorage/AzureStorageAccount/AzureStorageAccount.cs index ea20c29ab7..3fd569b918 100644 --- a/BuildingBlocks/src/BuildingBlocks.Infrastructure/Persistence/BlobStorage/AzureStorageAccount/AzureStorageAccount.cs +++ b/BuildingBlocks/src/BuildingBlocks.Infrastructure/Persistence/BlobStorage/AzureStorageAccount/AzureStorageAccount.cs @@ -142,7 +142,7 @@ internal static partial class AzureStorageAccountLogs EventName = "AzureStorageAccount.ErrorListingAllBlobs", Level = LogLevel.Error, Message = "There was an error listing all blobs.")] - public static partial void ErrorListingAllBlobs(this ILogger logger, Exception e); + public static partial void ErrorListingAllBlobs(this ILogger logger, Exception ex); [LoggerMessage( EventId = 645028, From 2466a09f31b73104d8b07ae00d23f295e2b7372a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Thu, 19 Oct 2023 14:29:35 +0200 Subject: [PATCH 111/133] chore: method renamed and refactored --- .../EventBus/RabbitMQ/EventBusRabbitMQ.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/RabbitMQ/EventBusRabbitMQ.cs b/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/RabbitMQ/EventBusRabbitMQ.cs index 2fa62371ea..cb0afee2c0 100644 --- a/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/RabbitMQ/EventBusRabbitMQ.cs +++ b/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/RabbitMQ/EventBusRabbitMQ.cs @@ -210,7 +210,7 @@ private async Task ProcessEvent(string eventName, string message) var concreteType = typeof(IIntegrationEventHandler<>).MakeGenericType(eventType); var policy = EventBusRetryPolicyFactory.Create( - _handlerRetryBehavior, (ex, _) => _logger.ErrorWhileExecutingEventHandlerType(eventName, ex.Message, ex.StackTrace!)); + _handlerRetryBehavior, (ex, _) => _logger.ErrorWhileExecutingEventHandlerType(eventName, ex)); await policy.ExecuteAsync(() => (Task)concreteType.GetMethod("Handle")!.Invoke(handler, new[] { integrationEvent })!); } @@ -256,6 +256,6 @@ internal static partial class EventBusRabbitMQLogs EventId = 288394, EventName = "EventBusRabbitMQ.ErrorWhileExecutingEventHandlerType", Level = LogLevel.Warning, - Message = "The following error was thrown while executing '{eventHandlerType}':\n'{errorMessage}'\n{stackTrace}.\nAttempting to retry...")] - public static partial void ErrorWhileExecutingEventHandlerType(this ILogger logger, string eventHandlerType, string errorMessage, string stackTrace); + Message = "An error was thrown while executing '{eventHandlerType}'. Attempting to retry...")] + public static partial void ErrorWhileExecutingEventHandlerType(this ILogger logger, string eventHandlerType, Exception exception); } From d9002a16648aba02e530d4f68ddc24432d358484 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Thu, 19 Oct 2023 14:27:36 +0200 Subject: [PATCH 112/133] chore: method refactored to resemble the one in EventBusAzureServiceBus --- .../GoogleCloudPubSub/EventBusGoogleCloudPubSub.cs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/GoogleCloudPubSub/EventBusGoogleCloudPubSub.cs b/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/GoogleCloudPubSub/EventBusGoogleCloudPubSub.cs index c9085582fd..b4e0e80cd2 100644 --- a/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/GoogleCloudPubSub/EventBusGoogleCloudPubSub.cs +++ b/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/GoogleCloudPubSub/EventBusGoogleCloudPubSub.cs @@ -2,6 +2,7 @@ using Autofac; using Enmeshed.BuildingBlocks.Application.Abstractions.Infrastructure.EventBus; using Enmeshed.BuildingBlocks.Application.Abstractions.Infrastructure.EventBus.Events; +using Enmeshed.BuildingBlocks.Infrastructure.EventBus.AzureServiceBus; using Enmeshed.BuildingBlocks.Infrastructure.EventBus.Json; using Google.Cloud.PubSub.V1; using Google.Protobuf; @@ -101,7 +102,7 @@ private static string RemoveIntegrationEventSuffix(string typeName) } catch (Exception ex) { - _logger.ErrorHandlingMessage(ex.Message, ex.StackTrace!); + _logger.ErrorHandlingMessage(ex.StackTrace!, ex); return SubscriberClient.Reply.Nack; } @@ -155,8 +156,8 @@ internal static partial class EventBusGoogleCloudPubSubLogs EventId = 712382, EventName = "EventBusGoogleCloudPubSub.ErrorHandlingMessage", Level = LogLevel.Error, - Message = "ERROR handling message: '{exceptionMessage}' - Context: '{exceptionSource}'.")] - public static partial void ErrorHandlingMessage(this ILogger logger, string exceptionMessage, string exceptionSource); + Message = "Error handling message with context {exceptionSource}.")] + public static partial void ErrorHandlingMessage(this ILogger logger, string exceptionSource, Exception exception); [LoggerMessage( EventId = 590747, From 65b7ba7c1fe8076deab32e7863894caf772604ee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Thu, 19 Oct 2023 14:26:24 +0200 Subject: [PATCH 113/133] chore: method renamed and refactored --- .../EventBus/RabbitMQ/EventBusRabbitMQ.cs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/RabbitMQ/EventBusRabbitMQ.cs b/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/RabbitMQ/EventBusRabbitMQ.cs index cb0afee2c0..dca5f0eec4 100644 --- a/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/RabbitMQ/EventBusRabbitMQ.cs +++ b/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/RabbitMQ/EventBusRabbitMQ.cs @@ -70,7 +70,7 @@ public void Publish(IntegrationEvent @event) .Or() .WaitAndRetry(_connectionRetryCount, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), - (ex, _) => _logger.SocketException(nameof(ex))); + (ex, _) => _logger.ErrorOnPublish(ex)); var eventName = @event.GetType().Name; @@ -171,7 +171,7 @@ private IModel CreateConsumerChannel() { channel.BasicReject(eventArgs.DeliveryTag, true); - _logger.ErrorWhileProcessingIntegrationEvent(eventName); + _logger.ErrorWhileProcessingIntegrationEvent(eventName, ex); } }; @@ -226,10 +226,10 @@ internal static partial class EventBusRabbitMQLogs { [LoggerMessage( EventId = 411326, - EventName = "EventBusRabbitMQ.SocketException", + EventName = "EventBusRabbitMQ.ErrorOnPublish", Level = LogLevel.Warning, - Message = "{exceptionString}")] - public static partial void SocketException(this ILogger logger, string exceptionString); + Message = "There was an error while trying to publish an event.")] + public static partial void ErrorOnPublish(this ILogger logger, Exception exception); [LoggerMessage( EventId = 585231, @@ -243,7 +243,7 @@ internal static partial class EventBusRabbitMQLogs EventName = "EventBusRabbitMQ.ErrorWhileProcessingIntegrationEvent", Level = LogLevel.Error, Message = "An error occurred while processing the integration event of type '{eventName}'.")] - public static partial void ErrorWhileProcessingIntegrationEvent(this ILogger logger, string eventName); + public static partial void ErrorWhileProcessingIntegrationEvent(this ILogger logger, string eventName, Exception exception); [LoggerMessage( EventId = 980768, From e556dd24781a0c2c10473648a06f0febac78739c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Thu, 19 Oct 2023 14:16:00 +0200 Subject: [PATCH 114/133] chore: method renamed and refactored --- .../RabbitMQ/DefaultRabbitMQPersisterConnection.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/RabbitMQ/DefaultRabbitMQPersisterConnection.cs b/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/RabbitMQ/DefaultRabbitMQPersisterConnection.cs index 1a8b2dfdcc..090abfd44f 100644 --- a/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/RabbitMQ/DefaultRabbitMQPersisterConnection.cs +++ b/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/RabbitMQ/DefaultRabbitMQPersisterConnection.cs @@ -87,7 +87,7 @@ public bool TryConnect() private void OnConnectionBlocked(object? sender, ConnectionBlockedEventArgs e) { if (_disposed) return; - _logger.ConnectionIsOnShutdown(); + _logger.ConnectionIsBlocked(); TryConnect(); } @@ -131,8 +131,8 @@ internal static partial class DefaultRabbitMqPersistentConnectionLogs [LoggerMessage( EventId = 454129, - EventName = "DefaultRabbitMqPersistentConnection.ConnectionIsOnShutdown", + EventName = "DefaultRabbitMqPersistentConnection.ConnectionIsBlocked", Level = LogLevel.Warning, - Message = "A RabbitMQ connection is on shutdown. Trying to re-connect...")] - public static partial void ConnectionIsOnShutdown(this ILogger logger); + Message = "A RabbitMQ connection is blocked. Trying to re-connect...")] + public static partial void ConnectionIsBlocked(this ILogger logger); } From 27788ef2f2a9729ad6db6766fb2db26d514ff33b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Thu, 19 Oct 2023 14:14:35 +0200 Subject: [PATCH 115/133] chore: method renamed and refactored --- .../RabbitMQ/DefaultRabbitMQPersisterConnection.cs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/RabbitMQ/DefaultRabbitMQPersisterConnection.cs b/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/RabbitMQ/DefaultRabbitMQPersisterConnection.cs index 090abfd44f..05f56ecfea 100644 --- a/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/RabbitMQ/DefaultRabbitMQPersisterConnection.cs +++ b/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/RabbitMQ/DefaultRabbitMQPersisterConnection.cs @@ -48,7 +48,7 @@ public void Dispose() } catch (IOException ex) { - _logger.LogCritical(ex, ex.Message); + _logger.LogCritical(ex, "There was an error while disposing the connection."); } } @@ -62,7 +62,7 @@ public bool TryConnect() .Or() .WaitAndRetry(_retryCount, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), - (ex, _) => _logger.BrokerUnreachableException(nameof(ex))); + (ex, _) => _logger.ConnectionError(ex)); policy.Execute(() => _connection = _connectionFactory .CreateConnection()); @@ -110,10 +110,10 @@ internal static partial class DefaultRabbitMqPersistentConnectionLogs { [LoggerMessage( EventId = 715507, - EventName = "DefaultRabbitMqPersistentConnection.BrokerUnreachableException", + EventName = "DefaultRabbitMqPersistentConnection.ConnectionError", Level = LogLevel.Warning, - Message = "{exceptionString}")] - public static partial void BrokerUnreachableException(this ILogger logger, string exceptionString); + Message = "There was an error while trying to connect to RabbitMQ. Attemping to retry...")] + public static partial void ConnectionError(this ILogger logger, Exception exception); [LoggerMessage( EventId = 119836, From 43f3b706102fb85f0f6d91251d3bd4e951bb5a5f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Fri, 20 Oct 2023 00:45:37 +0200 Subject: [PATCH 116/133] chore: substituted variables for classes as arguments of nameof() calls --- .../Mvc/ExceptionFilters/CustomExceptionFilter.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/BuildingBlocks/src/BuildingBlocks.API/Mvc/ExceptionFilters/CustomExceptionFilter.cs b/BuildingBlocks/src/BuildingBlocks.API/Mvc/ExceptionFilters/CustomExceptionFilter.cs index fcb4c5bde3..c4677e0456 100644 --- a/BuildingBlocks/src/BuildingBlocks.API/Mvc/ExceptionFilters/CustomExceptionFilter.cs +++ b/BuildingBlocks/src/BuildingBlocks.API/Mvc/ExceptionFilters/CustomExceptionFilter.cs @@ -42,7 +42,7 @@ public override void OnException(ExceptionContext context) switch (context.Exception) { case InfrastructureException infrastructureException: - _logger.InvalidUserInput(nameof(infrastructureException), infrastructureException.Code, infrastructureException.Message); + _logger.InvalidUserInput(nameof(InfrastructureException), infrastructureException.Code, infrastructureException.Message); httpError = CreateHttpErrorForInfrastructureException(infrastructureException); @@ -51,7 +51,7 @@ public override void OnException(ExceptionContext context) break; case ApplicationException applicationException: - _logger.InvalidUserInput(nameof(applicationException), applicationException.Code, applicationException.Message); + _logger.InvalidUserInput(nameof(ApplicationException), applicationException.Code, applicationException.Message); httpError = CreateHttpErrorForApplicationException(applicationException); @@ -61,7 +61,7 @@ public override void OnException(ExceptionContext context) break; case DomainException domainException: - _logger.InvalidUserInput(nameof(domainException), domainException.Code, domainException.Message); + _logger.InvalidUserInput(nameof(DomainException), domainException.Code, domainException.Message); httpError = CreateHttpErrorForDomainException(domainException); From ed17e19c6c6121f3a93d06df821c6a254b440109 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Fri, 20 Oct 2023 00:51:12 +0200 Subject: [PATCH 117/133] chore: log level set dynamically instead of duplicating the methods --- .../MediatR/LoggingBehavior.cs | 16 ++++------------ 1 file changed, 4 insertions(+), 12 deletions(-) diff --git a/BuildingBlocks/src/BuildingBlocks.Application/MediatR/LoggingBehavior.cs b/BuildingBlocks/src/BuildingBlocks.Application/MediatR/LoggingBehavior.cs index 4f5953da04..9c6d7757d0 100644 --- a/BuildingBlocks/src/BuildingBlocks.Application/MediatR/LoggingBehavior.cs +++ b/BuildingBlocks/src/BuildingBlocks.Application/MediatR/LoggingBehavior.cs @@ -37,10 +37,9 @@ private void After() { _watch!.Stop(); - if (_watch.ElapsedMilliseconds > 1000) - _logger.HandledMediatorRequestWarning(typeof(TRequest).Name, _watch.ElapsedMilliseconds); - else - _logger.HandledMediatorRequestInformation(typeof(TRequest).Name, _watch.ElapsedMilliseconds); + _logger.HandledMediatorRequest( + _watch.ElapsedMilliseconds > 1000 ? LogLevel.Warning : LogLevel.Information, + typeof(TRequest).Name, _watch.ElapsedMilliseconds); } } @@ -49,14 +48,7 @@ internal static partial class LoggingBehaviorLogs [LoggerMessage( EventId = 724322, EventName = "LoggingBehavior.HandledRequestInformation", - Level = LogLevel.Information, Message = "Handled '{requestName}' ('{timeElapsed}' ms).")] - public static partial void HandledMediatorRequestInformation(this ILogger logger, string requestName, long timeElapsed); + public static partial void HandledMediatorRequest(this ILogger logger, LogLevel level, string requestName, long timeElapsed); - [LoggerMessage( - EventId = 724322, - EventName = "LoggingBehavior.HandledRequestInformation", - Level = LogLevel.Warning, - Message = "Handled '{requestName}' ('{timeElapsed}' ms).")] - public static partial void HandledMediatorRequestWarning(this ILogger logger, string requestName, long timeElapsed); } From a628e19370829afeef3d543514d2caa6cb9714ac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Fri, 20 Oct 2023 01:01:01 +0200 Subject: [PATCH 118/133] chore: simplifying the logger messages --- .../AzureServiceBus/EventBusAzureServiceBus.cs | 14 +++++++------- .../GoogleCloudPubSub/EventBusGoogleCloudPubSub.cs | 7 ++++--- 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/AzureServiceBus/EventBusAzureServiceBus.cs b/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/AzureServiceBus/EventBusAzureServiceBus.cs index 61268d776e..1ad036d8db 100644 --- a/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/AzureServiceBus/EventBusAzureServiceBus.cs +++ b/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/AzureServiceBus/EventBusAzureServiceBus.cs @@ -133,7 +133,7 @@ private Task ErrorHandler(ProcessErrorEventArgs args) var ex = args.Exception; var context = args.ErrorSource; - _logger.ErrorHandlingMessage(ex.Message, context); + _logger.ErrorHandlingMessage(context, ex); return Task.CompletedTask; } @@ -164,7 +164,7 @@ private async Task ProcessEvent(string eventName, string message) try { var policy = EventBusRetryPolicyFactory.Create( - _handlerRetryBehavior, (ex, _) => _logger.ErrorWhileExecutingEventHandlerType(eventType.Name, ex.Message, ex.StackTrace!)); + _handlerRetryBehavior, (ex, _) => _logger.ErrorWhileExecutingEventHandlerType(eventType.Name, ex)); await policy.ExecuteAsync(() => (Task)concreteType.GetMethod("Handle")!.Invoke(handler, new[] { integrationEvent })!); } @@ -199,8 +199,8 @@ internal static partial class EventBusAzureServiceBusLogs EventId = 949322, EventName = "EventBusAzureServiceBus.ErrorHandlingMessage", Level = LogLevel.Error, - Message = "ERROR handling message: '{exceptionMessage}' - Context: '{exceptionContext}'.")] - public static partial void ErrorHandlingMessage(this ILogger logger, string exceptionMessage, ServiceBusErrorSource exceptionContext); + Message = "Error handling message with context {exceptionContext}.")] + public static partial void ErrorHandlingMessage(this ILogger logger, ServiceBusErrorSource exceptionContext, Exception exception); [LoggerMessage( EventId = 341537, @@ -213,9 +213,9 @@ internal static partial class EventBusAzureServiceBusLogs EventId = 726744, EventName = "EventBusAzureServiceBus.ErrorWhileExecutingEventHandlerCausingRetry", Level = LogLevel.Warning, - Message = "The following error was thrown while executing '{eventHandlerType}':\n'{errorMessage}'\n{stackTrace}.\nAttempting to retry...")] - public static partial void ErrorWhileExecutingEventHandlerType(this ILogger logger, string eventHandlerType, string errorMessage, string stackTrace); - + Message = "An error was thrown while executing '{eventHandlerType}'. Attempting to retry...")] + public static partial void ErrorWhileExecutingEventHandlerType(this ILogger logger, string eventHandlerType, Exception exception); + [LoggerMessage( EventId = 146670, EventName = "EventBusAzureServiceBus.ErrorWhileProcessingIntegrationEvent", diff --git a/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/GoogleCloudPubSub/EventBusGoogleCloudPubSub.cs b/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/GoogleCloudPubSub/EventBusGoogleCloudPubSub.cs index b4e0e80cd2..0716a17d15 100644 --- a/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/GoogleCloudPubSub/EventBusGoogleCloudPubSub.cs +++ b/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/GoogleCloudPubSub/EventBusGoogleCloudPubSub.cs @@ -1,5 +1,6 @@ using System.Text.RegularExpressions; using Autofac; +using Azure.Messaging.ServiceBus; using Enmeshed.BuildingBlocks.Application.Abstractions.Infrastructure.EventBus; using Enmeshed.BuildingBlocks.Application.Abstractions.Infrastructure.EventBus.Events; using Enmeshed.BuildingBlocks.Infrastructure.EventBus.AzureServiceBus; @@ -136,7 +137,7 @@ private async Task ProcessEvent(string eventName, string message) var handleMethod = handler.GetType().GetMethod("Handle"); var policy = EventBusRetryPolicyFactory.Create( - _handlerRetryBehavior, (ex, _) => _logger.ErrorWhileExecutingEventHandlerType(eventName, ex.Message, ex.StackTrace!)); + _handlerRetryBehavior, (ex, _) => _logger.ErrorWhileExecutingEventHandlerType(eventName, ex)); await policy.ExecuteAsync(() => (Task)handleMethod!.Invoke(handler, new object[] { integrationEvent })!); } @@ -170,6 +171,6 @@ internal static partial class EventBusGoogleCloudPubSubLogs EventId = 304842, EventName = "EventBusGoogleCloudPubSub.ErrorWhileExecutingEventHandlerType", Level = LogLevel.Warning, - Message = "The following error was thrown while executing '{eventHandlerType}':\n'{errorMessage}'\n{stackTrace}.\nAttempting to retry...")] - public static partial void ErrorWhileExecutingEventHandlerType(this ILogger logger, string eventHandlerType, string errorMessage, string stackTrace); + Message = "An error was thrown while executing '{eventHandlerType}'. Attempting to retry...")] + public static partial void ErrorWhileExecutingEventHandlerType(this ILogger logger, string eventHandlerType, Exception exception); } From b41e2d0fd0ea5121ccb0f6069cacc96da1f87e58 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Fri, 20 Oct 2023 01:02:59 +0200 Subject: [PATCH 119/133] chore: fixed a typo --- .../EventBus/RabbitMQ/DefaultRabbitMQPersisterConnection.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/RabbitMQ/DefaultRabbitMQPersisterConnection.cs b/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/RabbitMQ/DefaultRabbitMQPersisterConnection.cs index 05f56ecfea..55ec857d4c 100644 --- a/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/RabbitMQ/DefaultRabbitMQPersisterConnection.cs +++ b/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/RabbitMQ/DefaultRabbitMQPersisterConnection.cs @@ -112,7 +112,7 @@ internal static partial class DefaultRabbitMqPersistentConnectionLogs EventId = 715507, EventName = "DefaultRabbitMqPersistentConnection.ConnectionError", Level = LogLevel.Warning, - Message = "There was an error while trying to connect to RabbitMQ. Attemping to retry...")] + Message = "There was an error while trying to connect to RabbitMQ. Attempting to retry...")] public static partial void ConnectionError(this ILogger logger, Exception exception); [LoggerMessage( From d4f199acb609e0ed5cd64a38f3dc05e6282f7476 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Fri, 20 Oct 2023 01:13:21 +0200 Subject: [PATCH 120/133] fix: formatting issue that caused ci/cd test to fail --- .../BuildingBlocks.Infrastructure.csproj | 54 +++++++++---------- 1 file changed, 27 insertions(+), 27 deletions(-) diff --git a/BuildingBlocks/src/BuildingBlocks.Infrastructure/BuildingBlocks.Infrastructure.csproj b/BuildingBlocks/src/BuildingBlocks.Infrastructure/BuildingBlocks.Infrastructure.csproj index 7f56f319f1..3cc0081ccb 100644 --- a/BuildingBlocks/src/BuildingBlocks.Infrastructure/BuildingBlocks.Infrastructure.csproj +++ b/BuildingBlocks/src/BuildingBlocks.Infrastructure/BuildingBlocks.Infrastructure.csproj @@ -1,33 +1,33 @@ - - net7.0 - enable - enable - Enmeshed.$(MSBuildProjectName.Replace(" ", "_")) - + + net7.0 + enable + enable + Enmeshed.$(MSBuildProjectName.Replace(" ", "_")) + - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + - - - + + + From c135b48e3f2ef93ca5850c9171ae9a176eb27751 Mon Sep 17 00:00:00 2001 From: Timo Notheisen Date: Fri, 20 Oct 2023 09:00:26 +0200 Subject: [PATCH 121/133] chore: fix log event ids --- .../BuildingBlocks.Application/MediatR/LoggingBehavior.cs | 2 +- .../Commands/DeleteExpiredChallenges/Handler.cs | 6 +++--- .../Clients/Commands/DeleteClient/Handler.cs | 2 +- .../Devices/Commands/ChangePassword/Handler.cs | 6 +++--- .../Devices/Commands/DeleteDevice/Handler.cs | 6 +++--- .../Infrastructure/Reporter/LogReporter.cs | 4 ++-- .../Infrastructure/Reporter/LogReporter.cs | 4 ++-- .../Tiers/Commands/CreateQuotaForIdentity/Handler.cs | 8 ++++---- .../Tiers/Commands/CreateQuotaForTier/Handler.cs | 8 ++++---- .../Tiers/Commands/DeleteQuotaForIdentity/Handler.cs | 8 ++++---- .../Tiers/Commands/DeleteTierQuotaDefinition/Handler.cs | 8 ++++---- 11 files changed, 31 insertions(+), 31 deletions(-) diff --git a/BuildingBlocks/src/BuildingBlocks.Application/MediatR/LoggingBehavior.cs b/BuildingBlocks/src/BuildingBlocks.Application/MediatR/LoggingBehavior.cs index 9c6d7757d0..7abeec3cfd 100644 --- a/BuildingBlocks/src/BuildingBlocks.Application/MediatR/LoggingBehavior.cs +++ b/BuildingBlocks/src/BuildingBlocks.Application/MediatR/LoggingBehavior.cs @@ -47,7 +47,7 @@ internal static partial class LoggingBehaviorLogs { [LoggerMessage( EventId = 724322, - EventName = "LoggingBehavior.HandledRequestInformation", + EventName = "LoggingBehavior.HandledRequest", Message = "Handled '{requestName}' ('{timeElapsed}' ms).")] public static partial void HandledMediatorRequest(this ILogger logger, LogLevel level, string requestName, long timeElapsed); diff --git a/Modules/Challenges/src/Challenges.Application/Challenges/Commands/DeleteExpiredChallenges/Handler.cs b/Modules/Challenges/src/Challenges.Application/Challenges/Commands/DeleteExpiredChallenges/Handler.cs index e620c9f931..8b0f0a5abd 100644 --- a/Modules/Challenges/src/Challenges.Application/Challenges/Commands/DeleteExpiredChallenges/Handler.cs +++ b/Modules/Challenges/src/Challenges.Application/Challenges/Commands/DeleteExpiredChallenges/Handler.cs @@ -38,15 +38,15 @@ internal static partial class DeleteExpiredChallengesLogs { [LoggerMessage( EventId = 599235, - EventName = "Challenges.Application.DeleteExpiredChallenges.CancellationRequested", + EventName = "Challenges.DeleteExpiredChallenges.CancellationRequested", Level = LogLevel.Debug, Message = "Cancellation was requested. Stopping execution...")] public static partial void CancellationRequested(this ILogger logger); [LoggerMessage( EventId = 916630, - EventName = "Challenges.Application.DeleteExpiredChallenges.DeletionSuccessful", - Level = LogLevel.Debug, + EventName = "Challenges.DeleteExpiredChallenges.DeletionSuccessful", + Level = LogLevel.Information, Message = "Deletion of '{deletedChallengesCount}' challenges successful.")] public static partial void DeletionSuccessful(this ILogger logger, int deletedChallengesCount); } diff --git a/Modules/Devices/src/Devices.Application/Clients/Commands/DeleteClient/Handler.cs b/Modules/Devices/src/Devices.Application/Clients/Commands/DeleteClient/Handler.cs index 33355a2e37..8171bccf03 100644 --- a/Modules/Devices/src/Devices.Application/Clients/Commands/DeleteClient/Handler.cs +++ b/Modules/Devices/src/Devices.Application/Clients/Commands/DeleteClient/Handler.cs @@ -30,7 +30,7 @@ file static class LoggerExtensions private static readonly Action DELETED_CLIENT_WITH_ID = LoggerMessage.Define( LogLevel.Information, - new EventId(418943, "Devices.DeletedClientWithId"), + new EventId(418943, "Devices.DeleteClient.DeletedClientWithId"), "Successfully deleted client with id '{clientId}'." ); diff --git a/Modules/Devices/src/Devices.Application/Devices/Commands/ChangePassword/Handler.cs b/Modules/Devices/src/Devices.Application/Devices/Commands/ChangePassword/Handler.cs index b44dc6fa92..3c3f5cb9f5 100644 --- a/Modules/Devices/src/Devices.Application/Devices/Commands/ChangePassword/Handler.cs +++ b/Modules/Devices/src/Devices.Application/Devices/Commands/ChangePassword/Handler.cs @@ -33,7 +33,7 @@ public async Task Handle(ChangePasswordCommand request, CancellationToken cancel if (!changePasswordResult.Succeeded) throw new OperationFailedException(ApplicationErrors.Devices.ChangePasswordFailed(changePasswordResult.Errors.First().Description)); - _logger.ChangedPasswordForDeviceWithId(_activeDevice); + _logger.ChangedPasswordForDevice(_activeDevice); } } @@ -41,8 +41,8 @@ internal static partial class ChangePasswordLogs { [LoggerMessage( EventId = 277894, - EventName = "Devices.ChangedPasswordForDeviceWithId", + EventName = "Devices.ChangePassword.ChangedPasswordForDevice", Level = LogLevel.Information, Message = "Successfully changed password for device with id '{activeDevice}'.")] - public static partial void ChangedPasswordForDeviceWithId(this ILogger logger, DeviceId activeDevice); + public static partial void ChangedPasswordForDevice(this ILogger logger, DeviceId activeDevice); } diff --git a/Modules/Devices/src/Devices.Application/Devices/Commands/DeleteDevice/Handler.cs b/Modules/Devices/src/Devices.Application/Devices/Commands/DeleteDevice/Handler.cs index b0b9682041..2d34ef37c9 100644 --- a/Modules/Devices/src/Devices.Application/Devices/Commands/DeleteDevice/Handler.cs +++ b/Modules/Devices/src/Devices.Application/Devices/Commands/DeleteDevice/Handler.cs @@ -40,7 +40,7 @@ public async Task Handle(DeleteDeviceCommand request, CancellationToken cancella await _identitiesRepository.Update(device, cancellationToken); - _logger.MarkDeviceWithIdAsDeleted(request.DeviceId); + _logger.MarkedDeviceAsDeleted(request.DeviceId); } } @@ -48,8 +48,8 @@ internal static partial class DeleteDeviceLogs { [LoggerMessage( EventId = 776010, - EventName = "Devices.MarkDeviceWithIdAsDeleted", + EventName = "Devices.MarkDeviceAsDeleted.MarkedDeviceAsDeleted", Level = LogLevel.Information, Message = "Successfully marked device with id '{deviceId}' as deleted.")] - public static partial void MarkDeviceWithIdAsDeleted(this ILogger logger, string deviceId); + public static partial void MarkedDeviceAsDeleted(this ILogger logger, string deviceId); } diff --git a/Modules/Files/src/Files.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs b/Modules/Files/src/Files.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs index 64ea42b006..b61b290038 100644 --- a/Modules/Files/src/Files.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs +++ b/Modules/Files/src/Files.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs @@ -44,14 +44,14 @@ internal static partial class FilesLogs { [LoggerMessage( EventId = 629592, - EventName = "Files.LogReporter.NoBlobForFileId", + EventName = "Files.SanityCheck.NoBlobForFileId", Level = LogLevel.Error, Message = "No blob found for file id: '{databaseId}'.")] public static partial void NoBlobForFileId(this ILogger logger, FileId databaseId); [LoggerMessage( EventId = 487180, - EventName = "Files.LogReporter.NoDatabaseEntryForBlobId", + EventName = "Files.SanityCheck.NoDatabaseEntryForBlobId", Level = LogLevel.Error, Message = "No database entry found for blob id: '{blobId}'.")] public static partial void NoDatabaseEntryForBlobId(this ILogger logger, string blobId); diff --git a/Modules/Messages/src/Messages.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs b/Modules/Messages/src/Messages.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs index 870a8548d6..beaec70998 100644 --- a/Modules/Messages/src/Messages.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs +++ b/Modules/Messages/src/Messages.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs @@ -44,14 +44,14 @@ internal static partial class MessagesLogs { [LoggerMessage( EventId = 859729, - EventName = "Messages.LogReporter.NoBlobForMessageId", + EventName = "Messages.SanityCheck.NoBlobForMessageId", Level = LogLevel.Error, Message = "No blob found for file id: '{databaseId}'.")] public static partial void NoBlobForMessageId(this ILogger logger, MessageId databaseId); [LoggerMessage( EventId = 809167, - EventName = "Messages.LogReporter.NoDatabaseEntryForBlobId", + EventName = "Messages.SanityCheck.NoDatabaseEntryForBlobId", Level = LogLevel.Error, Message = "No database entry found for blob id: '{blobId}'.")] public static partial void NoDatabaseEntryForBlobId(this ILogger logger, string blobId); diff --git a/Modules/Quotas/src/Quotas.Application/Tiers/Commands/CreateQuotaForIdentity/Handler.cs b/Modules/Quotas/src/Quotas.Application/Tiers/Commands/CreateQuotaForIdentity/Handler.cs index adfe6c8c80..82dfc509a6 100644 --- a/Modules/Quotas/src/Quotas.Application/Tiers/Commands/CreateQuotaForIdentity/Handler.cs +++ b/Modules/Quotas/src/Quotas.Application/Tiers/Commands/CreateQuotaForIdentity/Handler.cs @@ -39,7 +39,7 @@ public async Task Handle(CreateQuotaForIdentityCommand reque await _identitiesRepository.Update(identity, cancellationToken); - _logger.CreatedQuotasForIdentities(identity.Address); + _logger.CreatedQuotaForIdentities(identity.Address, individualQuota.Id); var identityAddresses = new List { identity.Address }; var metrics = new List { metric.Key.Value }; @@ -54,8 +54,8 @@ internal static partial class CreateQuotaForIdentityLogs { [LoggerMessage( EventId = 868289, - EventName = "Quotas.CreatedQuotasForIdentities", + EventName = "Quotas.CreateQuotaForIdentity.CreatedQuotaForIdentities", Level = LogLevel.Information, - Message = "Successfully created Quota for Identity. Identity Address: '{identityAddress}'.")] - public static partial void CreatedQuotasForIdentities(this ILogger logger, string identityAddress); + Message = "Successfully created Quota for Identity. Identity Address: '{identityAddress}', Quota ID: '{quotaId}'.")] + public static partial void CreatedQuotaForIdentities(this ILogger logger, string identityAddress, string quotaId); } diff --git a/Modules/Quotas/src/Quotas.Application/Tiers/Commands/CreateQuotaForTier/Handler.cs b/Modules/Quotas/src/Quotas.Application/Tiers/Commands/CreateQuotaForTier/Handler.cs index 801f2e4358..195b73ba36 100644 --- a/Modules/Quotas/src/Quotas.Application/Tiers/Commands/CreateQuotaForTier/Handler.cs +++ b/Modules/Quotas/src/Quotas.Application/Tiers/Commands/CreateQuotaForTier/Handler.cs @@ -44,7 +44,7 @@ public async Task Handle(CreateQuotaForTierCommand reque await _tiersRepository.Update(tier, cancellationToken); - _logger.CreatedQuotaForTier(tier.Id, tier.Name); + _logger.CreatedQuotaForTier(tier.Id, tier.Name, result.Value.Id); _eventBus.Publish(new QuotaCreatedForTierIntegrationEvent(tier.Id, result.Value.Id)); @@ -57,8 +57,8 @@ internal static partial class CreateQuotaForTierLogs { [LoggerMessage( EventId = 346835, - EventName = "Quotas.CreatedQuotaForTier", + EventName = "Quotas.CreateQuotaForTier.CreatedQuotaForTier", Level = LogLevel.Information, - Message = "Successfully created Quota for Tier. Tier ID: '{tierId}', Tier Name: '{tierName}'.")] - public static partial void CreatedQuotaForTier(this ILogger logger, TierId tierId, string tierName); + Message = "Successfully created Quota for Tier. Tier ID: '{tierId}', Tier Name: '{tierName}', Quota Definition ID: {quotaDefinitionId}.")] + public static partial void CreatedQuotaForTier(this ILogger logger, TierId tierId, string tierName, string quotaDefinitionId); } diff --git a/Modules/Quotas/src/Quotas.Application/Tiers/Commands/DeleteQuotaForIdentity/Handler.cs b/Modules/Quotas/src/Quotas.Application/Tiers/Commands/DeleteQuotaForIdentity/Handler.cs index c525f16ed1..e753b158c1 100644 --- a/Modules/Quotas/src/Quotas.Application/Tiers/Commands/DeleteQuotaForIdentity/Handler.cs +++ b/Modules/Quotas/src/Quotas.Application/Tiers/Commands/DeleteQuotaForIdentity/Handler.cs @@ -33,7 +33,7 @@ public async Task Handle(DeleteQuotaForIdentityCommand request, CancellationToke await _identitiesRepository.Update(identity, cancellationToken); - _logger.DeletedQuota(request.IndividualQuotaId); + _logger.DeletedQuota(request.IndividualQuotaId, identity.Address); } } @@ -41,8 +41,8 @@ internal static partial class DeleteQuotaForIdentityLogs { [LoggerMessage( EventId = 247156, - EventName = "Quotas.DeleteQuota", + EventName = "Quotas.DeleteQuotaForIdentity.DeletedQuota", Level = LogLevel.Information, - Message = "Successfully deleted individual quota with id: '{individualQuotaId}'.")] - public static partial void DeletedQuota(this ILogger logger, string individualQuotaId); + Message = "Successfully deleted individual quota with id '{individualQuotaId}' from identity with address '{address}'.")] + public static partial void DeletedQuota(this ILogger logger, string individualQuotaId, string address); } diff --git a/Modules/Quotas/src/Quotas.Application/Tiers/Commands/DeleteTierQuotaDefinition/Handler.cs b/Modules/Quotas/src/Quotas.Application/Tiers/Commands/DeleteTierQuotaDefinition/Handler.cs index 56f1945388..791f1a8226 100644 --- a/Modules/Quotas/src/Quotas.Application/Tiers/Commands/DeleteTierQuotaDefinition/Handler.cs +++ b/Modules/Quotas/src/Quotas.Application/Tiers/Commands/DeleteTierQuotaDefinition/Handler.cs @@ -31,7 +31,7 @@ public async Task Handle(DeleteTierQuotaDefinitionCommand request, CancellationT await _tiersRepository.Update(tier, cancellationToken); - _logger.DeletedTierQuota(request.TierQuotaDefinitionId); + _logger.DeletedTierQuota(request.TierQuotaDefinitionId, tier.Id); _eventBus.Publish(new TierQuotaDefinitionDeletedIntegrationEvent(tier.Id, request.TierQuotaDefinitionId)); } @@ -41,8 +41,8 @@ internal static partial class DeleteTierQuotaDefinitionLogs { [LoggerMessage( EventId = 519284, - EventName = "Quotas.DeletedTierQuota", + EventName = "Quotas.DeleteTierQuotaDefinition.DeletedTierQuotaDefinition", Level = LogLevel.Information, - Message = "Successfully deleted tier quota definition with id: '{tierQuotaDefinitionId}'.")] - public static partial void DeletedTierQuota(this ILogger logger, string tierQuotaDefinitionId); + Message = "Successfully deleted tier quota definition with id: '{tierQuotaDefinitionId}' from tier with id '{tierId}'.")] + public static partial void DeletedTierQuotaDefinition(this ILogger logger, string tierQuotaDefinitionId, string tierId); } From 2d2285dd7de9fc645bb270f30ecb1e9b434c6af7 Mon Sep 17 00:00:00 2001 From: Timo Notheisen Date: Fri, 20 Oct 2023 09:07:21 +0200 Subject: [PATCH 122/133] refactor: move identity quota commands to Identities folder --- .../CreateQuotaForIdentityCommand.cs | 2 +- .../CreateQuotaForIdentityCommandValidator.cs | 2 +- .../Commands/CreateQuotaForIdentity/Handler.cs | 2 +- .../DeleteQuotaForIdentityCommand.cs | 2 +- .../DeleteQuotaForIdentityCommandValidator.cs | 2 +- .../Commands/DeleteQuotaForIdentity/Handler.cs | 2 +- .../Tiers/Commands/DeleteTierQuotaDefinition/Handler.cs | 2 +- .../Tests/Quotas/CreateQuotaForIdentity/HandlerTests.cs | 8 ++++---- .../Tests/Quotas/DeleteIndividualQuota/HandlerTests.cs | 6 +++--- 9 files changed, 14 insertions(+), 14 deletions(-) rename Modules/Quotas/src/Quotas.Application/{Tiers => Identities}/Commands/CreateQuotaForIdentity/CreateQuotaForIdentityCommand.cs (87%) rename Modules/Quotas/src/Quotas.Application/{Tiers => Identities}/Commands/CreateQuotaForIdentity/CreateQuotaForIdentityCommandValidator.cs (88%) rename Modules/Quotas/src/Quotas.Application/{Tiers => Identities}/Commands/CreateQuotaForIdentity/Handler.cs (96%) rename Modules/Quotas/src/Quotas.Application/{Tiers => Identities}/Commands/DeleteQuotaForIdentity/DeleteQuotaForIdentityCommand.cs (80%) rename Modules/Quotas/src/Quotas.Application/{Tiers => Identities}/Commands/DeleteQuotaForIdentity/DeleteQuotaForIdentityCommandValidator.cs (80%) rename Modules/Quotas/src/Quotas.Application/{Tiers => Identities}/Commands/DeleteQuotaForIdentity/Handler.cs (95%) diff --git a/Modules/Quotas/src/Quotas.Application/Tiers/Commands/CreateQuotaForIdentity/CreateQuotaForIdentityCommand.cs b/Modules/Quotas/src/Quotas.Application/Identities/Commands/CreateQuotaForIdentity/CreateQuotaForIdentityCommand.cs similarity index 87% rename from Modules/Quotas/src/Quotas.Application/Tiers/Commands/CreateQuotaForIdentity/CreateQuotaForIdentityCommand.cs rename to Modules/Quotas/src/Quotas.Application/Identities/Commands/CreateQuotaForIdentity/CreateQuotaForIdentityCommand.cs index 6c22ff71ce..f133921a0a 100644 --- a/Modules/Quotas/src/Quotas.Application/Tiers/Commands/CreateQuotaForIdentity/CreateQuotaForIdentityCommand.cs +++ b/Modules/Quotas/src/Quotas.Application/Identities/Commands/CreateQuotaForIdentity/CreateQuotaForIdentityCommand.cs @@ -2,7 +2,7 @@ using Backbone.Modules.Quotas.Domain.Aggregates.Identities; using MediatR; -namespace Backbone.Modules.Quotas.Application.Tiers.Commands.CreateQuotaForIdentity; +namespace Backbone.Modules.Quotas.Application.Identities.Commands.CreateQuotaForIdentity; public class CreateQuotaForIdentityCommand : IRequest { diff --git a/Modules/Quotas/src/Quotas.Application/Tiers/Commands/CreateQuotaForIdentity/CreateQuotaForIdentityCommandValidator.cs b/Modules/Quotas/src/Quotas.Application/Identities/Commands/CreateQuotaForIdentity/CreateQuotaForIdentityCommandValidator.cs similarity index 88% rename from Modules/Quotas/src/Quotas.Application/Tiers/Commands/CreateQuotaForIdentity/CreateQuotaForIdentityCommandValidator.cs rename to Modules/Quotas/src/Quotas.Application/Identities/Commands/CreateQuotaForIdentity/CreateQuotaForIdentityCommandValidator.cs index e27376da28..68f8f1033f 100644 --- a/Modules/Quotas/src/Quotas.Application/Tiers/Commands/CreateQuotaForIdentity/CreateQuotaForIdentityCommandValidator.cs +++ b/Modules/Quotas/src/Quotas.Application/Identities/Commands/CreateQuotaForIdentity/CreateQuotaForIdentityCommandValidator.cs @@ -2,7 +2,7 @@ using Enmeshed.BuildingBlocks.Application.FluentValidation; using FluentValidation; -namespace Backbone.Modules.Quotas.Application.Tiers.Commands.CreateQuotaForIdentity; +namespace Backbone.Modules.Quotas.Application.Identities.Commands.CreateQuotaForIdentity; public class CreateQuotaForIdentityCommandValidator : AbstractValidator { diff --git a/Modules/Quotas/src/Quotas.Application/Tiers/Commands/CreateQuotaForIdentity/Handler.cs b/Modules/Quotas/src/Quotas.Application/Identities/Commands/CreateQuotaForIdentity/Handler.cs similarity index 96% rename from Modules/Quotas/src/Quotas.Application/Tiers/Commands/CreateQuotaForIdentity/Handler.cs rename to Modules/Quotas/src/Quotas.Application/Identities/Commands/CreateQuotaForIdentity/Handler.cs index 82dfc509a6..baf6539ddb 100644 --- a/Modules/Quotas/src/Quotas.Application/Tiers/Commands/CreateQuotaForIdentity/Handler.cs +++ b/Modules/Quotas/src/Quotas.Application/Identities/Commands/CreateQuotaForIdentity/Handler.cs @@ -8,7 +8,7 @@ using Microsoft.Extensions.Logging; using MetricKey = Backbone.Modules.Quotas.Domain.Aggregates.Metrics.MetricKey; -namespace Backbone.Modules.Quotas.Application.Tiers.Commands.CreateQuotaForIdentity; +namespace Backbone.Modules.Quotas.Application.Identities.Commands.CreateQuotaForIdentity; public class Handler : IRequestHandler { diff --git a/Modules/Quotas/src/Quotas.Application/Tiers/Commands/DeleteQuotaForIdentity/DeleteQuotaForIdentityCommand.cs b/Modules/Quotas/src/Quotas.Application/Identities/Commands/DeleteQuotaForIdentity/DeleteQuotaForIdentityCommand.cs similarity index 80% rename from Modules/Quotas/src/Quotas.Application/Tiers/Commands/DeleteQuotaForIdentity/DeleteQuotaForIdentityCommand.cs rename to Modules/Quotas/src/Quotas.Application/Identities/Commands/DeleteQuotaForIdentity/DeleteQuotaForIdentityCommand.cs index a1db56652f..3dadb128dd 100644 --- a/Modules/Quotas/src/Quotas.Application/Tiers/Commands/DeleteQuotaForIdentity/DeleteQuotaForIdentityCommand.cs +++ b/Modules/Quotas/src/Quotas.Application/Identities/Commands/DeleteQuotaForIdentity/DeleteQuotaForIdentityCommand.cs @@ -1,6 +1,6 @@ using MediatR; -namespace Backbone.Modules.Quotas.Application.Tiers.Commands.DeleteQuotaForIdentity; +namespace Backbone.Modules.Quotas.Application.Identities.Commands.DeleteQuotaForIdentity; public class DeleteQuotaForIdentityCommand : IRequest { diff --git a/Modules/Quotas/src/Quotas.Application/Tiers/Commands/DeleteQuotaForIdentity/DeleteQuotaForIdentityCommandValidator.cs b/Modules/Quotas/src/Quotas.Application/Identities/Commands/DeleteQuotaForIdentity/DeleteQuotaForIdentityCommandValidator.cs similarity index 80% rename from Modules/Quotas/src/Quotas.Application/Tiers/Commands/DeleteQuotaForIdentity/DeleteQuotaForIdentityCommandValidator.cs rename to Modules/Quotas/src/Quotas.Application/Identities/Commands/DeleteQuotaForIdentity/DeleteQuotaForIdentityCommandValidator.cs index 08c1d8c9e3..f2ac1fb825 100644 --- a/Modules/Quotas/src/Quotas.Application/Tiers/Commands/DeleteQuotaForIdentity/DeleteQuotaForIdentityCommandValidator.cs +++ b/Modules/Quotas/src/Quotas.Application/Identities/Commands/DeleteQuotaForIdentity/DeleteQuotaForIdentityCommandValidator.cs @@ -1,7 +1,7 @@ using Enmeshed.BuildingBlocks.Application.FluentValidation; using FluentValidation; -namespace Backbone.Modules.Quotas.Application.Tiers.Commands.DeleteQuotaForIdentity; +namespace Backbone.Modules.Quotas.Application.Identities.Commands.DeleteQuotaForIdentity; public class DeleteQuotaForIdentityCommandValidator : AbstractValidator { diff --git a/Modules/Quotas/src/Quotas.Application/Tiers/Commands/DeleteQuotaForIdentity/Handler.cs b/Modules/Quotas/src/Quotas.Application/Identities/Commands/DeleteQuotaForIdentity/Handler.cs similarity index 95% rename from Modules/Quotas/src/Quotas.Application/Tiers/Commands/DeleteQuotaForIdentity/Handler.cs rename to Modules/Quotas/src/Quotas.Application/Identities/Commands/DeleteQuotaForIdentity/Handler.cs index e753b158c1..b975497a4e 100644 --- a/Modules/Quotas/src/Quotas.Application/Tiers/Commands/DeleteQuotaForIdentity/Handler.cs +++ b/Modules/Quotas/src/Quotas.Application/Identities/Commands/DeleteQuotaForIdentity/Handler.cs @@ -5,7 +5,7 @@ using MediatR; using Microsoft.Extensions.Logging; -namespace Backbone.Modules.Quotas.Application.Tiers.Commands.DeleteQuotaForIdentity; +namespace Backbone.Modules.Quotas.Application.Identities.Commands.DeleteQuotaForIdentity; public class Handler : IRequestHandler { private readonly IIdentitiesRepository _identitiesRepository; diff --git a/Modules/Quotas/src/Quotas.Application/Tiers/Commands/DeleteTierQuotaDefinition/Handler.cs b/Modules/Quotas/src/Quotas.Application/Tiers/Commands/DeleteTierQuotaDefinition/Handler.cs index 791f1a8226..a5c7093230 100644 --- a/Modules/Quotas/src/Quotas.Application/Tiers/Commands/DeleteTierQuotaDefinition/Handler.cs +++ b/Modules/Quotas/src/Quotas.Application/Tiers/Commands/DeleteTierQuotaDefinition/Handler.cs @@ -31,7 +31,7 @@ public async Task Handle(DeleteTierQuotaDefinitionCommand request, CancellationT await _tiersRepository.Update(tier, cancellationToken); - _logger.DeletedTierQuota(request.TierQuotaDefinitionId, tier.Id); + _logger.DeletedTierQuotaDefinition(request.TierQuotaDefinitionId, tier.Id); _eventBus.Publish(new TierQuotaDefinitionDeletedIntegrationEvent(tier.Id, request.TierQuotaDefinitionId)); } diff --git a/Modules/Quotas/test/Quotas.Application.Tests/Tests/Quotas/CreateQuotaForIdentity/HandlerTests.cs b/Modules/Quotas/test/Quotas.Application.Tests/Tests/Quotas/CreateQuotaForIdentity/HandlerTests.cs index 163015c72f..fdbd3e80af 100644 --- a/Modules/Quotas/test/Quotas.Application.Tests/Tests/Quotas/CreateQuotaForIdentity/HandlerTests.cs +++ b/Modules/Quotas/test/Quotas.Application.Tests/Tests/Quotas/CreateQuotaForIdentity/HandlerTests.cs @@ -1,7 +1,7 @@ -using Backbone.Modules.Quotas.Application.Infrastructure.Persistence.Repository; +using Backbone.Modules.Quotas.Application.Identities.Commands.CreateQuotaForIdentity; +using Backbone.Modules.Quotas.Application.Infrastructure.Persistence.Repository; using Backbone.Modules.Quotas.Application.Metrics; using Backbone.Modules.Quotas.Application.Tests.TestDoubles; -using Backbone.Modules.Quotas.Application.Tiers.Commands.CreateQuotaForIdentity; using Backbone.Modules.Quotas.Domain.Aggregates.Identities; using Backbone.Modules.Quotas.Domain.Aggregates.Metrics; using Backbone.Modules.Quotas.Domain.Aggregates.Tiers; @@ -23,8 +23,8 @@ public class HandlerTests public async Task Creates_quota_for_identity() { // Arrange - var max = 5; - var period = QuotaPeriod.Month; + const int max = 5; + const QuotaPeriod period = QuotaPeriod.Month; var metricKey = MetricKey.NumberOfSentMessages.Value; var identityAddress = IdentityAddress.Parse("id1KJnD8ipfckRQ1ivAhNVLtypmcVM5vPX4j"); var tierId = new TierId("TIRsomeTierId1111111"); diff --git a/Modules/Quotas/test/Quotas.Application.Tests/Tests/Quotas/DeleteIndividualQuota/HandlerTests.cs b/Modules/Quotas/test/Quotas.Application.Tests/Tests/Quotas/DeleteIndividualQuota/HandlerTests.cs index c588f63010..30fac5e8b7 100644 --- a/Modules/Quotas/test/Quotas.Application.Tests/Tests/Quotas/DeleteIndividualQuota/HandlerTests.cs +++ b/Modules/Quotas/test/Quotas.Application.Tests/Tests/Quotas/DeleteIndividualQuota/HandlerTests.cs @@ -1,5 +1,5 @@ -using Backbone.Modules.Quotas.Application.Infrastructure.Persistence.Repository; -using Backbone.Modules.Quotas.Application.Tiers.Commands.DeleteQuotaForIdentity; +using Backbone.Modules.Quotas.Application.Identities.Commands.DeleteQuotaForIdentity; +using Backbone.Modules.Quotas.Application.Infrastructure.Persistence.Repository; using Backbone.Modules.Quotas.Domain.Aggregates.Identities; using Backbone.Modules.Quotas.Domain.Aggregates.Tiers; using Enmeshed.BuildingBlocks.Application.Abstractions.Exceptions; @@ -9,7 +9,7 @@ using FluentAssertions; using Microsoft.Extensions.Logging; using Xunit; -using Handler = Backbone.Modules.Quotas.Application.Tiers.Commands.DeleteQuotaForIdentity.Handler; +using Handler = Backbone.Modules.Quotas.Application.Identities.Commands.DeleteQuotaForIdentity.Handler; using MetricKey = Backbone.Modules.Quotas.Domain.Aggregates.Metrics.MetricKey; namespace Backbone.Modules.Quotas.Application.Tests.Tests.Quotas.DeleteIndividualQuota; From e71339d1652adea44cdf9c1d7fc2658cadfa5b0d Mon Sep 17 00:00:00 2001 From: Timo Notheisen Date: Fri, 20 Oct 2023 09:07:36 +0200 Subject: [PATCH 123/133] fix: compiler error --- .../ExceptionFilters/CustomExceptionFilter.cs | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/BuildingBlocks/src/BuildingBlocks.API/Mvc/ExceptionFilters/CustomExceptionFilter.cs b/BuildingBlocks/src/BuildingBlocks.API/Mvc/ExceptionFilters/CustomExceptionFilter.cs index 714d876afa..d2d3489c44 100644 --- a/BuildingBlocks/src/BuildingBlocks.API/Mvc/ExceptionFilters/CustomExceptionFilter.cs +++ b/BuildingBlocks/src/BuildingBlocks.API/Mvc/ExceptionFilters/CustomExceptionFilter.cs @@ -1,5 +1,4 @@ -using System; -using System.Net; +using System.Net; using System.Text.Json; using System.Text.RegularExpressions; using Enmeshed.BuildingBlocks.API.Extensions; @@ -81,7 +80,7 @@ public override void OnException(ExceptionContext context) break; default: - _logger.ErrorWhileProcessingRequestToUri(context.HttpContext.Request.GetUri()); + _logger.ErrorWhileProcessingRequestToUri(context.HttpContext.Request.GetDisplayUrl()); httpError = CreateHttpErrorForUnexpectedException(context); @@ -147,12 +146,12 @@ private HttpError CreateHttpErrorForDomainException(DomainException domainExcept return null; } - private HttpStatusCode GetStatusCodeForInfrastructureException(InfrastructureException exception) + private static HttpStatusCode GetStatusCodeForInfrastructureException(InfrastructureException exception) { return HttpStatusCode.BadRequest; } - private HttpStatusCode GetStatusCodeForApplicationException(ApplicationException exception) + private static HttpStatusCode GetStatusCodeForApplicationException(ApplicationException exception) { return exception switch { @@ -206,7 +205,7 @@ private HttpError CreateHttpErrorForUnexpectedException(ExceptionContext context return httpError; } - private IEnumerable GetFormattedStackTrace(Exception exception) + private static IEnumerable GetFormattedStackTrace(Exception exception) { if (exception.StackTrace == null) return Enumerable.Empty(); @@ -229,13 +228,13 @@ internal static partial class ExceptionFilterLogs EventId = 938218, EventName = "ExceptionFilter.RequestBodyTooLarge", Level = LogLevel.Information, - Message = "'{error_code}': The body of the request is too large.")] - public static partial void RequestBodyTooLarge(this ILogger logger, string error_code); + Message = "'{errorCode}': The body of the request is too large.")] + public static partial void RequestBodyTooLarge(this ILogger logger, string errorCode); [LoggerMessage( EventId = 259125, EventName = "ExceptionFilter.ErrorWhileProcessingRequestToUri", Level = LogLevel.Error, Message = "Unexpected Error while processing request to '{uri}'.")] - public static partial void ErrorWhileProcessingRequestToUri(this ILogger logger, Uri uri); + public static partial void ErrorWhileProcessingRequestToUri(this ILogger logger, string uri); } From 5b519bd5083059099d2ee062d9b0d4fe28da6125 Mon Sep 17 00:00:00 2001 From: Timo Notheisen Date: Fri, 20 Oct 2023 09:21:20 +0200 Subject: [PATCH 124/133] chore: change remaining log event ids --- .../Infrastructure/Reporter/LogReporter.cs | 2 +- .../Infrastructure/Reporter/LogReporter.cs | 2 +- .../Infrastructure/Reporter/LogReporter.cs | 6 +++--- .../Infrastructure/Reporter/LogReporter.cs | 6 +++--- .../Infrastructure/Reporter/LogReporter.cs | 6 +++--- .../Infrastructure/Reporter/LogReporter.cs | 6 +++--- 6 files changed, 14 insertions(+), 14 deletions(-) diff --git a/Modules/Files/src/Files.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs b/Modules/Files/src/Files.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs index b61b290038..eca8d569e9 100644 --- a/Modules/Files/src/Files.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs +++ b/Modules/Files/src/Files.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs @@ -40,7 +40,7 @@ public void ReportOrphanedDatabaseId(FileId id) } } -internal static partial class FilesLogs +internal static partial class LogReporterLogs { [LoggerMessage( EventId = 629592, diff --git a/Modules/Messages/src/Messages.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs b/Modules/Messages/src/Messages.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs index beaec70998..33db75bd07 100644 --- a/Modules/Messages/src/Messages.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs +++ b/Modules/Messages/src/Messages.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs @@ -40,7 +40,7 @@ public void ReportOrphanedDatabaseId(MessageId id) } } -internal static partial class MessagesLogs +internal static partial class LogReporterLogs { [LoggerMessage( EventId = 859729, diff --git a/Modules/Relationships/src/Relationships.Jobs.SanityCheck.RelationshipChange/Infrastructure/Reporter/LogReporter.cs b/Modules/Relationships/src/Relationships.Jobs.SanityCheck.RelationshipChange/Infrastructure/Reporter/LogReporter.cs index aab9f3a34d..22ff370b06 100644 --- a/Modules/Relationships/src/Relationships.Jobs.SanityCheck.RelationshipChange/Infrastructure/Reporter/LogReporter.cs +++ b/Modules/Relationships/src/Relationships.Jobs.SanityCheck.RelationshipChange/Infrastructure/Reporter/LogReporter.cs @@ -40,18 +40,18 @@ public void ReportOrphanedDatabaseId(RelationshipChangeId id) } } -internal static partial class RelationshipChangeLogs +internal static partial class LogReporterLogs { [LoggerMessage( EventId = 349287, - EventName = "Relationships.LogReporter.NoBlobForRelationshipChangeId", + EventName = "Relationships.SanityCheck.NoBlobForRelationshipChangeId", Level = LogLevel.Error, Message = "No blob found for relationship change id: '{databaseId}'.")] public static partial void NoBlobForRelationshipChangeId(this ILogger logger, RelationshipChangeId databaseId); [LoggerMessage( EventId = 429922, - EventName = "Relationships.LogReporter.NoDatabaseEntryForBlobId", + EventName = "Relationships.SanityCheck.NoDatabaseEntryForBlobId", Level = LogLevel.Error, Message = "No database entry found for blob id: '{blobId}'.")] public static partial void NoDatabaseEntryForBlobId(this ILogger logger, string blobId); diff --git a/Modules/Relationships/src/Relationships.Jobs.SanityCheck.RelationshipTemplate/Infrastructure/Reporter/LogReporter.cs b/Modules/Relationships/src/Relationships.Jobs.SanityCheck.RelationshipTemplate/Infrastructure/Reporter/LogReporter.cs index 08282ccb09..703321386c 100644 --- a/Modules/Relationships/src/Relationships.Jobs.SanityCheck.RelationshipTemplate/Infrastructure/Reporter/LogReporter.cs +++ b/Modules/Relationships/src/Relationships.Jobs.SanityCheck.RelationshipTemplate/Infrastructure/Reporter/LogReporter.cs @@ -40,18 +40,18 @@ public void ReportOrphanedDatabaseId(RelationshipTemplateId id) } } -internal static partial class RelationshipTemplateLogs +internal static partial class LogReporterLogs { [LoggerMessage( EventId = 231727, - EventName = "Relationships.LogReporter.NoBlobForRelationshipTemplateId", + EventName = "Relationships.SanityCheck.NoBlobForRelationshipTemplateId", Level = LogLevel.Error, Message = "No blob found for relationship template id: '{databaseId}'.")] public static partial void NoBlobForRelationshipTemplateId(this ILogger logger, RelationshipTemplateId databaseId); [LoggerMessage( EventId = 232800, - EventName = "Relationships.LogReporter.NoDatabaseEntryForBlobId", + EventName = "Relationships.SanityCheck.NoDatabaseEntryForBlobId", Level = LogLevel.Error, Message = "No database entry found for blob id: '{blobId}'.")] public static partial void NoDatabaseEntryForBlobId(this ILogger logger, string blobId); diff --git a/Modules/Synchronization/src/Synchronization.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs b/Modules/Synchronization/src/Synchronization.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs index 85a8fc2ddb..e0f8a37c5f 100644 --- a/Modules/Synchronization/src/Synchronization.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs +++ b/Modules/Synchronization/src/Synchronization.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs @@ -40,18 +40,18 @@ public void ReportOrphanedDatabaseId(DatawalletModificationId id) } } -internal static partial class SynchronizationLogs +internal static partial class LogReporterLogs { [LoggerMessage( EventId = 525684, - EventName = "Synchronization.LogReporter.NoBlobForDatawalletModificationId", + EventName = "Synchronization.SanityCheck.NoBlobForDatawalletModificationId", Level = LogLevel.Error, Message = "No blob found for datawallet modification id: '{databaseId}'.")] public static partial void NoBlobForDatawalletModificationId(this ILogger logger, DatawalletModificationId databaseId); [LoggerMessage( EventId = 560290, - EventName = "Synchronization.LogReporter.NoDatabaseEntryForBlobId", + EventName = "Synchronization.SanityCheck.NoDatabaseEntryForBlobId", Level = LogLevel.Error, Message = "No database entry found for blob id: '{blobId}'.")] public static partial void NoDatabaseEntryForBlobId(this ILogger logger, string blobId); diff --git a/Modules/Tokens/src/Tokens.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs b/Modules/Tokens/src/Tokens.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs index 0894ec3142..650878e664 100644 --- a/Modules/Tokens/src/Tokens.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs +++ b/Modules/Tokens/src/Tokens.Jobs.SanityCheck/Infrastructure/Reporter/LogReporter.cs @@ -40,18 +40,18 @@ public void ReportOrphanedDatabaseId(TokenId id) } } -internal static partial class TokensLogs +internal static partial class LogReporterLogs { [LoggerMessage( EventId = 826083, - EventName = "Tokens.LogReporter.NoBlobForTokenId", + EventName = "Tokens.SanityCheck.NoBlobForTokenId", Level = LogLevel.Error, Message = "No blob found for token id: '{tokenId}'.")] public static partial void NoBlobForTokenId(this ILogger logger, TokenId tokenId); [LoggerMessage( EventId = 271286, - EventName = "Tokens.LogReporter.NoDatabaseEntryForBlobId", + EventName = "Tokens.SanityCheck.NoDatabaseEntryForBlobId", Level = LogLevel.Error, Message = "No database entry found for blob id: '{blobId}'.")] public static partial void NoDatabaseEntryForBlobId(this ILogger logger, string blobId); From 70c1ed67a8dd8725a930dc253a30a689bed9668e Mon Sep 17 00:00:00 2001 From: Timo Notheisen Date: Fri, 20 Oct 2023 09:21:38 +0200 Subject: [PATCH 125/133] chore: simplify linux script for event id generation --- scripts/linux/get_random_event_id.sh | 12 +----------- 1 file changed, 1 insertion(+), 11 deletions(-) diff --git a/scripts/linux/get_random_event_id.sh b/scripts/linux/get_random_event_id.sh index 2b223a24e7..25026988e6 100644 --- a/scripts/linux/get_random_event_id.sh +++ b/scripts/linux/get_random_event_id.sh @@ -1,12 +1,2 @@ #!/bin/bash - -while true; do - # Generate a random number in the range [0, 899999] - NUMBER=$(( $(dd if=/dev/urandom bs=3 count=1 2>/dev/null | od -An -i | tr -d '[:space:]') % 900000 )) - - # Adjust the number to the range [100000, 999999] - NUMBER=$(( NUMBER + 100000 )) - - echo $NUMBER - break -done +shufff -i 100000-999999 -n 1 From 67f70bef18b50a8c5e6ed76474547a96d601a3bc Mon Sep 17 00:00:00 2001 From: Timo Notheisen Date: Fri, 20 Oct 2023 09:22:21 +0200 Subject: [PATCH 126/133] chore: rename scripts for generating log event ids --- README.md | 2 +- .../linux/{get_random_event_id.sh => generate_log_event_id.sh} | 0 .../{get_random_event_id.ps1 => generate_log_event_id.ps1} | 0 3 files changed, 1 insertion(+), 1 deletion(-) rename scripts/linux/{get_random_event_id.sh => generate_log_event_id.sh} (100%) rename scripts/windows/{get_random_event_id.ps1 => generate_log_event_id.ps1} (100%) diff --git a/README.md b/README.md index ce19ee89c4..235561bbb3 100644 --- a/README.md +++ b/README.md @@ -23,7 +23,7 @@ Contribution to this project is highly appreciated. Head over to our [contributi ### Logging -Log event IDs are random 6-digit numbers and can be generated using `./scripts/linux/get_random_event_id.sh` or `./scripts/windows/get_random_event_id.ps1`. Simply run the scripts to generate a random 6-digit positive integer. +Log event IDs are random 6-digit numbers and can be generated using `./scripts/linux/generate_log_event_id.sh` or `./scripts/windows/generate_log_event_id.ps1`. Simply run the scripts to generate a random 6-digit positive integer. ## License diff --git a/scripts/linux/get_random_event_id.sh b/scripts/linux/generate_log_event_id.sh similarity index 100% rename from scripts/linux/get_random_event_id.sh rename to scripts/linux/generate_log_event_id.sh diff --git a/scripts/windows/get_random_event_id.ps1 b/scripts/windows/generate_log_event_id.ps1 similarity index 100% rename from scripts/windows/get_random_event_id.ps1 rename to scripts/windows/generate_log_event_id.ps1 From 8b8fa2f1a3593b6af118a556608c47932191c2dc Mon Sep 17 00:00:00 2001 From: Timo Notheisen Date: Fri, 20 Oct 2023 09:26:37 +0200 Subject: [PATCH 127/133] fix: compiler errors --- AdminUi/src/AdminUi/Controllers/IdentitiesController.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/AdminUi/src/AdminUi/Controllers/IdentitiesController.cs b/AdminUi/src/AdminUi/Controllers/IdentitiesController.cs index 3a083906b3..11d90d0953 100644 --- a/AdminUi/src/AdminUi/Controllers/IdentitiesController.cs +++ b/AdminUi/src/AdminUi/Controllers/IdentitiesController.cs @@ -4,8 +4,8 @@ using Backbone.Modules.Devices.Application.Devices.DTOs; using Backbone.Modules.Devices.Application.Identities.Commands.UpdateIdentity; using Backbone.Modules.Quotas.Application.DTOs; -using Backbone.Modules.Quotas.Application.Tiers.Commands.CreateQuotaForIdentity; -using Backbone.Modules.Quotas.Application.Tiers.Commands.DeleteQuotaForIdentity; +using Backbone.Modules.Quotas.Application.Identities.Commands.CreateQuotaForIdentity; +using Backbone.Modules.Quotas.Application.Identities.Commands.DeleteQuotaForIdentity; using Backbone.Modules.Quotas.Domain.Aggregates.Identities; using Enmeshed.BuildingBlocks.API; using Enmeshed.BuildingBlocks.API.Mvc; From 9eb98fbe1c34cef73c0f138d5bd13100de2c7cad Mon Sep 17 00:00:00 2001 From: Timo Notheisen Date: Fri, 20 Oct 2023 09:37:07 +0200 Subject: [PATCH 128/133] chore: fix formatting --- Backbone.Infrastructure/Logging/LogHelper.cs | 2 +- .../EventBus/AzureServiceBus/EventBusAzureServiceBus.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Backbone.Infrastructure/Logging/LogHelper.cs b/Backbone.Infrastructure/Logging/LogHelper.cs index 4e9b9a8db6..86547b87fe 100644 --- a/Backbone.Infrastructure/Logging/LogHelper.cs +++ b/Backbone.Infrastructure/Logging/LogHelper.cs @@ -27,7 +27,7 @@ private static bool IsHealthCheckEndpoint(HttpContext ctx) "Health checks", StringComparison.Ordinal); } - + return false; } diff --git a/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/AzureServiceBus/EventBusAzureServiceBus.cs b/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/AzureServiceBus/EventBusAzureServiceBus.cs index 1ad036d8db..e010740baf 100644 --- a/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/AzureServiceBus/EventBusAzureServiceBus.cs +++ b/BuildingBlocks/src/BuildingBlocks.Infrastructure/EventBus/AzureServiceBus/EventBusAzureServiceBus.cs @@ -215,7 +215,7 @@ internal static partial class EventBusAzureServiceBusLogs Level = LogLevel.Warning, Message = "An error was thrown while executing '{eventHandlerType}'. Attempting to retry...")] public static partial void ErrorWhileExecutingEventHandlerType(this ILogger logger, string eventHandlerType, Exception exception); - + [LoggerMessage( EventId = 146670, EventName = "EventBusAzureServiceBus.ErrorWhileProcessingIntegrationEvent", From ebd8ef68672115e501027314d5bd18d9669e347d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Fri, 20 Oct 2023 13:23:14 +0200 Subject: [PATCH 129/133] chore: use LoggerMessageAttribute --- .../Commands/RegisterDevice/Handler.cs | 19 +++++++------------ 1 file changed, 7 insertions(+), 12 deletions(-) diff --git a/Modules/Devices/src/Devices.Application/Devices/Commands/RegisterDevice/Handler.cs b/Modules/Devices/src/Devices.Application/Devices/Commands/RegisterDevice/Handler.cs index 24df392d6f..ba015b276e 100644 --- a/Modules/Devices/src/Devices.Application/Devices/Commands/RegisterDevice/Handler.cs +++ b/Modules/Devices/src/Devices.Application/Devices/Commands/RegisterDevice/Handler.cs @@ -111,17 +111,12 @@ public override void Write(Utf8JsonWriter writer, } } -file static class LoggerExtensions +internal static partial class DeleteDeviceLogs { - private static readonly Action CREATED_DEVICE = - LoggerMessage.Define( - LogLevel.Information, - new EventId(219823, "Devices.CreatedDevice"), - "Successfully created device. Device ID: '{deviceId}', User ID: '{userId}', Username: '{userName}'." - ); - - public static void CreatedDevice(this ILogger logger, DeviceId deviceId, string userId, string userName) - { - CREATED_DEVICE(logger, deviceId, userId, userName, default!); - } + [LoggerMessage( + EventId = 219823, + EventName = "Devices.CreatedDevice", + Level = LogLevel.Information, + Message = "Successfully created device. Device ID: '{deviceId}', User ID: '{userId}', Username: '{userName}'.")] + public static partial void CreatedDevice(this ILogger logger, DeviceId deviceId, string userId, string userName); } From b071cdc2daec121afa8de86dd6216f7942f6dff0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Fri, 20 Oct 2023 13:24:35 +0200 Subject: [PATCH 130/133] chore: use LoggerMessageAttribute --- .../Commands/CreateIdentity/Handler.cs | 19 +++++++------------ 1 file changed, 7 insertions(+), 12 deletions(-) diff --git a/Modules/Devices/src/Devices.Application/Identities/Commands/CreateIdentity/Handler.cs b/Modules/Devices/src/Devices.Application/Identities/Commands/CreateIdentity/Handler.cs index 0655b62b5e..51e4952e0a 100644 --- a/Modules/Devices/src/Devices.Application/Identities/Commands/CreateIdentity/Handler.cs +++ b/Modules/Devices/src/Devices.Application/Identities/Commands/CreateIdentity/Handler.cs @@ -72,17 +72,12 @@ public async Task Handle(CreateIdentityCommand command, } } -file static class LoggerExtensions +internal static partial class CreatedIdentityLogs { - private static readonly Action CREATED_IDENTITY = - LoggerMessage.Define( - LogLevel.Information, - new EventId(436321, "Devices.CreatedIdentity"), - "Identity created. Address: '{address}', Device ID: '{deviceId}', Username: '{userName}'." - ); - - public static void CreatedIdentity(this ILogger logger, IdentityAddress identityAddress, DeviceId deviceId, string userName) - { - CREATED_IDENTITY(logger, identityAddress, deviceId, userName, default!); - } + [LoggerMessage( + EventId = 436321, + EventName = "Devices.CreatedIdentity", + Level = LogLevel.Information, + Message = "Identity created. Address: '{address}', Device ID: '{deviceId}', Username: '{userName}'.")] + public static partial void CreatedIdentity(this ILogger logger, IdentityAddress address, DeviceId deviceId, string userName); } From dc90dcde24dc562f885aea580edde1d12c8ab53a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Fri, 20 Oct 2023 13:26:47 +0200 Subject: [PATCH 131/133] chore: use LoggerMessageAttribute --- .../Tiers/Commands/CreateTier/Handler.cs | 20 ++++++++----------- 1 file changed, 8 insertions(+), 12 deletions(-) diff --git a/Modules/Devices/src/Devices.Application/Tiers/Commands/CreateTier/Handler.cs b/Modules/Devices/src/Devices.Application/Tiers/Commands/CreateTier/Handler.cs index 88bbe94acf..d3bd047130 100644 --- a/Modules/Devices/src/Devices.Application/Tiers/Commands/CreateTier/Handler.cs +++ b/Modules/Devices/src/Devices.Application/Tiers/Commands/CreateTier/Handler.cs @@ -2,6 +2,7 @@ using Backbone.Modules.Devices.Application.IntegrationEvents.Outgoing; using Backbone.Modules.Devices.Domain.Aggregates.Tier; using Enmeshed.BuildingBlocks.Application.Abstractions.Infrastructure.EventBus; +using Enmeshed.DevelopmentKit.Identity.ValueObjects; using MediatR; using Microsoft.Extensions.Logging; using ApplicationException = Enmeshed.BuildingBlocks.Application.Abstractions.Exceptions.ApplicationException; @@ -41,17 +42,12 @@ public async Task Handle(CreateTierCommand request, Cancella } } -file static class LoggerExtensions +internal static partial class CreatedTierLogs { - private static readonly Action CREATED_TIER = - LoggerMessage.Define( - LogLevel.Information, - new EventId(383136, "Devices.CreatedTier"), - "Successfully created tier. Tier ID: '{tierId}', Tier Name: {tierName}" - ); - - public static void CreatedTier(this ILogger logger, string tierId, string tierName) - { - CREATED_TIER(logger, tierId, tierName, default!); - } + [LoggerMessage( + EventId = 383136, + EventName = "Devices.CreatedTier", + Level = LogLevel.Information, + Message = "Successfully created tier. Tier ID: '{tierId}', Tier Name: {tierName}")] + public static partial void CreatedTier(this ILogger logger, string tierId, string tierName); } From 6c3e15bd646eaba8b2aaa388a54c03d114455449 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Vetni=C4=87?= Date: Fri, 20 Oct 2023 13:28:09 +0200 Subject: [PATCH 132/133] chore: use LoggerMessageAttribute --- .../DirectPush/DirectPushService.cs | 57 +++++++------------ 1 file changed, 21 insertions(+), 36 deletions(-) diff --git a/Modules/Devices/src/Devices.Infrastructure/PushNotifications/DirectPush/DirectPushService.cs b/Modules/Devices/src/Devices.Infrastructure/PushNotifications/DirectPush/DirectPushService.cs index f96cb28128..bbd5fbbe57 100644 --- a/Modules/Devices/src/Devices.Infrastructure/PushNotifications/DirectPush/DirectPushService.cs +++ b/Modules/Devices/src/Devices.Infrastructure/PushNotifications/DirectPush/DirectPushService.cs @@ -114,41 +114,26 @@ public async Task DeleteRegistration(DeviceId deviceId, CancellationToken cancel } } -file static class LoggerExtensions +internal static partial class DirectPushServiceLogs { - private static readonly Action DELETING_DEVICE_REGISTRATION = - LoggerMessage.Define( - LogLevel.Information, - new EventId(950845, "Devices.DirectPushService.DeletingDeviceRegistration"), - "Deleting device registration for '{deviceId}' since handle is no longer valid." - ); - - private static readonly Action ERROR_WHILE_TRYING_TO_SEND_NOTIFICATION = - LoggerMessage.Define( - LogLevel.Error, - new EventId(624412, "Devices.DirectPushService.ErrorWhileTryingToSendNotification"), - "The following error occurred while trying to send the notification for '{deviceId}': '{error}'." - ); - - private static readonly Action UNREGISTERED_DEVICE = - LoggerMessage.Define( - LogLevel.Information, - new EventId(628738, "Devices.DirectPushService.UnregisteredDevice"), - "Unregistered device '{deviceId} from push notifications." - ); - - public static void DeletingDeviceRegistration(this ILogger logger, DeviceId deviceId) - { - DELETING_DEVICE_REGISTRATION(logger, deviceId, default!); - } - - public static void ErrorWhileTryingToSendNotification(this ILogger logger, DeviceId deviceId, string error) - { - ERROR_WHILE_TRYING_TO_SEND_NOTIFICATION(logger, deviceId, error, default!); - } - - public static void UnregisteredDevice(this ILogger logger, DeviceId deviceId) - { - UNREGISTERED_DEVICE(logger, deviceId, default!); - } + [LoggerMessage( + EventId = 950845, + EventName = "Devices.DirectPushService.DeletingDeviceRegistration", + Level = LogLevel.Information, + Message = "Deleting device registration for '{deviceId}' since handle is no longer valid.")] + public static partial void DeletingDeviceRegistration(this ILogger logger, DeviceId deviceId); + + [LoggerMessage( + EventId = 624412, + EventName = "Devices.DirectPushService.ErrorWhileTryingToSendNotification", + Level = LogLevel.Error, + Message = "The following error occurred while trying to send the notification for '{deviceId}': '{error}'.")] + public static partial void ErrorWhileTryingToSendNotification(this ILogger logger, DeviceId deviceId, string error); + + [LoggerMessage( + EventId = 628738, + EventName = "Devices.DirectPushService.UnregisteredDevice", + Level = LogLevel.Information, + Message = "Unregistered device '{deviceId} from push notifications.")] + public static partial void UnregisteredDevice(this ILogger logger, DeviceId deviceId); } From 3f6914e6d3176d793276db83dd28697256c42fa3 Mon Sep 17 00:00:00 2001 From: Timo Notheisen Date: Fri, 20 Oct 2023 13:33:26 +0200 Subject: [PATCH 133/133] chore: fix event ids --- .../Devices/Commands/RegisterDevice/Handler.cs | 2 +- .../Identities/Commands/CreateIdentity/Handler.cs | 2 +- .../Devices.Application/Tiers/Commands/CreateTier/Handler.cs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Modules/Devices/src/Devices.Application/Devices/Commands/RegisterDevice/Handler.cs b/Modules/Devices/src/Devices.Application/Devices/Commands/RegisterDevice/Handler.cs index ba015b276e..e59eed4f28 100644 --- a/Modules/Devices/src/Devices.Application/Devices/Commands/RegisterDevice/Handler.cs +++ b/Modules/Devices/src/Devices.Application/Devices/Commands/RegisterDevice/Handler.cs @@ -115,7 +115,7 @@ internal static partial class DeleteDeviceLogs { [LoggerMessage( EventId = 219823, - EventName = "Devices.CreatedDevice", + EventName = "Devices.RegisterDevice.RegisteredDevice", Level = LogLevel.Information, Message = "Successfully created device. Device ID: '{deviceId}', User ID: '{userId}', Username: '{userName}'.")] public static partial void CreatedDevice(this ILogger logger, DeviceId deviceId, string userId, string userName); diff --git a/Modules/Devices/src/Devices.Application/Identities/Commands/CreateIdentity/Handler.cs b/Modules/Devices/src/Devices.Application/Identities/Commands/CreateIdentity/Handler.cs index 51e4952e0a..c44dc19afe 100644 --- a/Modules/Devices/src/Devices.Application/Identities/Commands/CreateIdentity/Handler.cs +++ b/Modules/Devices/src/Devices.Application/Identities/Commands/CreateIdentity/Handler.cs @@ -76,7 +76,7 @@ internal static partial class CreatedIdentityLogs { [LoggerMessage( EventId = 436321, - EventName = "Devices.CreatedIdentity", + EventName = "Devices.CreateIdentity.CreatedIdentity", Level = LogLevel.Information, Message = "Identity created. Address: '{address}', Device ID: '{deviceId}', Username: '{userName}'.")] public static partial void CreatedIdentity(this ILogger logger, IdentityAddress address, DeviceId deviceId, string userName); diff --git a/Modules/Devices/src/Devices.Application/Tiers/Commands/CreateTier/Handler.cs b/Modules/Devices/src/Devices.Application/Tiers/Commands/CreateTier/Handler.cs index d3bd047130..21bd1d0c78 100644 --- a/Modules/Devices/src/Devices.Application/Tiers/Commands/CreateTier/Handler.cs +++ b/Modules/Devices/src/Devices.Application/Tiers/Commands/CreateTier/Handler.cs @@ -46,7 +46,7 @@ internal static partial class CreatedTierLogs { [LoggerMessage( EventId = 383136, - EventName = "Devices.CreatedTier", + EventName = "Devices.CreateTier.CreatedTier", Level = LogLevel.Information, Message = "Successfully created tier. Tier ID: '{tierId}', Tier Name: {tierName}")] public static partial void CreatedTier(this ILogger logger, string tierId, string tierName);