Skip to content

Commit 423066a

Browse files
committed
Add log traces for integration event handling
1 parent b9839d1 commit 423066a

13 files changed

Lines changed: 90 additions & 43 deletions

File tree

src/Services/Basket/Basket.API/Controllers/BasketController.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -82,13 +82,13 @@ public async Task<ActionResult> CheckoutAsync([FromBody]BasketCheckout basketChe
8282
{
8383
try
8484
{
85-
_logger.LogInformation("----- BasketController - Publishing integration event: {IntegrationEventId} ({@IntegrationEvent})", eventMessage.Id, eventMessage);
85+
_logger.LogInformation("----- Publishing integration event: {IntegrationEventId} at {AppShortName} - ({@IntegrationEvent})", eventMessage.Id, Program.AppShortName, eventMessage);
8686

8787
_eventBus.Publish(eventMessage);
8888
}
8989
catch (Exception ex)
9090
{
91-
_logger.LogError(ex, "----- BasketController - ERROR Publishing integration event");
91+
_logger.LogError(ex, "----- ERROR Publishing integration event: {IntegrationEventId} at {AppShortName} - ({@IntegrationEvent})", eventMessage.Id, Program.AppShortName, eventMessage);
9292

9393
throw;
9494
}

src/Services/Basket/Basket.API/IntegrationEvents/EventHandling/ProductPriceChangedIntegrationEventHandler.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ public async Task Handle(ProductPriceChangedIntegrationEvent @event)
2626
{
2727
using (LogContext.PushProperty("IntegrationEventId", @event.Id))
2828
{
29-
_logger.LogInformation("----- ProductPriceChangedIntegrationEventHandler - Handling integration event: {IntegrationEventId} ({@IntegrationEvent})", @event.Id, @event);
29+
_logger.LogInformation("----- Handling integration event: {IntegrationEventId} at {AppShortName} - ({@IntegrationEvent})", @event.Id, Program.AppShortName, @event);
3030

3131
var userIds = _repository.GetUsers();
3232

src/Services/Basket/Basket.API/Program.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API
1313
public class Program
1414
{
1515
public static readonly string AppName = typeof(Program).Namespace;
16-
public static readonly string ShortAppName = AppName.Substring(AppName.LastIndexOf('.', AppName.LastIndexOf('.') - 1) + 1);
16+
public static readonly string AppShortName = AppName.Substring(AppName.LastIndexOf('.', AppName.LastIndexOf('.') - 1) + 1);
1717

1818
public static int Main(string[] args)
1919
{

src/Services/Catalog/Catalog.API/IntegrationEvents/CatalogIntegrationEventService.cs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Events;
55
using Microsoft.eShopOnContainers.BuildingBlocks.IntegrationEventLogEF.Services;
66
using Microsoft.eShopOnContainers.BuildingBlocks.IntegrationEventLogEF.Utilities;
7+
using Microsoft.eShopOnContainers.Services.Catalog.API;
78
using Microsoft.eShopOnContainers.Services.Catalog.API.Infrastructure;
89
using Microsoft.Extensions.Logging;
910
using Serilog.Context;
@@ -40,15 +41,15 @@ public async Task PublishThroughEventBusAsync(IntegrationEvent evt)
4041
{
4142
try
4243
{
43-
_logger.LogInformation("----- CatalogIntegrationEventService - Publishing integration event: {IntegrationEventId} ({@IntegrationEvent})", evt.Id, evt);
44+
_logger.LogInformation("----- Publishing integration event: {IntegrationEventId} at {AppShortName} - ({@IntegrationEvent})", evt.Id, Program.AppShortName, evt);
4445

4546
await _eventLogService.MarkEventAsInProgressAsync(evt.Id);
4647
_eventBus.Publish(evt);
4748
await _eventLogService.MarkEventAsPublishedAsync(evt.Id);
4849
}
4950
catch (Exception ex)
5051
{
51-
_logger.LogError(ex, "----- CatalogIntegrationEventService - ERROR Publishing integration event");
52+
_logger.LogError(ex, "----- ERROR Publishing integration event: {IntegrationEventId} at {AppShortName} - ({@IntegrationEvent})", evt.Id, Program.AppShortName, evt);
5253
await _eventLogService.MarkEventAsFailedAsync(evt.Id);
5354
}
5455
}

src/Services/Catalog/Catalog.API/Program.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ namespace Microsoft.eShopOnContainers.Services.Catalog.API
1515
public class Program
1616
{
1717
public static readonly string AppName = typeof(Program).Namespace;
18-
public static readonly string ShortAppName = AppName.Substring(AppName.LastIndexOf('.', AppName.LastIndexOf('.') - 1) + 1);
18+
public static readonly string AppShortName = AppName.Substring(AppName.LastIndexOf('.', AppName.LastIndexOf('.') - 1) + 1);
1919

2020
public static int Main(string[] args)
2121
{
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Linq;
4+
using System.Threading.Tasks;
5+
6+
namespace Ordering.API.Application.Behaviors
7+
{
8+
internal static class BehaviorsHelperExtensions
9+
{
10+
internal static string GetTypeName(this object @object)
11+
{
12+
var typeName = string.Empty;
13+
var type = @object.GetType();
14+
15+
if (type.IsGenericType)
16+
{
17+
var genericTypes = string.Join(",", type.GetGenericArguments().Select(t => t.Name).ToArray());
18+
typeName = $"{type.Name.Remove(type.Name.IndexOf('`'))}<{genericTypes}>";
19+
}
20+
else
21+
{
22+
typeName = type.Name;
23+
}
24+
25+
return typeName;
26+
}
27+
28+
}
29+
}

src/Services/Ordering/Ordering.API/Application/Behaviors/LoggingBehavior.cs

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
using MediatR;
22
using Microsoft.Extensions.Logging;
3+
using System.Linq;
34
using System.Threading;
45
using System.Threading.Tasks;
56

6-
namespace Ordering.API.Infrastructure.Behaviors
7+
namespace Ordering.API.Application.Behaviors
78
{
89
public class LoggingBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
910
{
@@ -12,9 +13,10 @@ public class LoggingBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest,
1213

1314
public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
1415
{
15-
_logger.LogInformation($"Handling {typeof(TRequest).Name}");
16+
_logger.LogInformation("----- Handling command {CommandName} ({@Command})", request.GetTypeName(), request);
1617
var response = await next();
17-
_logger.LogInformation($"Handled {typeof(TResponse).Name}");
18+
_logger.LogInformation("----- Command {CommandName} handled - response: {@Response}", request.GetTypeName(), response);
19+
1820
return response;
1921
}
2022
}

src/Services/Ordering/Ordering.API/Application/Behaviors/TransactionBehaviour.cs

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,6 @@
44
using Microsoft.Extensions.Logging;
55
using Ordering.API.Application.IntegrationEvents;
66
using System;
7-
using System.Collections.Generic;
8-
using System.Linq;
97
using System.Threading;
108
using System.Threading.Tasks;
119

@@ -29,30 +27,32 @@ public TransactionBehaviour(OrderingContext dbContext,
2927
public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
3028
{
3129
TResponse response = default(TResponse);
30+
var typeName = request.GetTypeName();
3231

3332
try
3433
{
3534
var strategy = _dbContext.Database.CreateExecutionStrategy();
36-
await strategy.ExecuteAsync(async () =>
35+
36+
await strategy.ExecuteAsync(async () =>
3737
{
38-
_logger.LogInformation($"Begin transaction {typeof(TRequest).Name}");
38+
_logger.LogInformation("----- Begin transaction for {CommandName} ({@Command})", typeName, request);
3939

4040
await _dbContext.BeginTransactionAsync();
4141

4242
response = await next();
4343

4444
await _dbContext.CommitTransactionAsync();
4545

46-
_logger.LogInformation($"Committed transaction {typeof(TRequest).Name}");
46+
_logger.LogInformation("----- Transaction commited for {CommandName}", typeName);
4747

4848
await _orderingIntegrationEventService.PublishEventsThroughEventBusAsync();
4949
});
5050

5151
return response;
5252
}
53-
catch (Exception)
53+
catch (Exception ex)
5454
{
55-
_logger.LogInformation($"Rollback transaction executed {typeof(TRequest).Name}");
55+
_logger.LogError(ex, "----- ERROR Handling transaction for {CommandName} ({@Command})", typeName, request);
5656

5757
_dbContext.RollbackTransaction();
5858
throw;
Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,30 @@
11
using FluentValidation;
22
using MediatR;
3+
using Microsoft.Extensions.Logging;
34
using Ordering.Domain.Exceptions;
4-
using System;
55
using System.Linq;
66
using System.Threading;
77
using System.Threading.Tasks;
88

9-
namespace Ordering.API.Infrastructure.Behaviors
9+
namespace Ordering.API.Application.Behaviors
1010
{
1111
public class ValidatorBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
1212
{
13+
private readonly ILogger<ValidatorBehavior<TRequest, TResponse>> _logger;
1314
private readonly IValidator<TRequest>[] _validators;
14-
public ValidatorBehavior(IValidator<TRequest>[] validators) => _validators = validators;
15+
16+
public ValidatorBehavior(IValidator<TRequest>[] validators, ILogger<ValidatorBehavior<TRequest, TResponse>> logger)
17+
{
18+
_validators = validators;
19+
_logger = logger;
20+
}
1521

1622
public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
1723
{
24+
var typeName = request.GetTypeName();
25+
26+
_logger.LogInformation("----- Validating command {CommandType}", typeName);
27+
1828
var failures = _validators
1929
.Select(v => v.Validate(request))
2030
.SelectMany(result => result.Errors)
@@ -23,12 +33,13 @@ public async Task<TResponse> Handle(TRequest request, CancellationToken cancella
2333

2434
if (failures.Any())
2535
{
36+
_logger.LogWarning("----- Validation errors - {CommandType} - Command: {@Command} - Errors: {@ValidationErrors}", typeName, request, failures);
37+
2638
throw new OrderingDomainException(
2739
$"Command Validation Errors for type {typeof(TRequest).Name}", new ValidationException("Validation exception", failures));
2840
}
2941

30-
var response = await next();
31-
return response;
42+
return await next();
3243
}
3344
}
34-
}
45+
}

src/Services/Ordering/Ordering.API/Application/IntegrationEvents/EventHandling/UserCheckoutAcceptedIntegrationEventHandler.cs

Lines changed: 21 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
using Microsoft.Extensions.Logging;
77
using Ordering.API.Application.IntegrationEvents.Events;
88
using Serilog.Context;
9+
using Microsoft.eShopOnContainers.Services.Ordering.API;
910

1011
namespace Ordering.API.Application.IntegrationEvents.EventHandling
1112
{
@@ -35,34 +36,38 @@ public async Task Handle(UserCheckoutAcceptedIntegrationEvent eventMsg)
3536
{
3637
using (LogContext.PushProperty("IntegrationEventId", eventMsg.Id))
3738
{
38-
_logger.LogInformation("----- UserCheckoutAcceptedIntegrationEventHandler - Handling integration event: {IntegrationEventId} ({@IntegrationEvent})", eventMsg.Id, eventMsg);
39+
_logger.LogInformation("----- Handling integration event: {IntegrationEventId} at {AppShortName} - ({@IntegrationEvent})", eventMsg.Id, Program.AppShortName, eventMsg);
3940

4041
var result = false;
4142

4243
if (eventMsg.RequestId != Guid.Empty)
4344
{
44-
var createOrderCommand = new CreateOrderCommand(eventMsg.Basket.Items, eventMsg.UserId, eventMsg.UserName, eventMsg.City, eventMsg.Street,
45-
eventMsg.State, eventMsg.Country, eventMsg.ZipCode,
46-
eventMsg.CardNumber, eventMsg.CardHolderName, eventMsg.CardExpiration,
47-
eventMsg.CardSecurityNumber, eventMsg.CardTypeId);
45+
using (LogContext.PushProperty("IdentifiedCommandId", eventMsg.RequestId))
46+
{
47+
var createOrderCommand = new CreateOrderCommand(eventMsg.Basket.Items, eventMsg.UserId, eventMsg.UserName, eventMsg.City, eventMsg.Street,
48+
eventMsg.State, eventMsg.Country, eventMsg.ZipCode,
49+
eventMsg.CardNumber, eventMsg.CardHolderName, eventMsg.CardExpiration,
50+
eventMsg.CardSecurityNumber, eventMsg.CardTypeId);
4851

49-
_logger.LogInformation("----- UserCheckoutAcceptedIntegrationEventHandler - CreateOrderCommand: {@CreateOrderCommand}", createOrderCommand);
52+
var requestCreateOrder = new IdentifiedCommand<CreateOrderCommand, bool>(createOrderCommand, eventMsg.RequestId);
5053

51-
var requestCreateOrder = new IdentifiedCommand<CreateOrderCommand, bool>(createOrderCommand, eventMsg.RequestId);
52-
result = await _mediator.Send(requestCreateOrder);
54+
_logger.LogInformation("----- IdentifiedCreateOrderCommand: {@IdentifiedCreateOrderCommand}", requestCreateOrder);
5355

54-
if (result)
55-
{
56-
_logger.LogInformation("----- UserCheckoutAcceptedIntegrationEventHandler - CreateOrderCommand suceeded - RequestId: {RequestId}", eventMsg.RequestId);
57-
}
58-
else
59-
{
60-
_logger.LogWarning("----- UserCheckoutAcceptedIntegrationEventHandler - CreateOrderCommand failed - RequestId: {RequestId}", eventMsg.RequestId);
56+
result = await _mediator.Send(requestCreateOrder);
57+
58+
if (result)
59+
{
60+
_logger.LogInformation("----- CreateOrderCommand suceeded - RequestId: {RequestId}", eventMsg.RequestId);
61+
}
62+
else
63+
{
64+
_logger.LogWarning("----- CreateOrderCommand failed - RequestId: {RequestId}", eventMsg.RequestId);
65+
}
6166
}
6267
}
6368
else
6469
{
65-
_logger.LogWarning("----- UserCheckoutAcceptedIntegrationEventHandler - Invalid IntegrationEvent - RequestId is missing}");
70+
_logger.LogWarning("----- Invalid IntegrationEvent - RequestId is missing - {@IntegrationEvent}", eventMsg);
6671
}
6772
}
6873
}

0 commit comments

Comments
 (0)