Skip to content

Commit

Permalink
Merge main into filtering-and-ordering-for-overview-tables
Browse files Browse the repository at this point in the history
  • Loading branch information
github-actions[bot] authored Oct 20, 2023
2 parents 6db8b1b + 34687df commit 54f73f7
Show file tree
Hide file tree
Showing 49 changed files with 701 additions and 192 deletions.
4 changes: 2 additions & 2 deletions AdminUi/src/AdminUi/Controllers/IdentitiesController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,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.Mvc;
using Enmeshed.BuildingBlocks.API.Mvc.ControllerAttributes;
Expand Down
5 changes: 2 additions & 3 deletions Backbone.Infrastructure/Logging/LogHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand All @@ -28,7 +28,6 @@ private static bool IsHealthCheckEndpoint(HttpContext ctx)
StringComparison.Ordinal);
}

// No endpoint, so not a health check endpoint
return false;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,7 @@ 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.InvalidUserInput(nameof(InfrastructureException), infrastructureException.Code, infrastructureException.Message);

httpError = CreateHttpErrorForInfrastructureException(infrastructureException);

Expand All @@ -51,27 +50,25 @@ 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.InvalidUserInput(nameof(ApplicationException), applicationException.Code, applicationException.Message);

httpError = CreateHttpErrorForApplicationException(applicationException);

context.HttpContext.Response.StatusCode =
(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.InvalidUserInput(nameof(DomainException), domainException.Code, domainException.Message);

httpError = CreateHttpErrorForDomainException(domainException);

context.HttpContext.Response.StatusCode = (int)GetStatusCodeForDomainException(domainException);

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,
Expand All @@ -83,8 +80,7 @@ public override void OnException(ExceptionContext context)

break;
default:
_logger.LogError(context.Exception,
"Unexpected Error while processing request to '{uri}'", context.HttpContext.Request.GetDisplayUrl());
_logger.ErrorWhileProcessingRequestToUri(context.HttpContext.Request.GetDisplayUrl());

httpError = CreateHttpErrorForUnexpectedException(context);

Expand Down Expand Up @@ -150,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
{
Expand Down Expand Up @@ -209,7 +205,7 @@ private HttpError CreateHttpErrorForUnexpectedException(ExceptionContext context
return httpError;
}

private IEnumerable<string> GetFormattedStackTrace(Exception exception)
private static IEnumerable<string> GetFormattedStackTrace(Exception exception)
{
if (exception.StackTrace == null)
return Enumerable.Empty<string>();
Expand All @@ -218,3 +214,27 @@ private IEnumerable<string> GetFormattedStackTrace(Exception exception)
Regex.Matches(exception.StackTrace, "at .+").Select(m => m.Value.Trim());
}
}

internal static partial class ExceptionFilterLogs
{
[LoggerMessage(
EventId = 799306,
EventName = "ExceptionFilter.InvalidUserInput",
Level = LogLevel.Information,
Message = "An '{exception}' occurred. Error Code: '{code}'. Error message: '{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 = "'{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, string uri);
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Diagnostics;
using Enmeshed.BuildingBlocks.Infrastructure.Exceptions;
using MediatR;
using Microsoft.Extensions.Logging;

Expand Down Expand Up @@ -36,8 +37,18 @@ private void After()
{
_watch!.Stop();

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.HandledMediatorRequest(
_watch.ElapsedMilliseconds > 1000 ? LogLevel.Warning : LogLevel.Information,
typeof(TRequest).Name, _watch.ElapsedMilliseconds);
}
}

internal static partial class LoggingBehaviorLogs
{
[LoggerMessage(
EventId = 724322,
EventName = "LoggingBehavior.HandledRequest",
Message = "Handled '{requestName}' ('{timeElapsed}' ms).")]
public static partial void HandledMediatorRequest(this ILogger logger, LogLevel level, string requestName, long timeElapsed);

}
Original file line number Diff line number Diff line change
@@ -1,33 +1,33 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<RootNamespace>Enmeshed.$(MSBuildProjectName.Replace(" ", "_"))</RootNamespace>
</PropertyGroup>
<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<RootNamespace>Enmeshed.$(MSBuildProjectName.Replace(" ", "_"))</RootNamespace>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Autofac" Version="7.1.0" />
<PackageReference Include="Azure.Messaging.ServiceBus" Version="7.16.2" />
<PackageReference Include="Azure.Storage.Blobs" Version="12.18.0" />
<PackageReference Include="Google.Cloud.PubSub.V1" Version="3.7.0" />
<PackageReference Include="Google.Cloud.Storage.V1" Version="4.6.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.12" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.12" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Identity.Core" Version="7.0.12" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
<!-- CAUTION: Do not upgrade 'Npgsql.EntityFrameworkCore.PostgreSQL' to 7.0.11, because there is an error regarding __EFMigrationHistory tables introduces with the fix of the following GitHub issue: https://github.com/npgsql/efcore.pg/issues/2787 -->
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="[7.0.4]" />
<PackageReference Include="Polly" Version="8.0.0" />
<PackageReference Include="RabbitMQ.Client" Version="6.6.0" />
<PackageReference Include="System.Interactive.Async" Version="6.0.1" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Autofac" Version="7.1.0" />
<PackageReference Include="Azure.Messaging.ServiceBus" Version="7.16.2" />
<PackageReference Include="Azure.Storage.Blobs" Version="12.18.0" />
<PackageReference Include="Google.Cloud.PubSub.V1" Version="3.7.0" />
<PackageReference Include="Google.Cloud.Storage.V1" Version="4.6.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.12" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.12" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Identity.Core" Version="7.0.12" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
<!-- CAUTION: Do not upgrade 'Npgsql.EntityFrameworkCore.PostgreSQL' to 7.0.11, because there is an error regarding __EFMigrationHistory tables introduces with the fix of the following GitHub issue: https://github.com/npgsql/efcore.pg/issues/2787 -->
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="[7.0.4]" />
<PackageReference Include="Polly" Version="8.0.0" />
<PackageReference Include="RabbitMQ.Client" Version="6.6.0" />
<PackageReference Include="System.Interactive.Async" Version="6.0.1" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\BuildingBlocks.Application.Abstractions\BuildingBlocks.Application.Abstractions.csproj" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\BuildingBlocks.Application.Abstractions\BuildingBlocks.Application.Abstractions.csproj" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -65,12 +65,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<T, TH>()
Expand All @@ -83,7 +83,7 @@ public void Subscribe<T, TH>()
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
Expand All @@ -92,7 +92,7 @@ public void Subscribe<T, TH>()
Name = eventName
}).GetAwaiter().GetResult();

_logger.LogTrace("Successfully created subscription on Service Bus.");
_logger.LogInformation("Successfully created subscription on Service Bus.");
}
catch (ServiceBusException)
{
Expand Down Expand Up @@ -121,8 +121,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;
Expand All @@ -134,16 +133,18 @@ 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(context, ex);

return Task.CompletedTask;
}

