Skip to content

Commit ca4e137

Browse files
committed
#101 Updated logging to avoid CA1848
1 parent 51542cb commit ca4e137

File tree

10 files changed

+56
-15
lines changed

10 files changed

+56
-15
lines changed

src/VerticalSliceArchitectureTemplate/Common/Behaviours/LoggingBehaviour.cs

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,18 @@
33

44
namespace VerticalSliceArchitectureTemplate.Common.Behaviours;
55

6+
public static class RequestInformationLogger
7+
{
8+
private static readonly Action<ILogger, string, object, object, Exception?> LogAction =
9+
LoggerMessage.Define<string, object, object>(
10+
LogLevel.Information,
11+
new EventId(2, nameof(RequestInformationLogger)),
12+
"CleanArchitecture Request: {Name} {@UserId} {@Request}");
13+
14+
public static void Log(ILogger logger, string name, object userId, object request) =>
15+
LogAction(logger, name, userId, request, null);
16+
}
17+
618
public class LoggingBehaviour<TRequest>(ILogger<TRequest> logger, CurrentUserService currentUserService)
719
: IRequestPreProcessor<TRequest>
820
where TRequest : notnull
@@ -12,8 +24,7 @@ public Task Process(TRequest request, CancellationToken cancellationToken)
1224
var requestName = typeof(TRequest).Name;
1325
var userId = currentUserService.UserId ?? string.Empty;
1426

15-
logger.LogInformation("CleanArchitecture Request: {Name} {@UserId} {@Request}",
16-
requestName, userId, request);
27+
RequestInformationLogger.Log(logger, requestName, userId, request);
1728

1829
return Task.CompletedTask;
1930
}

src/VerticalSliceArchitectureTemplate/Common/Behaviours/PerformanceBehaviour.cs

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,18 @@
44

55
namespace VerticalSliceArchitectureTemplate.Common.Behaviours;
66

7+
public static class LongRunningRequestLog
8+
{
9+
private static readonly Action<ILogger, string, long, string, object, Exception?> LogAction =
10+
LoggerMessage.Define<string, long, string, object>(
11+
LogLevel.Warning,
12+
new EventId(3, nameof(LongRunningRequestLog)),
13+
"VerticalSliceArchitecture Long Running Request: {Name} ({ElapsedMilliseconds} milliseconds) {@UserId} {@Request}");
14+
15+
public static void Log(ILogger logger, string name, long elapsedMilliseconds, string userId, object request) =>
16+
LogAction(logger, name, elapsedMilliseconds, userId, request, null);
17+
}
18+
719
public class PerformanceBehaviour<TRequest, TResponse>(
820
ILogger<TRequest> logger,
921
CurrentUserService currentUserService)
@@ -28,9 +40,7 @@ public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TRe
2840
var requestName = typeof(TRequest).Name;
2941
var userId = currentUserService.UserId ?? string.Empty;
3042

31-
logger.LogWarning(
32-
"CleanArchitecture Long Running Request: {Name} ({ElapsedMilliseconds} milliseconds) {@UserId} {@Request}",
33-
requestName, elapsedMilliseconds, userId, request);
43+
LongRunningRequestLog.Log(logger, requestName, elapsedMilliseconds, userId, request);
3444
}
3545

3646
return response;

src/VerticalSliceArchitectureTemplate/Common/Behaviours/UnhandledExceptionBehaviour.cs

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,18 @@
22

33
namespace VerticalSliceArchitectureTemplate.Common.Behaviours;
44

5+
public static class UnhandledExceptionBehaviourLogger
6+
{
7+
private static readonly Action<ILogger, string, object, Exception> LogAction =
8+
LoggerMessage.Define<string, object>(
9+
LogLevel.Error,
10+
new EventId(1, nameof(UnhandledExceptionBehaviourLogger)),
11+
"VerticalSliceArchitecture Request: Unhandled Exception for Request {Name} {@Request}");
12+
13+
public static void Log(ILogger logger, string name, object request, Exception exception) =>
14+
LogAction(logger, name, request, exception);
15+
}
16+
517
public class UnhandledExceptionBehaviour<TRequest, TResponse>(ILogger<TRequest> logger)
618
: IPipelineBehavior<TRequest, TResponse>
719
where TRequest : notnull
@@ -17,8 +29,7 @@ public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TRe
1729
{
1830
var requestName = typeof(TRequest).Name;
1931

20-
logger.LogError(ex, "CleanArchitecture Request: Unhandled Exception for Request {Name} {@Request}",
21-
requestName, request);
32+
UnhandledExceptionBehaviourLogger.Log(logger, requestName, request, ex);
2233

2334
throw;
2435
}

