Skip to content

Commit 030a86d

Browse files
authored
perf: use logging methods and pass cancellation token (#395)
1 parent 64371fe commit 030a86d

8 files changed

Lines changed: 64 additions & 67 deletions

File tree

src/Cnblogs.Architecture.Ddd.Cqrs.Abstractions/InvalidCacheRequestHandler.cs

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ namespace Cnblogs.Architecture.Ddd.Cqrs.Abstractions;
77
/// <summary>
88
/// The default handler for <see cref="InvalidCacheRequest"/>.
99
/// </summary>
10-
public class InvalidCacheRequestHandler : IRequestHandler<InvalidCacheRequest>
10+
public partial class InvalidCacheRequestHandler : IRequestHandler<InvalidCacheRequest>
1111
{
1212
private readonly ICacheProvider _cacheProvider;
1313
private readonly ILogger<InvalidCacheRequestHandler> _logger;
@@ -41,15 +41,14 @@ public async Task Handle(InvalidCacheRequest request, CancellationToken cancella
4141
}
4242
catch (Exception e)
4343
{
44-
_logger.LogError(
45-
"----- Invalid Cache Failed, Type: {TypeName}, Request: {RequestBody}, Message: {Message}",
46-
request.GetType().Name,
47-
request,
48-
e.Message);
44+
LogInvalidCacheFailed(request.GetType().Name, request, e.Message);
4945
if (request.ThrowIfFailed == true)
5046
{
5147
throw;
5248
}
5349
}
5450
}
51+
52+
[LoggerMessage(LogLevel.Error, "----- Invalid Cache Failed, Type: {TypeName}, Request: {RequestBody}, Message: {Message}")]
53+
partial void LogInvalidCacheFailed(string typeName, InvalidCacheRequest requestBody, string message);
5554
}

src/Cnblogs.Architecture.Ddd.Cqrs.Abstractions/LockableRequestBehavior.cs

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
using Cnblogs.Architecture.Ddd.Infrastructure.Abstractions;
2-
32
using MediatR;
4-
53
using Microsoft.Extensions.Logging;
64

75
namespace Cnblogs.Architecture.Ddd.Cqrs.Abstractions;
@@ -11,7 +9,7 @@ namespace Cnblogs.Architecture.Ddd.Cqrs.Abstractions;
119
/// </summary>
1210
/// <typeparam name="TRequest">The type of request.</typeparam>
1311
/// <typeparam name="TResponse">The type of response.</typeparam>
14-
public class LockableRequestBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
12+
public partial class LockableRequestBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
1513
where TRequest : ILockableRequest, IRequest<TResponse>
1614
where TResponse : ILockableResponse, new()
1715
{
@@ -45,19 +43,21 @@ public async Task<TResponse> Handle(
4543
: null;
4644
var response = await _distributedLockProvider.ExecuteWithLockAsync(
4745
request.GetLockKey(),
48-
async () => await next(),
46+
async () => await next(cancellationToken),
4947
expiresIn);
5048
response.LockAcquired = true;
5149
return response;
5250
}
5351
catch (AcquireDistributionLockFailedException e)
5452
{
55-
_logger.LogError(
56-
e,
57-
"Acquire Distribution Lock Failed, Request: {@Request}, LockKey: {@LockLey}",
58-
request,
59-
e.LockKey);
53+
LogAcquireDistributionLockFailed(request, e.LockKey, e);
6054
return new TResponse { IsConcurrentError = true, LockAcquired = false };
6155
}
6256
}
63-
}
57+
58+
[LoggerMessage(LogLevel.Error, "Acquire Distribution Lock Failed, Request: {@request}, LockKey: {@lockLey}")]
59+
partial void LogAcquireDistributionLockFailed(
60+
TRequest request,
61+
string lockLey,
62+
AcquireDistributionLockFailedException acquireDistributionLockFailedException);
63+
}

src/Cnblogs.Architecture.Ddd.Cqrs.Abstractions/LoggingBehavior.cs

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ namespace Cnblogs.Architecture.Ddd.Cqrs.Abstractions;
99
/// </summary>
1010
/// <typeparam name="TRequest">The type of request.</typeparam>
1111
/// <typeparam name="TResponse">The type of response.</typeparam>
12-
public class LoggingBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
12+
public partial class LoggingBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
1313
where TRequest : IRequest<TResponse>
1414
{
1515
private readonly ILogger<LoggingBehavior<TRequest, TResponse>> _logger;
@@ -29,9 +29,15 @@ public async Task<TResponse> Handle(
2929
RequestHandlerDelegate<TResponse> next,
3030
CancellationToken cancellationToken)
3131
{
32-
_logger.LogDebug("Handling {@Request}", request);
33-
var result = await next();
34-
_logger.LogDebug("Handled {@Request}", request);
32+
LogHandlingRequest(request);
33+
var result = await next(cancellationToken);
34+
LogHandledRequest(request);
3535
return result;
3636
}
37+
38+
[LoggerMessage(LogLevel.Debug, "Handling {request}")]
39+
partial void LogHandlingRequest(TRequest request);
40+
41+
[LoggerMessage(LogLevel.Debug, "Handled {Request}")]
42+
partial void LogHandledRequest(TRequest request);
3743
}