private async Task<bool> ProcessEvent(string eventName, string message)
{
if (!_subscriptionManager.HasSubscriptionsForEvent(eventName))
{
_logger.NoSubscriptionForEvent(eventName);
return false;
}

await using var scope = _autofac.BeginLifetimeScope(AUTOFAC_SCOPE_NAME);

Expand All @@ -163,24 +164,62 @@ private async Task<bool> 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));

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);
return false;
}
}

return true;
}
}

internal static partial class EventBusAzureServiceBusLogs
{
[LoggerMessage(
EventId = 302940,
EventName = "EventBusAzureServiceBus.SendingIntegrationEvent",
Level = LogLevel.Debug,
Message = "Sending integration event with id '{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(this ILogger logger, string messageId);

[LoggerMessage(
EventId = 949322,
EventName = "EventBusAzureServiceBus.ErrorHandlingMessage",
Level = LogLevel.Error,
Message = "Error handling message with context {exceptionContext}.")]
public static partial void ErrorHandlingMessage(this ILogger logger, ServiceBusErrorSource exceptionContext, Exception exception);

[LoggerMessage(
EventId = 341537,
EventName = "EventBusAzureServiceBus.NoSubscriptionForEvent",
Level = LogLevel.Warning,
Message = "No subscription for event: '{eventName}'.")]
public static partial void NoSubscriptionForEvent(this ILogger logger, string eventName);

[LoggerMessage(
EventId = 726744,
EventName = "EventBusAzureServiceBus.ErrorWhileExecutingEventHandlerCausingRetry",
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",
Level = LogLevel.Error,
Message = "An error occurred while processing the integration event with id '{integrationEventId}'.")]
public static partial void ErrorWhileProcessingIntegrationEvent(this ILogger logger, string integrationEventId);
}
Loading

0 comments on commit 54f73f7

Please sign in to comment.