Skip to content

Commit 122fab5

Browse files
committed
Add LogContext to IntegrationEventHandlers
1 parent 6ccd7b6 commit 122fab5

27 files changed

Lines changed: 337 additions & 161 deletions

File tree

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

Lines changed: 13 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,8 @@ public class BasketController : ControllerBase
2525

2626
public BasketController(
2727
ILogger<BasketController> logger,
28-
IBasketRepository repository,
29-
IIdentityService identityService,
28+
IBasketRepository repository,
29+
IIdentityService identityService,
3030
IEventBus eventBus)
3131
{
3232
_logger = logger;
@@ -58,7 +58,7 @@ public async Task<ActionResult<CustomerBasket>> UpdateBasketAsync([FromBody]Cust
5858
public async Task<ActionResult> CheckoutAsync([FromBody]BasketCheckout basketCheckout, [FromHeader(Name = "x-requestid")] string requestId)
5959
{
6060
var userId = _identityService.GetUserIdentity();
61-
61+
6262
basketCheckout.RequestId = (Guid.TryParse(requestId, out Guid guid) && guid != Guid.Empty) ?
6363
guid : basketCheckout.RequestId;
6464

@@ -78,20 +78,17 @@ public async Task<ActionResult> CheckoutAsync([FromBody]BasketCheckout basketChe
7878
// Once basket is checkout, sends an integration event to
7979
// ordering.api to convert basket to order and proceeds with
8080
// order creation process
81-
using (LogContext.PushProperty("IntegrationEventId", eventMessage.Id))
81+
try
8282
{
83-
try
84-
{
85-
_logger.LogInformation("----- Publishing integration event: {IntegrationEventId} at {AppShortName} - ({@IntegrationEvent})", eventMessage.Id, Program.AppShortName, eventMessage);
86-
87-
_eventBus.Publish(eventMessage);
88-
}
89-
catch (Exception ex)
90-
{
91-
_logger.LogError(ex, "----- ERROR Publishing integration event: {IntegrationEventId} at {AppShortName} - ({@IntegrationEvent})", eventMessage.Id, Program.AppShortName, eventMessage);
92-
93-
throw;
94-
}
83+
_logger.LogInformation("----- Publishing integration event: {IntegrationEventId} at {AppShortName} - ({@IntegrationEvent})", eventMessage.Id, Program.AppShortName, eventMessage);
84+
85+
_eventBus.Publish(eventMessage);
86+
}
87+
catch (Exception ex)
88+
{
89+
_logger.LogError(ex, "----- ERROR Publishing integration event: {IntegrationEventId} at {AppShortName} - ({@IntegrationEvent})", eventMessage.Id, Program.AppShortName, eventMessage);
90+
91+
throw;
9592
}
9693

9794
return Accepted();

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

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
using Basket.API.IntegrationEvents.Events;
22
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Abstractions;
3+
using Microsoft.eShopOnContainers.Services.Basket.API;
34
using Microsoft.eShopOnContainers.Services.Basket.API.Model;
5+
using Microsoft.Extensions.Logging;
6+
using Serilog.Context;
47
using System;
58
using System.Threading.Tasks;
69

@@ -9,15 +12,24 @@ namespace Basket.API.IntegrationEvents.EventHandling
912
public class OrderStartedIntegrationEventHandler : IIntegrationEventHandler<OrderStartedIntegrationEvent>
1013
{
1114
private readonly IBasketRepository _repository;
15+
private readonly ILogger<OrderStartedIntegrationEventHandler> _logger;
1216

13-
public OrderStartedIntegrationEventHandler(IBasketRepository repository)
17+
public OrderStartedIntegrationEventHandler(
18+
IBasketRepository repository,
19+
ILogger<OrderStartedIntegrationEventHandler> logger)
1420
{
1521
_repository = repository ?? throw new ArgumentNullException(nameof(repository));
22+
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
1623
}
1724

1825
public async Task Handle(OrderStartedIntegrationEvent @event)
1926
{
20-
await _repository.DeleteBasketAsync(@event.UserId.ToString());
27+
using (LogContext.PushProperty("IntegrationEventId_Context", @event.Id))
28+
{
29+
_logger.LogInformation("----- Handling integration event: {IntegrationEventId} at {AppShortName} - ({@IntegrationEvent})", @event.Id, Program.AppShortName, @event);
30+
31+
await _repository.DeleteBasketAsync(@event.UserId.ToString());
32+
}
2133
}
2234
}
2335
}

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ public ProductPriceChangedIntegrationEventHandler(
2424

2525
public async Task Handle(ProductPriceChangedIntegrationEvent @event)
2626
{
27-
using (LogContext.PushProperty("IntegrationEventId", @event.Id))
27+
using (LogContext.PushProperty("IntegrationEventId_Context", @event.Id))
2828
{
2929
_logger.LogInformation("----- Handling integration event: {IntegrationEventId} at {AppShortName} - ({@IntegrationEvent})", @event.Id, Program.AppShortName, @event);
3030

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

Lines changed: 20 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ public class CatalogIntegrationEventService : ICatalogIntegrationEventService
2424

2525
public CatalogIntegrationEventService(
2626
ILogger<CatalogIntegrationEventService> logger,
27-
IEventBus eventBus,
27+
IEventBus eventBus,
2828
CatalogContext catalogContext,
2929
Func<DbConnection, IIntegrationEventLogService> integrationEventLogServiceFactory)
3030
{
@@ -37,39 +37,33 @@ public CatalogIntegrationEventService(
3737

3838
public async Task PublishThroughEventBusAsync(IntegrationEvent evt)
3939
{
40-
using (LogContext.PushProperty("IntegrationEventId", evt.Id))
40+
try
4141
{
42-
try
43-
{
44-
_logger.LogInformation("----- Publishing integration event: {IntegrationEventId} at {AppShortName} - ({@IntegrationEvent})", evt.Id, Program.AppShortName, evt);
42+
_logger.LogInformation("----- Publishing integration event: {IntegrationEventId_published} at {AppShortName} - ({@IntegrationEvent})", evt.Id, Program.AppShortName, evt);
4543

46-
await _eventLogService.MarkEventAsInProgressAsync(evt.Id);
47-
_eventBus.Publish(evt);
48-
await _eventLogService.MarkEventAsPublishedAsync(evt.Id);
49-
}
50-
catch (Exception ex)
51-
{
52-
_logger.LogError(ex, "----- ERROR Publishing integration event: {IntegrationEventId} at {AppShortName} - ({@IntegrationEvent})", evt.Id, Program.AppShortName, evt);
53-
await _eventLogService.MarkEventAsFailedAsync(evt.Id);
54-
}
44+
await _eventLogService.MarkEventAsInProgressAsync(evt.Id);
45+
_eventBus.Publish(evt);
46+
await _eventLogService.MarkEventAsPublishedAsync(evt.Id);
47+
}
48+
catch (Exception ex)
49+
{
50+
_logger.LogError(ex, "----- ERROR Publishing integration event: {IntegrationEventId} at {AppShortName} - ({@IntegrationEvent})", evt.Id, Program.AppShortName, evt);
51+
await _eventLogService.MarkEventAsFailedAsync(evt.Id);
5552
}
5653
}
5754

5855
public async Task SaveEventAndCatalogContextChangesAsync(IntegrationEvent evt)
5956
{
60-
using (LogContext.PushProperty("IntegrationEventId", evt.Id))
61-
{
62-
_logger.LogInformation("----- CatalogIntegrationEventService - Saving changes and integrationEvent: {IntegrationEventId}", evt.Id);
57+
_logger.LogInformation("----- CatalogIntegrationEventService - Saving changes and integrationEvent: {IntegrationEventId}", evt.Id);
6358

64-
//Use of an EF Core resiliency strategy when using multiple DbContexts within an explicit BeginTransaction():
65-
//See: https://docs.microsoft.com/en-us/ef/core/miscellaneous/connection-resiliency
66-
await ResilientTransaction.New(_catalogContext).ExecuteAsync(async () =>
67-
{
68-
// Achieving atomicity between original catalog database operation and the IntegrationEventLog thanks to a local transaction
69-
await _catalogContext.SaveChangesAsync();
70-
await _eventLogService.SaveEventAsync(evt, _catalogContext.Database.CurrentTransaction.GetDbTransaction());
71-
});
72-
}
59+
//Use of an EF Core resiliency strategy when using multiple DbContexts within an explicit BeginTransaction():
60+
//See: https://docs.microsoft.com/en-us/ef/core/miscellaneous/connection-resiliency
61+
await ResilientTransaction.New(_catalogContext).ExecuteAsync(async () =>
62+
{
63+
// Achieving atomicity between original catalog database operation and the IntegrationEventLog thanks to a local transaction
64+
await _catalogContext.SaveChangesAsync();
65+
await _eventLogService.SaveEventAsync(evt, _catalogContext.Database.CurrentTransaction.GetDbTransaction());
66+
});
7367
}
7468
}
7569
}

src/Services/Catalog/Catalog.API/IntegrationEvents/EventHandling/OrderStatusChangedToAwaitingValidationIntegrationEventHandler.cs

Lines changed: 28 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -8,39 +8,51 @@
88
using System.Linq;
99
using global::Catalog.API.IntegrationEvents;
1010
using IntegrationEvents.Events;
11+
using Serilog.Context;
12+
using Microsoft.Extensions.Logging;
1113

1214
public class OrderStatusChangedToAwaitingValidationIntegrationEventHandler :
1315
IIntegrationEventHandler<OrderStatusChangedToAwaitingValidationIntegrationEvent>
1416
{
1517
private readonly CatalogContext _catalogContext;
1618
private readonly ICatalogIntegrationEventService _catalogIntegrationEventService;
19+
private readonly ILogger<OrderStatusChangedToAwaitingValidationIntegrationEventHandler> _logger;
1720

18-
public OrderStatusChangedToAwaitingValidationIntegrationEventHandler(CatalogContext catalogContext,
19-
ICatalogIntegrationEventService catalogIntegrationEventService)
21+
public OrderStatusChangedToAwaitingValidationIntegrationEventHandler(
22+
CatalogContext catalogContext,
23+
ICatalogIntegrationEventService catalogIntegrationEventService,
24+
ILogger<OrderStatusChangedToAwaitingValidationIntegrationEventHandler> logger)
2025
{
2126
_catalogContext = catalogContext;
2227
_catalogIntegrationEventService = catalogIntegrationEventService;
28+
_logger = logger ?? throw new System.ArgumentNullException(nameof(logger));
2329
}
2430

25-
public async Task Handle(OrderStatusChangedToAwaitingValidationIntegrationEvent command)
31+
public async Task Handle(OrderStatusChangedToAwaitingValidationIntegrationEvent @event)
2632
{
27-
var confirmedOrderStockItems = new List<ConfirmedOrderStockItem>();
28-
29-
foreach (var orderStockItem in command.OrderStockItems)
33+
using (LogContext.PushProperty("IntegrationEventId_Context", @event.Id))
3034
{
31-
var catalogItem = _catalogContext.CatalogItems.Find(orderStockItem.ProductId);
32-
var hasStock = catalogItem.AvailableStock >= orderStockItem.Units;
33-
var confirmedOrderStockItem = new ConfirmedOrderStockItem(catalogItem.Id, hasStock);
35+
_logger.LogInformation("----- Handling integration event: {IntegrationEventId} at {AppShortName} - ({@IntegrationEvent})", @event.Id, Program.AppShortName, @event);
3436

35-
confirmedOrderStockItems.Add(confirmedOrderStockItem);
36-
}
37+
var confirmedOrderStockItems = new List<ConfirmedOrderStockItem>();
38+
39+
foreach (var orderStockItem in @event.OrderStockItems)
40+
{
41+
var catalogItem = _catalogContext.CatalogItems.Find(orderStockItem.ProductId);
42+
var hasStock = catalogItem.AvailableStock >= orderStockItem.Units;
43+
var confirmedOrderStockItem = new ConfirmedOrderStockItem(catalogItem.Id, hasStock);
3744

38-
var confirmedIntegrationEvent = confirmedOrderStockItems.Any(c => !c.HasStock)
39-
? (IntegrationEvent) new OrderStockRejectedIntegrationEvent(command.OrderId, confirmedOrderStockItems)
40-
: new OrderStockConfirmedIntegrationEvent(command.OrderId);
45+
confirmedOrderStockItems.Add(confirmedOrderStockItem);
46+
}
4147

42-
await _catalogIntegrationEventService.SaveEventAndCatalogContextChangesAsync(confirmedIntegrationEvent);
43-
await _catalogIntegrationEventService.PublishThroughEventBusAsync(confirmedIntegrationEvent);
48+
var confirmedIntegrationEvent = confirmedOrderStockItems.Any(c => !c.HasStock)
49+
? (IntegrationEvent)new OrderStockRejectedIntegrationEvent(@event.OrderId, confirmedOrderStockItems)
50+
: new OrderStockConfirmedIntegrationEvent(@event.OrderId);
51+
52+
await _catalogIntegrationEventService.SaveEventAndCatalogContextChangesAsync(confirmedIntegrationEvent);
53+
await _catalogIntegrationEventService.PublishThroughEventBusAsync(confirmedIntegrationEvent);
54+
55+
}
4456
}
4557
}
4658
}

src/Services/Catalog/Catalog.API/IntegrationEvents/EventHandling/OrderStatusChangedToPaidIntegrationEventHandler.cs

Lines changed: 20 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,28 +4,40 @@
44
using System.Threading.Tasks;
55
using Infrastructure;
66
using Microsoft.eShopOnContainers.Services.Catalog.API.IntegrationEvents.Events;
7+
using Microsoft.Extensions.Logging;
8+
using Serilog.Context;
79

810
public class OrderStatusChangedToPaidIntegrationEventHandler :
911
IIntegrationEventHandler<OrderStatusChangedToPaidIntegrationEvent>
1012
{
1113
private readonly CatalogContext _catalogContext;
14+
private readonly ILogger<OrderStatusChangedToPaidIntegrationEventHandler> _logger;
1215

13-
public OrderStatusChangedToPaidIntegrationEventHandler(CatalogContext catalogContext)
16+
public OrderStatusChangedToPaidIntegrationEventHandler(
17+
CatalogContext catalogContext,
18+
ILogger<OrderStatusChangedToPaidIntegrationEventHandler> logger)
1419
{
1520
_catalogContext = catalogContext;
21+
_logger = logger ?? throw new System.ArgumentNullException(nameof(logger));
1622
}
1723

18-
public async Task Handle(OrderStatusChangedToPaidIntegrationEvent command)
24+
public async Task Handle(OrderStatusChangedToPaidIntegrationEvent @event)
1925
{
20-
//we're not blocking stock/inventory
21-
foreach (var orderStockItem in command.OrderStockItems)
26+
using (LogContext.PushProperty("IntegrationEventId_Context", @event.Id))
2227
{
23-
var catalogItem = _catalogContext.CatalogItems.Find(orderStockItem.ProductId);
28+
_logger.LogInformation("----- Handling integration event: {IntegrationEventId} at {AppShortName} - ({@IntegrationEvent})", @event.Id, Program.AppShortName, @event);
2429

25-
catalogItem.RemoveStock(orderStockItem.Units);
26-
}
30+
//we're not blocking stock/inventory
31+
foreach (var orderStockItem in @event.OrderStockItems)
32+
{
33+
var catalogItem = _catalogContext.CatalogItems.Find(orderStockItem.ProductId);
34+
35+
catalogItem.RemoveStock(orderStockItem.Units);
36+
}
2737

28-
await _catalogContext.SaveChangesAsync();
38+
await _catalogContext.SaveChangesAsync();
39+
40+
}
2941
}
3042
}
3143
}

src/Services/Marketing/Marketing.API/IntegrationEvents/Handlers/UserLocationUpdatedIntegrationEventHandler.cs

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44
using Marketing.API.Model;
55
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Abstractions;
66
using Microsoft.eShopOnContainers.Services.Marketing.API.Infrastructure.Repositories;
7+
using Microsoft.Extensions.Logging;
8+
using Serilog.Context;
79
using System;
810
using System.Collections.Generic;
911
using System.Threading.Tasks;
@@ -12,20 +14,29 @@ public class UserLocationUpdatedIntegrationEventHandler
1214
: IIntegrationEventHandler<UserLocationUpdatedIntegrationEvent>
1315
{
1416
private readonly IMarketingDataRepository _marketingDataRepository;
17+
private readonly ILogger<UserLocationUpdatedIntegrationEventHandler> _logger;
1518

16-
public UserLocationUpdatedIntegrationEventHandler(IMarketingDataRepository repository)
19+
public UserLocationUpdatedIntegrationEventHandler(
20+
IMarketingDataRepository repository,
21+
ILogger<UserLocationUpdatedIntegrationEventHandler> logger)
1722
{
1823
_marketingDataRepository = repository ?? throw new ArgumentNullException(nameof(repository));
24+
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
1925
}
2026

2127
public async Task Handle(UserLocationUpdatedIntegrationEvent @event)
2228
{
23-
var userMarketingData = await _marketingDataRepository.GetAsync(@event.UserId);
24-
userMarketingData = userMarketingData ??
25-
new MarketingData() { UserId = @event.UserId };
29+
using (LogContext.PushProperty("IntegrationEventId_Context", @event.Id))
30+
{
31+
_logger.LogInformation("----- Handling integration event: {IntegrationEventId} at {AppShortName} - ({@IntegrationEvent})", @event.Id, Program.AppShortName, @event);
2632

27-
userMarketingData.Locations = MapUpdatedUserLocations(@event.LocationList);
28-
await _marketingDataRepository.UpdateLocationAsync(userMarketingData);
33+
var userMarketingData = await _marketingDataRepository.GetAsync(@event.UserId);
34+
userMarketingData = userMarketingData ??
35+
new MarketingData() { UserId = @event.UserId };
36+
37+
userMarketingData.Locations = MapUpdatedUserLocations(@event.LocationList);
38+
await _marketingDataRepository.UpdateLocationAsync(userMarketingData);
39+
}
2940
}
3041

3142
private List<Location> MapUpdatedUserLocations(List<UserLocationDetails> newUserLocations)

src/Services/Marketing/Marketing.API/Program.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
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/Ordering/Ordering.API/Application/Behaviors/BehaviorsHelperExtensions.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ namespace Ordering.API.Application.Behaviors
77
{
88
internal static class BehaviorsHelperExtensions
99
{
10-
internal static string GetTypeName(this object @object)
10+
internal static string GetGenericTypeName(this object @object)
1111
{
1212
var typeName = string.Empty;
1313
var type = @object.GetType();

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,9 @@ public class LoggingBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest,
1313

1414
public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
1515
{
16-
_logger.LogInformation("----- Handling command {CommandName} ({@Command})", request.GetTypeName(), request);
16+
_logger.LogInformation("----- Handling command {CommandName} ({@Command})", request.GetGenericTypeName(), request);
1717
var response = await next();
18-
_logger.LogInformation("----- Command {CommandName} handled - response: {@Response}", request.GetTypeName(), response);
18+
_logger.LogInformation("----- Command {CommandName} handled - response: {@Response}", request.GetGenericTypeName(), response);
1919

2020
return response;
2121
}

0 commit comments

Comments
 (0)