src/Cnblogs.Architecture.Ddd.Cqrs.Abstractions/ValidationBehavior.cs

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ namespace Cnblogs.Architecture.Ddd.Cqrs.Abstractions;
99
/// </summary>
1010
/// <typeparam name="TRequest">The type of request.</typeparam>
1111
/// <typeparam name="TResponse">The type of response.</typeparam>
12-
public class ValidationBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
12+
public partial class ValidationBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
1313
where TRequest : IValidatable, IRequest<TResponse>
1414
where TResponse : IValidationResponse, new()
1515
{
@@ -30,19 +30,15 @@ public async Task<TResponse> Handle(
3030
RequestHandlerDelegate<TResponse> next,
3131
CancellationToken cancellationToken)
3232
{
33-
_logger.LogInformation("----- Validating request {RequestType}", request.GetType().Name);
33+
LogValidating(request.GetType().Name);
3434
var errors = new ValidationErrors();
3535
request.Validate(errors);
3636
if (errors.Count == 0)
3737
{
38-
return await next();
38+
return await next(cancellationToken);
3939
}
4040

41-
_logger.LogWarning(
42-
"----- Validation failed with error, type: {RequestType}, Request: {Request}, Message: {Message}",
43-
request.GetType().Name,
44-
request,
45-
errors.First().Message);
41+
LogValidationFailedWithError(request.GetType().Name, request, errors.First().Message);
4642

4743
return new TResponse
4844
{
@@ -51,4 +47,10 @@ public async Task<TResponse> Handle(
5147
ValidationErrors = errors
5248
};
5349
}
54-
}
50+
51+
[LoggerMessage(LogLevel.Information, "----- Validating request {RequestType}")]
52+
partial void LogValidating(string requestType);
53+
54+
[LoggerMessage(LogLevel.Warning, "----- Validation failed with error, type: {RequestType}, Request: {Request}, Message: {Message}")]
55+
partial void LogValidationFailedWithError(string requestType, TRequest request, string message);
56+
}

src/Cnblogs.Architecture.Ddd.EventBus.Abstractions/DefaultEventBus.cs

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ namespace Cnblogs.Architecture.Ddd.EventBus.Abstractions;
66
/// <summary>
77
/// Default implementation for <see cref="IEventBus"/>
88
/// </summary>
9-
public class DefaultEventBus : IEventBus
9+
public partial class DefaultEventBus : IEventBus
1010
{
1111
private readonly IEventBuffer _eventBuffer;
1212
private readonly IMediator _mediator;
@@ -59,7 +59,7 @@ public async Task<bool> TryPublishAsync<TEvent>(string eventName, TEvent @event)
5959
}
6060
catch (Exception e)
6161
{
62-
_logger.LogError(e, "Publish IntegrationEvent({Name}) failed, {Event}", eventName, @event);
62+
LogPublishIntegrationEvent(eventName, @event, e);
6363
return false;
6464
}
6565
}
@@ -69,15 +69,17 @@ public Task ReceiveAsync<TEvent>(TEvent receivedEvent)
6969
where TEvent : IntegrationEvent
7070
{
7171
var traceId = receivedEvent.TraceId ?? receivedEvent.Id;
72-
_logger.LogInformation(
73-
"Received integration event, Name: {EventName}, Event: {Event}, TraceId: {TraceId}",
74-
typeof(TEvent).Name,
75-
receivedEvent,
76-
traceId);
72+
LogReceivedIntegrationEventName(typeof(TEvent).Name, receivedEvent, traceId);
7773
TraceId = traceId;
7874
return _mediator.Publish(receivedEvent);
7975
}
8076

8177
/// <inheritdoc />
8278
public Guid? TraceId { get; set; }
79+
80+
[LoggerMessage(LogLevel.Error, "Publish IntegrationEvent({Name}) failed, {Event}")]
81+
partial void LogPublishIntegrationEvent(string name, object @event, Exception exception);
82+
83+
[LoggerMessage(LogLevel.Information, "Received integration event, Name: {EventName}, Event: {Event}, TraceId: {TraceId}")]
84+
partial void LogReceivedIntegrationEventName(string eventName, object @event, Guid traceId);
8385
}

