Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add more logs #85

Merged
merged 5 commits into from
Mar 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions src/BuildingBlocks/Logging/LoggingExtension.cs
Original file line number Diff line number Diff line change
Expand Up @@ -97,8 +97,9 @@ public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)

private static string GetGrafanaUrl(string traceId)
{
var url = HttpUtility.UrlEncode("http://localhost:3000/explore?schemaVersion=1&panes={\"vvs\":{\"queries\":[{\"query\":" + traceId + "}]} }");
return url;
var baseUrl = "http://localhost:3000/explore?schemaVersion=1&panes=";
var query = HttpUtility.UrlEncode("{\"vvs\":{\"queries\":[{\"query\":" + traceId + "}]}}");
return baseUrl + query;
}
}

Expand Down
13 changes: 8 additions & 5 deletions src/Services/Basket/Basket.API.Tests/BasketControllerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using Eshop.BuildingBlocks.EventBus.RabbitMQ.Abstractions;
using Grpc.Core;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Moq;
using System;
using System.Collections.Generic;
Expand All @@ -19,21 +20,23 @@ public class BasketControllerTests
{
private readonly Mock<IBasketRepository> _basketRepositoryMock;
private readonly Mock<IRabbitMQProducer> _rabbitMQProducerMock;
private readonly Mock<ILogger<BasketController>> _logger;
private readonly Mock<DiscountProtoService.DiscountProtoServiceClient> _discountProtoServiceClientMock;

public BasketControllerTests()
{
_basketRepositoryMock = new Mock<IBasketRepository>();
_rabbitMQProducerMock = new Mock<IRabbitMQProducer>();
_discountProtoServiceClientMock = new Mock<DiscountProtoService.DiscountProtoServiceClient>();
_logger = new Mock<ILogger<BasketController>>();
}

[Fact]
public async Task GetBasket_Username_Null_Or_Empty_Return_BadRequest()
{
// Arrange
var username = string.Empty;
var controller = new BasketController(_basketRepositoryMock.Object, _discountProtoServiceClientMock.Object, _rabbitMQProducerMock.Object);
var controller = new BasketController(_logger.Object, _basketRepositoryMock.Object, _discountProtoServiceClientMock.Object, _rabbitMQProducerMock.Object);

// Act
var actual = await controller.GetBasket(username);
Expand All @@ -48,7 +51,7 @@ public async Task GetBasket_NoBasket_Return_EmptyBasket()
// Arrange
var username = "test";
_basketRepositoryMock.Setup(x => x.GetBasketAsync(It.IsAny<string>())).ReturnsAsync(() => null);
var controller = new BasketController(_basketRepositoryMock.Object, _discountProtoServiceClientMock.Object, _rabbitMQProducerMock.Object);
var controller = new BasketController(_logger.Object, _basketRepositoryMock.Object, _discountProtoServiceClientMock.Object, _rabbitMQProducerMock.Object);

// Act
var actual = await controller.GetBasket(username);
Expand Down Expand Up @@ -81,7 +84,7 @@ public async Task UpdateBasket_Returns_Updated_Basket()
.Returns(discountMockCall);

_basketRepositoryMock.Setup(x => x.UpdateBasketAsync(It.IsAny<ShoppingCart>())).ReturnsAsync(basket);
var controller = new BasketController(_basketRepositoryMock.Object, _discountProtoServiceClientMock.Object, _rabbitMQProducerMock.Object);
var controller = new BasketController(_logger.Object, _basketRepositoryMock.Object, _discountProtoServiceClientMock.Object, _rabbitMQProducerMock.Object);

// Act
var actual = await controller.UpdateBasket(basket);
Expand All @@ -103,7 +106,7 @@ public async Task Checkout_Return_BadRequest_When_Basket_Is_Null()
Username = "test",
};
_basketRepositoryMock.Setup(x => x.GetBasketAsync(It.IsAny<string>())).ReturnsAsync(() => null);
var controller = new BasketController(_basketRepositoryMock.Object, _discountProtoServiceClientMock.Object, _rabbitMQProducerMock.Object);
var controller = new BasketController(_logger.Object, _basketRepositoryMock.Object, _discountProtoServiceClientMock.Object, _rabbitMQProducerMock.Object);

// Act
var actual = await controller.Checkout(basket);
Expand Down Expand Up @@ -135,7 +138,7 @@ public async Task Checkout_Sends_Out_CheckOut_Event_And_Deletes_Basket()
}
});

