Skip to content

Commit

Permalink
Add new settings EnableContextLoggingMiddleware
Browse files Browse the repository at this point in the history
  • Loading branch information
support committed Nov 25, 2023
1 parent 197502e commit 9a226fc
Show file tree
Hide file tree
Showing 11 changed files with 122 additions and 31 deletions.
5 changes: 5 additions & 0 deletions src/Core/Grand.Infrastructure/Configuration/AppConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,11 @@ public class AppConfig
/// </summary>
public long? MaxRequestBodySize { get; set; }

/// <summary>
/// Gets or sets the value to enable a middleware for logging additional information about CurrentCustomer and store
/// </summary>
public bool EnableContextLoggingMiddleware { get; set; }

/// <summary>
/// Gets or sets a value indicating - (Serilog) use middleware for smarter HTTP request logging
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using Grand.Business.Core.Queries.Checkout.Orders;
using Grand.Domain.Payments;
using MediatR;
using Microsoft.Extensions.Logging;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;

Expand All @@ -20,13 +21,13 @@ public class CaptureCommandHandlerTests
private Mock<IPaymentTransactionService> _paymentTransactionMock;
private Mock<IOrderService> _orderServiceMock;
private Mock<IMediator> _mediatorMock;
private Mock<ILogger> _loggerMock;
private Mock<ILogger<CaptureCommandHandler>> _loggerMock;