src/VerticalSliceArchitectureTemplate/Common/Domain/BaseEntity.cs

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,5 +4,10 @@ namespace VerticalSliceArchitectureTemplate.Common.Domain;
44

55
public abstract class BaseEntity
66
{
7-
public readonly List<INotification> StagedEvents = [];
7+
private readonly List<INotification> _stagedEvents = [];
8+
9+
public IReadOnlyList<INotification> StagedEvents => _stagedEvents;
10+
11+
protected void AddEvent(INotification notification) => _stagedEvents.Add(notification);
12+
public void ClearEvents() => _stagedEvents.Clear();
813
}

src/VerticalSliceArchitectureTemplate/Common/Persistence/EventPublisher.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ private async Task DispatchDomainEvents(DbContext? context)
3535
.SelectMany(e => e.StagedEvents)
3636
.ToList();
3737

38-
entities.ForEach(e => e.StagedEvents.Clear());
38+
entities.ForEach(e => e.ClearEvents());
3939

4040
foreach (var domainEvent in domainEvents)
4141
await mediator.Publish(domainEvent);

src/VerticalSliceArchitectureTemplate/Features/Todos/Domain/Todo.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ public class Todo : BaseEntity
88
{
99
public Todo()
1010
{
11-
StagedEvents.Add(new TodoCreatedEvent(Id));
11+
AddEvent(new TodoCreatedEvent(Id));
1212
}
1313

1414
public Guid Id { get; init; }
@@ -27,6 +27,6 @@ public void Complete()
2727

2828
IsCompleted = true;
2929

30-
StagedEvents.Add(new TodoCompletedEvent(Id));
30+
AddEvent(new TodoCompletedEvent(Id));
3131
}
3232
}

src/VerticalSliceArchitectureTemplate/Host/EndpointDiscovery.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ private static IEnumerable<Type> GetEndpointTypes(params Assembly[] assemblies)
3030
x is { IsInterface: false, IsAbstract: false });
3131
}
3232

33-
private static MethodInfo? GetMapEndpointsMethod(IReflect type)
33+
private static MethodInfo? GetMapEndpointsMethod(Type type)
3434
{
3535
return type.GetMethod(nameof(IEndpoints.MapEndpoints),
3636
BindingFlags.Static | BindingFlags.Public);

src/VerticalSliceArchitectureTemplate/Host/ExceptionHandler.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,8 @@ public static void UseProductionExceptionHandler(this WebApplication app)
1919

2020
public sealed class KnownExceptionsHandler : IExceptionHandler
2121
{
22-
private static readonly IDictionary<Type, Func<HttpContext, Exception, IResult>> ExceptionHandlers =
23-
new Dictionary<Type, Func<HttpContext, Exception, IResult>>
22+
private static readonly Dictionary<Type, Func<HttpContext, Exception, IResult>> ExceptionHandlers =
23+
new()
2424
{
2525
{ typeof(ValidationException), HandleValidationException },
2626
{ typeof(InvalidOperationException), HandleInvalidOperationException },

src/VerticalSliceArchitectureTemplate/VerticalSliceArchitectureTemplate.csproj

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,4 +15,8 @@
1515
<PackageReference Include="ErrorOr" />
1616
</ItemGroup>
1717

18+
<ItemGroup>
19+
<Folder Include="Common\Logging\" />
20+
</ItemGroup>
21+
1822
</Project>

tests/VerticalSliceArchitecture.ArchTests/TestBase.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ public abstract class TestBase
77
{
88
private static readonly Types ProgramTypes = Types.InAssembly(typeof(Program).Assembly);
99

10-
protected PredicateList TypesMatchingAnyPattern(params string[] patterns)
10+
protected static PredicateList TypesMatchingAnyPattern(params string[] patterns)
1111
{
1212
var output = ProgramTypes.That();
1313

0 commit comments

Comments
 (0)