src/Cnblogs.Architecture.Ddd.EventBus.Dapr/DaprEventBusProvider.cs

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ namespace Cnblogs.Architecture.Ddd.EventBus.Dapr;
88
/// <summary>
99
/// Implementations for <see cref="IEventBusProvider"/> using Dapr.
1010
/// </summary>
11-
public class DaprEventBusProvider : IEventBusProvider
11+
public partial class DaprEventBusProvider : IEventBusProvider
1212
{
1313
private readonly DaprClient _daprClient;
1414
private readonly DaprOptions _daprOptions;
@@ -33,17 +33,14 @@ public DaprEventBusProvider(
3333
/// <inheritdoc />
3434
public async Task PublishAsync(string eventName, IntegrationEvent @event)
3535
{
36-
_logger.LogInformation(
37-
"Publishing IntegrationEvent, PubSub: {PubSubName}, TopicName: {TopicName}, Name: {EventName}, Body: {Event}, TraceId: {TraceId}",
38-
DaprOptions.PubSubName,
39-
DaprUtils.GetDaprTopicName(_daprOptions.AppName, eventName),
40-
eventName,
41-
@event,
42-
@event.TraceId ?? @event.Id);
36+
LogPublishingIntegrationEvent(DaprOptions.PubSubName, DaprUtils.GetDaprTopicName(_daprOptions.AppName, eventName), eventName, @event, @event.TraceId ?? @event.Id);
4337
object data = @event; // do not provide type information to serializer since it's base class.
4438
await _daprClient.PublishEventAsync(
4539
DaprOptions.PubSubName,
4640
DaprUtils.GetDaprTopicName(_daprOptions.AppName, eventName),
4741
data);
4842
}
43+
44+
[LoggerMessage(LogLevel.Information, "Publishing IntegrationEvent, PubSub: {PubSubName}, TopicName: {TopicName}, Name: {EventName}, Body: {Event}, TraceId: {TraceId}")]
45+
partial void LogPublishingIntegrationEvent(string pubSubName, string topicName, string eventName, IntegrationEvent @event, Guid traceId);
4946
}

test/Cnblogs.Architecture.IntegrationTestProject/EventHandlers/TestIntegrationEventHandler.cs

Lines changed: 10 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -4,27 +4,24 @@
44

55
namespace Cnblogs.Architecture.IntegrationTestProject.EventHandlers;
66

7-
public class TestIntegrationEventHandler : IIntegrationEventHandler<TestIntegrationEvent>,
8-
IIntegrationEventHandler<BlogPostCreatedIntegrationEvent>
7+
public partial class TestIntegrationEventHandler(ILogger<TestIntegrationEventHandler> logger)
8+
: IIntegrationEventHandler<TestIntegrationEvent>,
9+
IIntegrationEventHandler<BlogPostCreatedIntegrationEvent>
910
{
10-
private readonly ILogger _logger;
11-
12-
public TestIntegrationEventHandler(ILogger<TestIntegrationEventHandler> logger)
13-
{
14-
_logger = logger;
15-
}
11+
private readonly ILogger _logger = logger;
1612

1713
public Task Handle(TestIntegrationEvent notification, CancellationToken cancellationToken)
1814
{
19-
_logger.LogInformation(LogTemplates.HandledIntegratonEvent, notification);
20-
15+
LogHandledIntegrationEventEvent(notification);
2116
return Task.CompletedTask;
2217
}
2318

2419
public Task Handle(BlogPostCreatedIntegrationEvent notification, CancellationToken cancellationToken)
2520
{
26-
_logger.LogInformation(LogTemplates.HandledIntegratonEvent, notification);
27-
21+
LogHandledIntegrationEventEvent(notification);
2822
return Task.CompletedTask;
2923
}
30-
}
24+
25+
[LoggerMessage(LogLevel.Information, LogTemplates.HandledIntegratonEvent)]
26+
partial void LogHandledIntegrationEventEvent(object @event);
27+
}

test/Cnblogs.Architecture.UnitTests/Cqrs/Behaviors/LoggerBehaviorTests.cs

Lines changed: 4 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -29,27 +29,21 @@ public async Task LoggerBehavior_ShouldLogDebugAsync()
2929
Arg.Any<Func<object, Exception?, string>>());
3030
}
3131

32-
private class TestLogger<T> : ILogger<T>
32+
private class TestLogger<T>(ILogger<T> logger) : ILogger<T>
3333
{
34-
private readonly ILogger<T> _logger;
35-
3634
// ReSharper disable once ContextualLoggerProblem
37-
public TestLogger(ILogger<T> logger)
38-
{
39-
_logger = logger;
40-
}
4135

4236
/// <inheritdoc />
4337
public IDisposable? BeginScope<TState>(TState state)
4438
where TState : notnull
4539
{
46-
return _logger.BeginScope(state);
40+
return logger.BeginScope(state);
4741
}
4842

4943
/// <inheritdoc />
5044
public virtual bool IsEnabled(LogLevel logLevel)
5145
{
52-
return _logger.IsEnabled(logLevel);
46+
return true;
5347
}
5448

5549
/// <inheritdoc />
@@ -60,7 +54,7 @@ public virtual void Log<TState>(
6054
Exception? exception,
6155
Func<TState, Exception?, string> formatter)
6256
{
63-
_logger.Log<object>(logLevel, eventId, state!, exception, (_, _) => string.Empty);
57+
logger.Log<object>(logLevel, eventId, state!, exception, (_, _) => string.Empty);
6458
}
6559
}
6660
}

0 commit comments

Comments
 (0)