[TestInitialize]
public void Init()
{
_mediatorMock = new Mock<IMediator>();
_loggerMock = new Mock<ILogger>();
_loggerMock = new Mock<ILogger<CaptureCommandHandler>>();
_orderServiceMock = new Mock<IOrderService>();
_paymentServiceMock = new Mock<IPaymentService>();
_paymentTransactionMock = new Mock<IPaymentTransactionService>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
using Grand.Domain.Orders;
using Grand.Domain.Payments;
using MediatR;
using Microsoft.Extensions.Logging;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;

Expand All @@ -23,7 +24,7 @@ public class PartiallyRefundCommandHandlerTests
private Mock<IOrderService> _orderServiceMock;
private Mock<IMediator> _mediatorMock;
private Mock<IMessageProviderService> _messageProviderServiceMock;
private Mock<ILogger> _loggerMock;
private Mock<ILogger<PartiallyRefundCommandHandler>> _loggerMock;

[TestInitialize]
public void Init()
Expand All @@ -33,7 +34,7 @@ public void Init()
_paymentTransactionMock = new Mock<IPaymentTransactionService>();
_messageProviderServiceMock = new Mock<IMessageProviderService>();
_paymentServiceMock = new Mock<IPaymentService>();
_loggerMock = new Mock<ILogger>();
_loggerMock = new Mock<ILogger<PartiallyRefundCommandHandler>>();

_handler = new PartiallyRefundCommandHandler(_paymentServiceMock.Object, _paymentTransactionMock.Object, _mediatorMock.Object, _messageProviderServiceMock.Object, _loggerMock.Object, _orderServiceMock.Object, new Domain.Localization.LanguageSettings());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
using Grand.Domain.Orders;
using Grand.Domain.Payments;
using MediatR;
using Microsoft.Extensions.Logging;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;

Expand All @@ -23,7 +24,7 @@ public class RefundCommandHandlerTests
private Mock<IOrderService> _orderServiceMock;
private Mock<IMediator> _mediatorMock;
private Mock<IMessageProviderService> _messageProviderServiceMock;
private Mock<ILogger> _loggerMock;
private Mock<ILogger<RefundCommandHandler>> _loggerMock;

[TestInitialize]
public void Init()
Expand All @@ -33,7 +34,7 @@ public void Init()
_paymentTransactionMock = new Mock<IPaymentTransactionService>();
_messageProviderServiceMock = new Mock<IMessageProviderService>();
_paymentServiceMock = new Mock<IPaymentService>();
_loggerMock = new Mock<ILogger>();
_loggerMock = new Mock<ILogger<RefundCommandHandler>>();

_handler = new RefundCommandHandler(_mediatorMock.Object, _paymentServiceMock.Object, _paymentTransactionMock.Object, _orderServiceMock.Object, _messageProviderServiceMock.Object, _loggerMock.Object, new Domain.Localization.LanguageSettings());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
using Grand.Domain.Orders;
using Grand.Domain.Payments;
using MediatR;
using Microsoft.Extensions.Logging;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;

Expand All @@ -23,7 +24,7 @@ public class VoidCommandHandlerTests
private Mock<IOrderService> _orderServiceMock;
private Mock<IMediator> _mediatorMock;
private Mock<IMessageProviderService> _messageProviderServiceMock;
private Mock<ILogger> _loggerMock;
private Mock<ILogger<VoidCommandHandler>> _loggerMock;

[TestInitialize]
public void Init()
Expand All @@ -33,7 +34,7 @@ public void Init()
_paymentTransactionMock = new Mock<IPaymentTransactionService>();
_messageProviderServiceMock = new Mock<IMessageProviderService>();
_paymentServiceMock = new Mock<IPaymentService>();
_loggerMock = new Mock<ILogger>();
_loggerMock = new Mock<ILogger<VoidCommandHandler>>();

_handler = new VoidCommandHandler(
_orderServiceMock.Object,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ public async Task Execute_HasWarnings_InvokeExpectedMethos()
.ReturnsAsync((new List<string>() { "warning" }, null));
await _task.Execute();

_loggerMock.Verify(c => c.InsertLog(Domain.Logging.LogLevel.Error, It.IsAny<string>(), It.IsAny<string>(), It.IsAny<Customer>(), null, null, null), Times.Once);
_loggerMock.Verify(c => c.LogInformation(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<Customer>(), null, null, null), Times.Once);
}

[TestMethod]
Expand All @@ -78,7 +78,7 @@ public async Task Execute_Valid_InvokeExpectedMethos()
.ReturnsAsync((new List<string>(), null));
await _task.Execute();

_loggerMock.Verify(c => c.InsertLog(Domain.Logging.LogLevel.Error, It.IsAny<string>(), It.IsAny<string>(), It.IsAny<Customer>(), null, null, null), Times.Never);
_loggerMock.Verify(c => c.LogError(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<Customer>(), null, null, null), Times.Never);
_auctionMock.Verify(c => c.UpdateBid(It.IsAny<Bid>()), Times.Once);
_auctionMock.Verify(c => c.UpdateAuctionEnded(It.IsAny<Product>(), It.IsAny<bool>(), It.IsAny<bool>()), Times.Once);
_messageProviderMock.Verify(c => c.SendAuctionEndedStoreOwnerMessage(It.IsAny<Product>(), It.IsAny<string>(), It.IsAny<Bid>()), Times.Once);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ public async Task Execute_ThrowExecption_InovekExpectedMethodsAndInsertLog()
It.IsAny<string>(), It.IsAny<string>(), It.IsAny<IEnumerable<string>>())).ThrowsAsync(new Exception());

await _task.Execute();
_loggerMock.Verify(c => c.InsertLog(Domain.Logging.LogLevel.Error, It.IsAny<string>(), It.IsAny<string>(), It.IsAny<Customer>(), null, null, null), Times.Once);
_loggerMock.Verify(c => c.LogError(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<Customer>(), null, null, null), Times.Once);
_queuedEmailServiceMock.Verify(c => c.UpdateQueuedEmail(It.IsAny<QueuedEmail>()), Times.Once);
}
}
Expand Down
29 changes: 29 additions & 0 deletions src/Web/Grand.Web.Common/Middleware/ContextLoggingMiddleware.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
using Grand.Infrastructure;
using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;

namespace Grand.Web.Common.Middleware;