var controller = new BasketController(_basketRepositoryMock.Object, _discountProtoServiceClientMock.Object, _rabbitMQProducerMock.Object);
var controller = new BasketController(_logger.Object, _basketRepositoryMock.Object, _discountProtoServiceClientMock.Object, _rabbitMQProducerMock.Object);
_rabbitMQProducerMock.Setup(x => x.PublishAsJsonAsync(It.IsAny<string>(), It.IsAny<object>()));
_basketRepositoryMock.Setup(x => x.DeleteBasketAsync(It.IsAny<string>()));

Expand Down
19 changes: 18 additions & 1 deletion src/Services/Basket/Basket.API/Controllers/BasketController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,15 @@ public class BasketController : ControllerBase
private readonly IBasketRepository _repository;
private readonly IRabbitMQProducer _rabbitMQProducer;
private readonly DiscountProtoService.DiscountProtoServiceClient _discountProtoServiceClient;
private readonly ILogger<BasketController> _logger;

public BasketController(
ILogger<BasketController> logger,
IBasketRepository repository,
DiscountProtoService.DiscountProtoServiceClient discountProtoServiceClient,
IRabbitMQProducer rabbitMQProducer)
{
_logger = logger;
_repository = repository ?? throw new ArgumentNullException(nameof(repository));
_discountProtoServiceClient = discountProtoServiceClient ?? throw new ArgumentNullException(nameof(discountProtoServiceClient));
_rabbitMQProducer = rabbitMQProducer ?? throw new ArgumentNullException(nameof(rabbitMQProducer));
Expand All @@ -32,6 +35,7 @@ public async Task<ActionResult<ShoppingCart>> GetBasket(string username)
if (string.IsNullOrEmpty(username))
return BadRequest("Username cannot be null or empty.");

_logger.LogInformation($"Getting basket for username {GetLogStringValue(username)}");
var basket = await _repository.GetBasketAsync(username);
return Ok(basket ?? new ShoppingCart(username));
}
Expand All @@ -40,6 +44,7 @@ public async Task<ActionResult<ShoppingCart>> GetBasket(string username)
[ProducesResponseType(typeof(ShoppingCart), (int)HttpStatusCode.OK)]
public async Task<ActionResult<ShoppingCart>> UpdateBasket([FromBody] ShoppingCart basket)
{
_logger.LogInformation($"Updating basket for username {GetLogStringValue(basket.Username)}");
foreach (var item in basket.Items)
{
var discountResquest = new GetDiscountRequest() { ProductName = item.ProductName };
Expand All @@ -54,6 +59,7 @@ public async Task<ActionResult<ShoppingCart>> UpdateBasket([FromBody] ShoppingCa
[ProducesResponseType(typeof(void), (int)HttpStatusCode.OK)]
public async Task<IActionResult> DeleteBasket(string username)
{
_logger.LogInformation($"Delete basket for username {GetLogStringValue(username)}");
await _repository.DeleteBasketAsync(username);
return Ok();
}
Expand All @@ -68,12 +74,23 @@ public async Task<IActionResult> Checkout([FromBody] BasketCheckout basketChecko
if (basket == null)
return BadRequest();

_logger.LogInformation($"checking out basket for username {GetLogStringValue(basketCheckout.Username)}");
basketCheckout.TotalPrice = basket.TotalPrice;
await _rabbitMQProducer.PublishAsJsonAsync("order.checkout", basketCheckout);

await _repository.DeleteBasketAsync(basket.Username);

return Accepted();
}

/// <summary>
/// Prevents Log Injection attacks
/// https://owasp.org/www-community/attacks/Log_Injection
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
private static string GetLogStringValue(string value)
{
return value.Replace(Environment.NewLine, "");
}
}
}
4 changes: 4 additions & 0 deletions src/Services/Basket/Basket.API/Grpc/BasketService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ public override async Task<ShoppingCartModel> GetBasket(GetBasketRequest request
if (string.IsNullOrEmpty(request.Username))
throw new RpcException(new Status(StatusCode.InvalidArgument, "Username cannot be null or empty."));

_logger.LogInformation($"Getting basket for username {request.Username}");
var basket = await _repository.GetBasketAsync(request.Username);
basket ??= new ShoppingCart(request.Username);
_logger.LogInformation("Basket is retrieved for Username : {Username}", request.Username);
Expand All @@ -45,6 +46,7 @@ public override async Task<ShoppingCartModel> GetBasket(GetBasketRequest request

public override async Task<ShoppingCartModel> UpdateBasket(UpdateBasketRequest request, ServerCallContext context)
{
_logger.LogInformation($"Updating basket for username {request.ShoppingCart.Username}");
var ShoppingCartItems = request.ShoppingCart.Items.ToList();

foreach (var item in ShoppingCartItems)
Expand All @@ -62,6 +64,7 @@ public override async Task<ShoppingCartModel> UpdateBasket(UpdateBasketRequest r

public override async Task<NoResponse> DeletetBasket(DeletetBasketRequest request, ServerCallContext context)
{
_logger.LogInformation($"Delete basket for username {request.Username}");
await _repository.DeleteBasketAsync(request.Username);
return new NoResponse();
}
Expand All @@ -72,6 +75,7 @@ public override async Task<NoResponse> Checkout(CheckoutViewModel request, Serve
if (basket == null)
throw new RpcException(new Status(StatusCode.NotFound, "Basket not found."));

_logger.LogInformation($"checking out basket for username {request.Username}");
request.TotalPrice = (double)basket.TotalPrice;
var basketCheckout = _mapper.Map<BasketCheckout>(request);

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using Catalog.API.Entities;
using Catalog.API.Repositories;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System.Net;

namespace Catalog.API.Controllers
Expand All @@ -22,6 +23,7 @@ public CatalogController(IProductRepository repository, ILogger<CatalogControlle
[ProducesResponseType(typeof(IEnumerable<Product>), (int)HttpStatusCode.OK)]
public async Task<ActionResult<IEnumerable<Product>>> GetProducts()
{
_logger.LogInformation("Getting the list of all the products.");
var products = await _repository.GetProductsAsync();
return Ok(products);
}
Expand All @@ -34,6 +36,8 @@ public async Task<ActionResult<Product>> GetProductById(string id)
if (string.IsNullOrEmpty(id))
return BadRequest("Product Id cannot be null or empty.");

_logger.LogInformation("Getting product with Id={ProductId}.", GetLogStringValue(id));

var product = await _repository.GetProductAsync(id);
if (product == null)
{
Expand All @@ -51,6 +55,7 @@ public async Task<ActionResult<IEnumerable<Product>>> GetProductByCategory(strin
if (string.IsNullOrEmpty(category))
return BadRequest("Category cannot be null or empty.");

_logger.LogInformation("Getting the list of all the products for Category={category}", GetLogStringValue(category));
var products = await _repository.GetProductByCategoryAsync(category);
return Ok(products);
}
Expand All @@ -59,6 +64,7 @@ public async Task<ActionResult<IEnumerable<Product>>> GetProductByCategory(strin
[ProducesResponseType(typeof(Product), (int)HttpStatusCode.Created)]
public async Task<ActionResult<Product>> CreateProduct([FromBody] Product product)
{
_logger.LogInformation($"Cearting product: {GetLogStringValue(JsonConvert.SerializeObject(product))}");
await _repository.CreateProductAsync(product);
return CreatedAtRoute("GetProduct", new { id = product.Id }, product);
}
Expand All @@ -67,6 +73,7 @@ public async Task<ActionResult<Product>> CreateProduct([FromBody] Product produc
[ProducesResponseType(typeof(Product), (int)HttpStatusCode.OK)]
public async Task<IActionResult> UpdateProduct([FromBody] Product product)
{
_logger.LogInformation($"Updating product {GetLogStringValue(JsonConvert.SerializeObject(product))}");
return Ok(await _repository.UpdateProductAsync(product));
}

Expand All @@ -77,6 +84,7 @@ public async Task<IActionResult> DeleteProductById(string id)
if (string.IsNullOrEmpty(id))
return BadRequest("Product Id cannot be null or empty.");

_logger.LogInformation($"Deleting product with Id {GetLogStringValue(id)}");
return Ok(await _repository.DeleteProductAsync(id));
}

Expand Down
8 changes: 8 additions & 0 deletions src/Services/Catalog/Catalog.API/Grpc/CatalogService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ public CatalogService(IProductRepository repository, ILogger<CatalogService> log

public override async Task<GetProductsResponse> GetProducts(NoRequest request, ServerCallContext context)
{
_logger.LogInformation("Getting the list of all the products.");
var products = await _repository.GetProductsAsync();
var productModels = _mapper.Map<List<ProductModel>>(products);
var result = new GetProductsResponse();
Expand All @@ -30,6 +31,8 @@ public override async Task<GetProductsResponse> GetProducts(NoRequest request, S

public override async Task<ProductModel> GetProductById(GetProductByIdRequest request, ServerCallContext context)
{
_logger.LogInformation("Getting product with Id={ProductId}.", request.Id);

var product = await _repository.GetProductAsync(request.Id);

if (product == null)
Expand All @@ -41,6 +44,8 @@ public override async Task<ProductModel> GetProductById(GetProductByIdRequest re

public override async Task<GetProductByCategoryResponse> GetProductByCategory(GetProductByCategoryRequest request, ServerCallContext context)
{
_logger.LogInformation("Getting the list of all the products for Category={category}", request.Category);

var products = await _repository.GetProductByCategoryAsync(request.Category);
var productModels = _mapper.Map<List<ProductModel>>(products);
var result = new GetProductByCategoryResponse();
Expand All @@ -50,6 +55,7 @@ public override async Task<GetProductByCategoryResponse> GetProductByCategory(Ge

public override async Task<ProductModel> CreateProduct(CreateProductRequest request, ServerCallContext context)
{
_logger.LogInformation($"Cearting product: {request.Product}");
var product = _mapper.Map<Product>(request.Product);
await _repository.CreateProductAsync(product);

Expand All @@ -59,13 +65,15 @@ public override async Task<ProductModel> CreateProduct(CreateProductRequest requ

public override async Task<UpdateProductResponse> UpdateProduct(UpdateProductRequest request, ServerCallContext context)
{
_logger.LogInformation($"Updating product {request.Product}");
var product = _mapper.Map<Product>(request.Product);
var result = await _repository.UpdateProductAsync(product);
return new UpdateProductResponse() { Result = result };
}

public override async Task<DeleteProductIdResponse> DeleteProductById(DeleteProductIdRequest request, ServerCallContext context)
{
_logger.LogInformation($"Deleting product with Id {request.Id}");
var result = await _repository.DeleteProductAsync(request.Id);
return new DeleteProductIdResponse() { Result = result };
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,19 @@ namespace Discount.API.Controllers
public class DiscountController : ControllerBase
{
private readonly IDiscountRepository _repository;
private readonly ILogger<DiscountController> _logger;

public DiscountController(IDiscountRepository repository)
public DiscountController(IDiscountRepository repository, ILogger<DiscountController> logger)
{
_repository = repository ?? throw new ArgumentNullException(nameof(repository));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}

[HttpGet("{productName}", Name = "GetDiscount")]
[ProducesResponseType(typeof(Coupon), (int)HttpStatusCode.OK)]
public async Task<ActionResult<Coupon>> GetDiscount(string productName)
{
_logger.LogInformation($"Getting discount for the prodcut {GetLogStringValue(productName)}");
var coupon = await _repository.GetDiscountAsync(productName);
return Ok(coupon);
}
Expand All @@ -28,6 +31,7 @@ public async Task<ActionResult<Coupon>> GetDiscount(string productName)
[ProducesResponseType(typeof(Coupon), (int)HttpStatusCode.OK)]
public async Task<ActionResult<Coupon>> CreateDiscount([FromBody] Coupon coupon)
{
_logger.LogInformation($"Create discount for the prodcut {GetLogStringValue(coupon.ProductName)}");
await _repository.CreateDiscountAsync(coupon);
return CreatedAtRoute("GetDiscount", new { productName = coupon.ProductName }, coupon);
}
Expand All @@ -36,14 +40,27 @@ public async Task<ActionResult<Coupon>> CreateDiscount([FromBody] Coupon coupon)
[ProducesResponseType(typeof(Coupon), (int)HttpStatusCode.OK)]
public async Task<ActionResult<Coupon>> UpdateDiscount([FromBody] Coupon coupon)
{
_logger.LogInformation($"Update discount for the prodcut {GetLogStringValue(coupon.ProductName)}");
return Ok(await _repository.UpdateDiscountAsync(coupon));
}

[HttpDelete("{productName}", Name = "DeleteDiscount")]
[ProducesResponseType(typeof(void), (int)HttpStatusCode.OK)]
public async Task<ActionResult<bool>> DeleteDiscount(string productName)
{
_logger.LogInformation($"Delete discount for the prodcut {GetLogStringValue(productName)}");
return Ok(await _repository.DeleteDiscountAsync(productName));
}

/// <summary>
/// Prevents Log Injection attacks
/// https://owasp.org/www-community/attacks/Log_Injection
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
private static string GetLogStringValue(string value)
{
return value.Replace(Environment.NewLine, "");
}
}
}
2 changes: 2 additions & 0 deletions src/Services/Discount/Discount.API/Grpc/DiscountService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,8 @@ public override async Task<CouponModel> UpdateDiscount(UpdateDiscountRequest req

public override async Task<DeleteDiscountResponse> DeleteDiscount(DeleteDiscountRequest request, ServerCallContext context)
{
_logger.LogInformation($"Delete discount for the prodcut {request.ProductName}");

var deleted = await _repository.DeleteDiscountAsync(request.ProductName);
var response = new DeleteDiscountResponse
{
Expand Down
Loading
Loading