public class ContextLoggingMiddleware
{
private readonly RequestDelegate _next;

public ContextLoggingMiddleware(RequestDelegate next)
{
_next = next;
}

public async Task InvokeAsync(HttpContext context)
{
var workContext = context.RequestServices.GetRequiredService<IWorkContext>();

var requestTelemetry = context.Features.Get<RequestTelemetry>();
requestTelemetry.Properties.TryAdd("Customer", workContext?.CurrentCustomer?.Email);
requestTelemetry.Properties.TryAdd("Store", workContext?.CurrentStore?.Name);
requestTelemetry.Properties.TryAdd("Currency", workContext?.WorkingCurrency?.Name);
requestTelemetry.Properties.TryAdd("Language", workContext?.WorkingLanguage?.Name);

await _next(context);
}
}
52 changes: 52 additions & 0 deletions src/Web/Grand.Web.Common/Startup/LoggerStartup.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
using Grand.Domain.Data;
using Grand.Infrastructure;
using Grand.Infrastructure.Configuration;
using Grand.Web.Common.Middleware;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace Grand.Web.Common.Startup
{
/// <summary>
/// Represents object for the configuring logger middleware on application startup
/// </summary>
public class LoggerStartup : IStartupApplication
{
/// <summary>
/// Add and configure any of the middleware
/// </summary>
/// <param name="services">Collection of service descriptors</param>
/// <param name="configuration">Configuration root of the application</param>
public void ConfigureServices(IServiceCollection services, IConfiguration configuration)
{

}

/// <summary>
/// Configure the using of added middleware
/// </summary>
/// <param name="application">Builder for configuring an application's request pipeline</param>
/// <param name="webHostEnvironment">WebHostEnvironment</param>
public void Configure(IApplicationBuilder application, IWebHostEnvironment webHostEnvironment)
{
//check whether database is installed
if (!DataSettingsManager.DatabaseIsInstalled())
return;

var appConfig = application.ApplicationServices.GetRequiredService<AppConfig>();

//set context logging
if(appConfig.EnableContextLoggingMiddleware)
application.UseMiddleware<ContextLoggingMiddleware>();
}

/// <summary>
/// Gets order of this startup configuration implementation
/// </summary>
public int Priority => 501;
public bool BeforeConfigure => false;

}
}
37 changes: 19 additions & 18 deletions src/Web/Grand.Web/App_Data/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,10 @@
//Gets or sets the maximum allowed size of any request body in bytes
//the default value is 30MB
"MaxRequestBodySize": null, //max 2147483648


//Gets or sets the value to enable a middleware for logging additional information about CurrentCustomer and CurrentStore
"EnableContextLoggingMiddleware": false,

//(Serilog) Request logging - The package includes middleware for smarter HTTP request logging.
"UseSerilogRequestLogging": false
},
Expand Down Expand Up @@ -133,7 +136,7 @@
"UseResponseCompression": false,

//Gets or sets a value indicating whether mini profiler should be displayed in public store (used for debugging)
"DisplayMiniProfilerInPublicStore": true,
"DisplayMiniProfilerInPublicStore": false,

//Indicates whether to ignore InstallUrlMiddleware
"IgnoreInstallUrlMiddleware": false,
Expand Down Expand Up @@ -245,26 +248,24 @@
"SystemModel": true
},
"UseSwagger": false,
//Settings only for advanced users

"Logging": {
"LogLevel": {
"Default": "Information",
"System": "Information"
}
},
"Serilog": {
"Using": [ "Serilog.Sinks.File" ]
//,
//"MinimumLevel": {
// "Default": "Warning"
// }
//,
//"WriteTo": [
// {
// "Name": "File",
// "Args": { "path": "logs/log.txt" }
// }
// ]
"Using": [ "Serilog.Sinks.Console" ],
"MinimumLevel": "Information",
"WriteTo": [
{ "Name": "Console" }
]
},

"ApplicationInsights": {
"Enabled": false,
"ConnectionString": ""
"Enabled": true,
"InstrumentationKey": "b6efc68b-61cd-4463-bd86-c4355532f338",
"EnableAdaptiveSampling": false
}
//https://docs.microsoft.com/en-us/azure/azure-monitor/app/asp-net-core
//The following configuration allows ApplicationInsights to capture
Expand Down
4 changes: 2 additions & 2 deletions src/Web/Grand.Web/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Serilog;
using StartupBase = Grand.Infrastructure.StartupBase;

Expand All @@ -18,7 +17,8 @@
options.ValidateOnBuild = false;
});

builder.Logging.AddConsole();
builder.Services.AddLogging();

//use serilog
builder.Host.UseSerilog();

Expand Down

0 comments on commit 9a226fc

Please sign in to comment.