Skip to content

Open-source eCommerce platform for C# and ASP.NET Core 10 with MongoDB. Build multi-store shops and multi-vendor marketplaces with B2B/B2C, REST API, plugins, Vue 3 and Docker.

Replace Custom Logger with System Logger Provider Implementation (#439)

Krzysztof Pajak31cb21deaedf
diff --git a/src/Business/Grand.Business.Catalog/Services/Directory/GeoLookupService.cs b/src/Business/Grand.Business.Catalog/Services/Directory/GeoLookupService.cs
index be8032331..7d2eee1e8 100644
--- a/src/Business/Grand.Business.Catalog/Services/Directory/GeoLookupService.cs
+++ b/src/Business/Grand.Business.Catalog/Services/Directory/GeoLookupService.cs
@@ -1,12 +1,10 @@
//This product contains GeoLite2 data created by MaxMind, from http://www.maxmind.com
-
using Grand.Business.Core.Interfaces.Catalog.Directory;
-using Grand.Business.Core.Extensions;
-using Grand.Business.Core.Interfaces.Common.Logging;
using Grand.SharedKernel.Extensions;
using MaxMind.GeoIP2;
using MaxMind.GeoIP2.Exceptions;
using MaxMind.GeoIP2.Responses;
+using Microsoft.Extensions.Logging;
namespace Grand.Business.Catalog.Services.Directory
{
@@ -17,13 +15,13 @@ namespace Grand.Business.Catalog.Services.Directory
{
#region Fields
- private readonly ILogger _logger;
+ private readonly ILogger<GeoLookupService> _logger;
#endregion
#region Ctor
- public GeoLookupService(ILogger logger)
+ public GeoLookupService(ILogger<GeoLookupService> logger)
{
_logger = logger;
}
@@ -53,7 +51,7 @@ namespace Grand.Business.Catalog.Services.Directory
}
catch (Exception exc)
{
- _ = _logger.Warning("Cannot load MaxMind record", exc);
+ _logger.LogError(exc, "Cannot load MaxMind record");
return null;
}
}
diff --git a/src/Business/Grand.Business.Catalog/Services/Tax/TaxService.cs b/src/Business/Grand.Business.Catalog/Services/Tax/TaxService.cs
index 71a6c28c9..740082568 100644
--- a/src/Business/Grand.Business.Catalog/Services/Tax/TaxService.cs
+++ b/src/Business/Grand.Business.Catalog/Services/Tax/TaxService.cs
@@ -1,9 +1,7 @@
using Grand.Business.Core.Interfaces.Catalog.Directory;
using Grand.Business.Core.Interfaces.Catalog.Tax;
using Grand.Business.Core.Utilities.Catalog;
-using Grand.Business.Core.Extensions;
using Grand.Business.Core.Interfaces.Common.Directory;
-using Grand.Business.Core.Interfaces.Common.Logging;
using Grand.Domain.Catalog;
using Grand.Domain.Common;
using Grand.Domain.Customers;
@@ -12,6 +10,7 @@ using Grand.Domain.Orders;
using Grand.Domain.Tax;
using Grand.Infrastructure;
using Grand.Infrastructure.Extensions;
+using Microsoft.Extensions.Logging;
namespace Grand.Business.Catalog.Services.Tax
{
@@ -27,7 +26,7 @@ namespace Grand.Business.Catalog.Services.Tax
private readonly IGeoLookupService _geoLookupService;
private readonly ICountryService _countryService;
private readonly IEnumerable<ITaxProvider> _taxProviders;
- private readonly ILogger _logger;
+ private readonly ILogger<TaxService> _logger;
private readonly TaxSettings _taxSettings;
private readonly TaxProviderSettings _taxProviderSettings;
private readonly CustomerSettings _customerSettings;
@@ -43,7 +42,7 @@ namespace Grand.Business.Catalog.Services.Tax
IGeoLookupService geoLookupService,
ICountryService countryService,
IEnumerable<ITaxProvider> taxProviders,
- ILogger logger,
+ ILogger<TaxService> logger,
TaxSettings taxSettings,
TaxProviderSettings taxProviderSettings,
CustomerSettings customerSettings,
@@ -249,7 +248,7 @@ namespace Grand.Business.Catalog.Services.Tax
{
foreach (var error in calculateTaxResult.Errors)
{
- _ = _logger.Error($"{activeTaxProvider.FriendlyName} - {error}", null, customer);
+ _logger.LogError("{FriendlyName} - {Error}", activeTaxProvider.FriendlyName, error);
}
}
return (taxRate, isTaxable);
diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CaptureCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CaptureCommandHandler.cs
index 464732fc5..df599a83d 100644
--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CaptureCommandHandler.cs
+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CaptureCommandHandler.cs
@@ -3,12 +3,11 @@ using Grand.Business.Core.Interfaces.Checkout.Orders;
using Grand.Business.Core.Interfaces.Checkout.Payments;
using Grand.Business.Core.Queries.Checkout.Orders;
using Grand.Business.Core.Utilities.Checkout;
-using Grand.Business.Core.Interfaces.Common.Logging;
-using Grand.Domain.Logging;
using Grand.Domain.Payments;
using Grand.SharedKernel;
using MediatR;
using Grand.Business.Core.Extensions;
+using Microsoft.Extensions.Logging;
namespace Grand.Business.Checkout.Commands.Handlers.Orders
{
@@ -18,14 +17,14 @@ namespace Grand.Business.Checkout.Commands.Handlers.Orders
private readonly IPaymentTransactionService _paymentTransaction;
private readonly IOrderService _orderService;
private readonly IMediator _mediator;
- private readonly ILogger _logger;
+ private readonly ILogger<CaptureCommandHandler> _logger;
public CaptureCommandHandler(
IPaymentService paymentService,
IPaymentTransactionService paymentTransaction,
IMediator mediator,
IOrderService orderService,
- ILogger logger)
+ ILogger<CaptureCommandHandler> logger)
{
_paymentService = paymentService;
_paymentTransaction = paymentTransaction;
@@ -95,7 +94,7 @@ namespace Grand.Business.Checkout.Commands.Handlers.Orders
if (!string.IsNullOrEmpty(error))
{
//log it
- await _logger.InsertLog(LogLevel.Error, $"Error capturing order code # {paymentTransaction.OrderCode}. Error: {error}", $"Error capturing order code # {paymentTransaction.OrderCode}. Error: {error}");
+ _logger.LogError("Error capturing order code # {PaymentTransactionOrderCode}. Error: {Error}", paymentTransaction.OrderCode, error);
}
return result.Errors;
}
diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PartiallyRefundCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PartiallyRefundCommandHandler.cs
index 5f57783c7..98ca1201c 100644
--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PartiallyRefundCommandHandler.cs
+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PartiallyRefundCommandHandler.cs
@@ -4,12 +4,11 @@ using Grand.Business.Core.Interfaces.Checkout.Orders;
using Grand.Business.Core.Interfaces.Checkout.Payments;
using Grand.Business.Core.Queries.Checkout.Orders;
using Grand.Business.Core.Utilities.Checkout;
-using Grand.Business.Core.Interfaces.Common.Logging;
using Grand.Business.Core.Interfaces.Messages;
using Grand.Domain.Localization;
-using Grand.Domain.Logging;
using Grand.SharedKernel;
using MediatR;
+using Microsoft.Extensions.Logging;
namespace Grand.Business.Checkout.Commands.Handlers.Orders
{
@@ -19,7 +18,7 @@ namespace Grand.Business.Checkout.Commands.Handlers.Orders
private readonly IPaymentTransactionService _paymentTransactionService;
private readonly IMediator _mediator;
private readonly IMessageProviderService _messageProviderService;
- private readonly ILogger _logger;
+ private readonly ILogger<PartiallyRefundCommandHandler> _logger;
private readonly IOrderService _orderService;
private readonly LanguageSettings _languageSettings;
@@ -28,7 +27,7 @@ namespace Grand.Business.Checkout.Commands.Handlers.Orders
IPaymentTransactionService paymentTransactionService,
IMediator mediator,
IMessageProviderService messageProviderService,
- ILogger logger,
+ ILogger<PartiallyRefundCommandHandler> logger,
IOrderService orderService,
LanguageSettings languageSettings)
{
@@ -112,8 +111,8 @@ namespace Grand.Business.Checkout.Commands.Handlers.Orders
}
if (string.IsNullOrEmpty(error)) return result.Errors;
- var logError = $"Error refunding order #{paymentTransaction.OrderCode}. Error: {error}";
- await _logger.InsertLog(LogLevel.Error, logError, logError);
+
+ _logger.LogError("Error refunding order #{PaymentTransactionOrderCode}. Error: {Error}", paymentTransaction.OrderCode, error);
return result.Errors;
}
}
diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PlaceOrderCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PlaceOrderCommandHandler.cs
index 25ab73008..8909501ca 100644
--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PlaceOrderCommandHandler.cs
+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PlaceOrderCommandHandler.cs
@@ -11,7 +11,6 @@ using Grand.Business.Core.Interfaces.Checkout.Orders;
using Grand.Business.Core.Interfaces.Checkout.Payments;
using Grand.Business.Core.Interfaces.Common.Directory;
using Grand.Business.Core.Interfaces.Common.Localization;
-using Grand.Business.Core.Interfaces.Common.Logging;
using Grand.Business.Core.Interfaces.Common.Pdf;
using Grand.Business.Core.Interfaces.Customers;
using Grand.Business.Core.Interfaces.Messages;
@@ -32,6 +31,7 @@ using Grand.SharedKernel;
using Grand.SharedKernel.Extensions;
using MediatR;
using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging;
namespace Grand.Business.Checkout.Commands.Handlers.Orders
{
@@ -43,7 +43,7 @@ namespace Grand.Business.Checkout.Commands.Handlers.Orders
private readonly IInventoryManageService _inventoryManageService;
private readonly IPaymentService _paymentService;
private readonly IPaymentTransactionService _paymentTransactionService;
- private readonly ILogger _logger;
+ private readonly ILogger<PlaceOrderCommandHandler> _logger;
private readonly IOrderCalculationService _orderTotalCalculationService;
private readonly IPricingService _pricingService;
private readonly IProductAttributeFormatter _productAttributeFormatter;
@@ -78,7 +78,7 @@ namespace Grand.Business.Checkout.Commands.Handlers.Orders
IInventoryManageService inventoryManageService,
IPaymentService paymentService,
IPaymentTransactionService paymentTransactionService,
- ILogger logger,
+ ILogger<PlaceOrderCommandHandler> logger,
IOrderCalculationService orderTotalCalculationService,
IPricingService priceCalculationService,
IProductAttributeFormatter productAttributeFormatter,
@@ -205,7 +205,7 @@ namespace Grand.Business.Checkout.Commands.Handlers.Orders
}
catch (Exception exc)
{
- _ = _logger.Error(exc.Message, exc);
+ _logger.LogError(exc, exc.Message);
result.AddError(exc.Message);
}
@@ -221,8 +221,7 @@ namespace Grand.Business.Checkout.Commands.Handlers.Orders
if (string.IsNullOrEmpty(error)) return result;
//log it
- var logError = $"Error while placing order. {error}";
- _ = _logger.Error(logError);
+ _logger.LogError("Error while placing order. {Error}", error);
#endregion
@@ -1088,7 +1087,7 @@ namespace Grand.Business.Checkout.Commands.Handlers.Orders
}
catch (Exception ex)
{
- _ = _logger.Error($"Error - order placed attachment file {order.OrderNumber}", ex);
+ _logger.LogError(ex, "Error - order placed attachment file {OrderOrderNumber}", order.OrderNumber);
}
await messageProviderService
@@ -1105,7 +1104,7 @@ namespace Grand.Business.Checkout.Commands.Handlers.Orders
}
catch (Exception e)
{
- await _logger.InsertLog(Domain.Logging.LogLevel.Error, "Place order send notification error", e.Message);
+ _logger.LogError(e, "Place order send notification error");
}
}
diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RefundCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RefundCommandHandler.cs
index 213bc7643..441963f63 100644
--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RefundCommandHandler.cs
+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RefundCommandHandler.cs
@@ -3,11 +3,10 @@ using Grand.Business.Core.Events.Checkout.Orders;
using Grand.Business.Core.Interfaces.Checkout.Orders;
using Grand.Business.Core.Interfaces.Checkout.Payments;
using Grand.Business.Core.Utilities.Checkout;
-using Grand.Business.Core.Interfaces.Common.Logging;
using Grand.Business.Core.Interfaces.Messages;
using Grand.Domain.Localization;
-using Grand.Domain.Logging;
using MediatR;
+using Microsoft.Extensions.Logging;
namespace Grand.Business.Checkout.Commands.Handlers.Orders
{
@@ -18,7 +17,7 @@ namespace Grand.Business.Checkout.Commands.Handlers.Orders
private readonly IPaymentTransactionService _paymentTransactionService;
private readonly IOrderService _orderService;
private readonly IMessageProviderService _messageProviderService;
- private readonly ILogger _logger;
+ private readonly ILogger<RefundCommandHandler> _logger;
private readonly LanguageSettings _languageSettings;
public RefundCommandHandler(
@@ -27,7 +26,7 @@ namespace Grand.Business.Checkout.Commands.Handlers.Orders
IPaymentTransactionService paymentTransactionService,
IOrderService orderService,
IMessageProviderService messageProviderService,
- ILogger logger,
+ ILogger<RefundCommandHandler> logger,
LanguageSettings languageSettings)
{
_mediator = mediator;
@@ -104,9 +103,7 @@ namespace Grand.Business.Checkout.Commands.Handlers.Orders
}
if (string.IsNullOrEmpty(error)) return result.Errors;
- //log it
- var logError = $"Error refunding order #{paymentTransaction.OrderCode}. Error: {error}";
- await _logger.InsertLog(LogLevel.Error, logError, logError);
+ _logger.LogError("Error refunding order #{PaymentTransactionOrderCode}. Error: {Error}", paymentTransaction.OrderCode, error);
return result.Errors;
}
}
diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/VoidCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/VoidCommandHandler.cs
index 62be759bf..4ad05e96d 100644
--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/VoidCommandHandler.cs
+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/VoidCommandHandler.cs
@@ -3,11 +3,10 @@ using Grand.Business.Core.Interfaces.Checkout.Orders;
using Grand.Business.Core.Interfaces.Checkout.Payments;
using Grand.Business.Core.Queries.Checkout.Orders;
using Grand.Business.Core.Utilities.Checkout;
-using Grand.Business.Core.Interfaces.Common.Logging;
-using Grand.Domain.Logging;
using Grand.SharedKernel;
using MediatR;
using Grand.Business.Core.Extensions;
+using Microsoft.Extensions.Logging;
namespace Grand.Business.Checkout.Commands.Handlers.Orders
{
@@ -17,14 +16,14 @@ namespace Grand.Business.Checkout.Commands.Handlers.Orders
private readonly IMediator _mediator;
private readonly IPaymentService _paymentService;
private readonly IPaymentTransactionService _paymentTransactionService;
- private readonly ILogger _logger;
+ private readonly ILogger<VoidCommandHandler> _logger;
public VoidCommandHandler(
IOrderService orderService,
IMediator mediator,
IPaymentService paymentService,
IPaymentTransactionService paymentTransactionService,
- ILogger logger)
+ ILogger<VoidCommandHandler> logger)
{
_orderService = orderService;
_mediator = mediator;
@@ -86,8 +85,8 @@ namespace Grand.Business.Checkout.Commands.Handlers.Orders
}
if (string.IsNullOrEmpty(error)) return result.Errors;
- var logError = $"Error voiding order #{paymentTransaction.OrderCode}. Error: {error}";
- await _logger.InsertLog(LogLevel.Error, logError, logError);
+
+ _logger.LogError("Error voiding order #{PaymentTransactionOrderCode}. Error: {Error}", paymentTransaction.OrderCode, error);
return result.Errors;
}
}
diff --git a/src/Business/Grand.Business.Checkout/Services/Shipping/ShippingService.cs b/src/Business/Grand.Business.Checkout/Services/Shipping/ShippingService.cs
index af250eb38..c9156daf8 100644
--- a/src/Business/Grand.Business.Checkout/Services/Shipping/ShippingService.cs
+++ b/src/Business/Grand.Business.Checkout/Services/Shipping/ShippingService.cs
@@ -1,8 +1,6 @@
using Grand.Business.Core.Interfaces.Checkout.Shipping;
using Grand.Business.Core.Utilities.Checkout;
-using Grand.Business.Core.Extensions;
using Grand.Business.Core.Interfaces.Common.Directory;
-using Grand.Business.Core.Interfaces.Common.Logging;
using Grand.Domain.Common;
using Grand.Domain.Customers;
using Grand.Domain.Orders;
@@ -10,6 +8,7 @@ using Grand.Domain.Shipping;
using Grand.Domain.Stores;
using Grand.Infrastructure.Extensions;
using Grand.SharedKernel;
+using Microsoft.Extensions.Logging;
namespace Grand.Business.Checkout.Services.Shipping
{
@@ -20,7 +19,7 @@ namespace Grand.Business.Checkout.Services.Shipping
{
#region Fields
- private readonly ILogger _logger;
+ private readonly ILogger<ShippingService> _logger;
private readonly ICountryService _countryService;
private readonly IEnumerable<IShippingRateCalculationProvider> _shippingRateCalculationProvider;
private readonly ShippingSettings _shippingSettings;
@@ -34,7 +33,7 @@ namespace Grand.Business.Checkout.Services.Shipping
/// Ctor
/// </summary>
public ShippingService(
- ILogger logger,
+ ILogger<ShippingService> logger,
ICountryService countryService,
IEnumerable<IShippingRateCalculationProvider> shippingRateCalculationProvider,
ShippingProviderSettings shippingProviderSettings,
@@ -196,7 +195,7 @@ namespace Grand.Business.Checkout.Services.Shipping
foreach (var error in getShippingOptionResponse.Errors)
{
result.AddError(error);
- _ = _logger.Warning($"Shipping ({shippingRateMethod.FriendlyName}). {error}");
+ _logger.LogWarning("Shipping ({FriendlyName}) {Error}", shippingRateMethod.FriendlyName, error);
}
//clear the shipping options in this case
break;
diff --git a/src/Business/Grand.Business.Common/Services/Logging/DefaultLogger.cs b/src/Business/Grand.Business.Common/Services/Logging/DefaultLogger.cs
deleted file mode 100644
index 647838bce..000000000
--- a/src/Business/Grand.Business.Common/Services/Logging/DefaultLogger.cs
+++ /dev/null
@@ -1,151 +0,0 @@
-using Grand.Business.Core.Interfaces.Common.Logging;
-using Grand.Domain;
-using Grand.Domain.Customers;
-using Grand.Domain.Data;
-using Grand.Domain.Logging;
-
-namespace Grand.Business.Common.Services.Logging
-{
- /// <summary>
- /// Default logger
- /// </summary>
- public class DefaultLogger : ILogger
- {
- #region Fields
-
- private readonly IRepository<Log> _logRepository;
-
- #endregion
-
- #region Ctor
-
- /// <summary>
- /// Ctor
- /// </summary>
- /// <param name="logRepository">Log repository</param>
- public DefaultLogger(IRepository<Log> logRepository)
- {
- _logRepository = logRepository;
- }
-
- #endregion
-
- #region Methods
-
-
- /// <summary>
- /// Gets all log items
- /// </summary>
- /// <param name="fromUtc">Log item creation from; null to load all records</param>
- /// <param name="toUtc">Log item creation to; null to load all records</param>
- /// <param name="message">Message</param>
- /// <param name="logLevel">Log level; null to load all records</param>
- /// <param name="pageIndex">Page index</param>
- /// <param name="pageSize">Page size</param>
- /// <returns>Log item items</returns>
- public virtual async Task<IPagedList<Log>> GetAllLogs(DateTime? fromUtc = null, DateTime? toUtc = null,
- string message = "", LogLevel? logLevel = null,
- int pageIndex = 0, int pageSize = int.MaxValue)
- {
- var query = from p in _logRepository.Table
- select p;
-
- if (fromUtc.HasValue)
- query = query.Where(l => fromUtc.Value <= l.CreatedOnUtc);
- if (toUtc.HasValue)
- query = query.Where(l => toUtc.Value >= l.CreatedOnUtc);
- if (logLevel.HasValue)
- {
- query = query.Where(l => logLevel.Value == l.LogLevelId);
- }
- if (!string.IsNullOrEmpty(message))
- query = query.Where(l => l.ShortMessage.ToLower().Contains(message.ToLower()) || l.FullMessage.ToLower().Contains(message.ToLower()));
-
- query = query.OrderByDescending(x => x.CreatedOnUtc);
-
- var logs = await PagedList<Log>.Create(query, pageIndex, pageSize);
-
- return logs;
- }
-
- /// <summary>
- /// Gets a log item
- /// </summary>
- /// <param name="logId">Log item identifier</param>
- /// <returns>Log item</returns>
- public virtual Task<Log> GetLogById(string logId)
- {
- return _logRepository.GetByIdAsync(logId);
- }
-
- /// <summary>
- /// Get log items by identifiers
- /// </summary>
- /// <param name="logIds">Log item identifiers</param>
- /// <returns>Log items</returns>
- public virtual async Task<IList<Log>> GetLogByIds(string[] logIds)
- {
- if (logIds == null || logIds.Length == 0)
- return new List<Log>();
-
- var query = from l in _logRepository.Table
- where logIds.Contains(l.Id)
- select l;
-
- var logItems = await Task.FromResult(query.ToList());
- return logIds.Select(id => logItems.Find(x => x.Id == id)).Where(log => log != null).ToList();
- }
-
- /// <summary>
- /// Inserts a log item
- /// </summary>
- /// <param name="logLevel">Log level</param>
- /// <param name="shortMessage">The short message</param>
- /// <param name="fullMessage">The full message</param>
- /// <param name="customer">The customer to associate log record with</param>
- /// <param name="ipAddress">Ip address</param>
- /// <param name="pageUrl">Page url</param>
- /// <param name="referrerUrl">Referrer url</param>
- /// <returns>A log item</returns>
- public virtual Task InsertLog(LogLevel logLevel, string shortMessage, string fullMessage = "", Customer customer = null,
- string ipAddress = default, string pageUrl = default, string referrerUrl = default)
- {
- var log = new Log {
- LogLevelId = logLevel,
- ShortMessage = shortMessage,
- FullMessage = fullMessage,
- IpAddress = ipAddress,
- CustomerId = customer != null ? customer.Id : "",
- PageUrl = pageUrl,
- ReferrerUrl = referrerUrl,
- CreatedOnUtc = DateTime.UtcNow
- };
-
- _logRepository.InsertAsync(log);
-
- return Task.CompletedTask;
- }
-
- /// <summary>
- /// Deletes a log item
- /// </summary>
- /// <param name="log">Log item</param>
- public virtual async Task DeleteLog(Log log)
- {
- if (log == null)
- throw new ArgumentNullException(nameof(log));
-
- await _logRepository.DeleteAsync(log);
- }
-
- /// <summary>
- /// Clears a log
- /// </summary>
- public virtual async Task ClearLog()
- {
- await _logRepository.ClearAsync();
- }
-
- #endregion
- }
-}
diff --git a/src/Business/Grand.Business.Common/Services/Security/PermissionProvider.cs b/src/Business/Grand.Business.Common/Services/Security/PermissionProvider.cs
index c47f5f6d4..d3f35b2b0 100644
--- a/src/Business/Grand.Business.Common/Services/Security/PermissionProvider.cs
+++ b/src/Business/Grand.Business.Common/Services/Security/PermissionProvider.cs
@@ -67,7 +67,6 @@ namespace Grand.Business.Common.Services.Security
StandardPermission.ManageEmailAccounts,
StandardPermission.ManageStores,
StandardPermission.ManagePlugins,
- StandardPermission.ManageSystemLog,
StandardPermission.ManageMessageQueue,
StandardPermission.ManageMessageContactForm,
StandardPermission.ManageMaintenance,
@@ -153,7 +152,6 @@ namespace Grand.Business.Common.Services.Security
StandardPermission.ManageEmailAccounts,
StandardPermission.ManageStores,
StandardPermission.ManagePlugins,
- StandardPermission.ManageSystemLog,
StandardPermission.ManageMessageQueue,
StandardPermission.ManageMessageContactForm,
StandardPermission.ManageMaintenance,
diff --git a/src/Business/Grand.Business.Common/Startup/StartupApplication.cs b/src/Business/Grand.Business.Common/Startup/StartupApplication.cs
index a6976577e..1df08ee29 100644
--- a/src/Business/Grand.Business.Common/Startup/StartupApplication.cs
+++ b/src/Business/Grand.Business.Common/Startup/StartupApplication.cs
@@ -78,8 +78,6 @@ namespace Grand.Business.Common.Startup
private void RegisterLoggingService(IServiceCollection serviceCollection)
{
serviceCollection.AddScoped<ICustomerActivityService, CustomerActivityService>();
- serviceCollection.AddScoped<ILogger, DefaultLogger>();
-
}
private void RegisterSecurityService(IServiceCollection serviceCollection)
{
diff --git a/src/Business/Grand.Business.Core/Extensions/LoggingExtensions.cs b/src/Business/Grand.Business.Core/Extensions/LoggingExtensions.cs
deleted file mode 100644
index bb63f9de8..000000000
--- a/src/Business/Grand.Business.Core/Extensions/LoggingExtensions.cs
+++ /dev/null
@@ -1,32 +0,0 @@
-using Grand.Domain.Customers;
-using Grand.Domain.Logging;
-using Grand.Business.Core.Interfaces.Common.Logging;
-
-namespace Grand.Business.Core.Extensions
-{
- public static class LoggingExtensions
- {
- public static Task Information(this ILogger logger, string message, Exception exception = null, Customer customer = null)
- {
- return FilteredLog(logger, LogLevel.Information, message, exception, customer);
- }
- public static Task Warning(this ILogger logger, string message, Exception exception = null, Customer customer = null)
- {
- return FilteredLog(logger, LogLevel.Warning, message, exception, customer);
- }
- public static Task Error(this ILogger logger, string message, Exception exception = null, Customer customer = null)
- {
- return FilteredLog(logger, LogLevel.Error, message, exception, customer);
- }
- public static Task Fatal(this ILogger logger, string message, Exception exception = null, Customer customer = null)
- {
- return FilteredLog(logger, LogLevel.Fatal, message, exception, customer);
- }
-
- private static Task FilteredLog(ILogger logger, LogLevel level, string message, Exception exception = null, Customer customer = null)
- {
- var fullMessage = exception == null ? string.Empty : exception.ToString();
- return logger.InsertLog(level, message, fullMessage, customer);
- }
- }
-}
diff --git a/src/Business/Grand.Business.Core/Interfaces/Common/Logging/ILogger.cs b/src/Business/Grand.Business.Core/Interfaces/Common/Logging/ILogger.cs
deleted file mode 100644
index 1b63a7339..000000000
--- a/src/Business/Grand.Business.Core/Interfaces/Common/Logging/ILogger.cs
+++ /dev/null
@@ -1,68 +0,0 @@
-using Grand.Domain;
-using Grand.Domain.Customers;
-using Grand.Domain.Logging;
-
-namespace Grand.Business.Core.Interfaces.Common.Logging
-{
- /// <summary>
- /// Logger interface
- /// </summary>
- public interface ILogger
- {
- /// <summary>
- /// Gets all log items
- /// </summary>
- /// <param name="fromUtc">Log item creation from; null to load all records</param>
- /// <param name="toUtc">Log item creation to; null to load all records</param>
- /// <param name="message">Message</param>
- /// <param name="logLevel">Log level; null to load all records</param>
- /// <param name="pageIndex">Page index</param>
- /// <param name="pageSize">Page size</param>
- /// <returns>Log item items</returns>
- Task<IPagedList<Log>> GetAllLogs(DateTime? fromUtc = null, DateTime? toUtc = null,
- string message = "", LogLevel? logLevel = null,
- int pageIndex = 0, int pageSize = int.MaxValue);
-
- /// <summary>
- /// Gets a log item
- /// </summary>
- /// <param name="logId">Log item identifier</param>
- /// <returns>Log item</returns>
- Task<Log> GetLogById(string logId);
-
- /// <summary>
- /// Get log items by identifiers
- /// </summary>
- /// <param name="logIds">Log item identifiers</param>
- /// <returns>Log items</returns>
- Task<IList<Log>> GetLogByIds(string[] logIds);
-
- /// <summary>
- /// Inserts a log item
- /// </summary>
- /// <param name="logLevel">Log level</param>
- /// <param name="shortMessage">The short message</param>
- /// <param name="fullMessage">The full message</param>
- /// <param name="customer">The customer to associate log record with</param>
- /// <param name="ipAddress">Ip address</param>
- /// <param name="pageUrl">Page url</param>
- /// <param name="referrerUrl">Referrer url</param>
- /// <returns>A log item</returns>
- Task InsertLog(LogLevel logLevel, string shortMessage, string fullMessage = "", Customer customer = null,
- string ipAddress = default,
- string pageUrl = default,
- string referrerUrl = default);
-
- /// <summary>
- /// Deletes a log item
- /// </summary>
- /// <param name="log">Log item</param>
- Task DeleteLog(Log log);
-
- /// <summary>
- /// Clears a log
- /// </summary>
- Task ClearLog();
-
- }
-}
diff --git a/src/Business/Grand.Business.Core/Utilities/Common/Security/PermissionSystemName.cs b/src/Business/Grand.Business.Core/Utilities/Common/Security/PermissionSystemName.cs
index d15d799bd..fb7c0ba1a 100644
--- a/src/Business/Grand.Business.Core/Utilities/Common/Security/PermissionSystemName.cs
+++ b/src/Business/Grand.Business.Core/Utilities/Common/Security/PermissionSystemName.cs
@@ -60,7 +60,6 @@
public const string EmailAccounts = "ManageEmailAccounts";
public const string Stores = "ManageStores";
public const string Plugins = "ManagePlugins";
- public const string SystemLog = "ManageSystemLog";
public const string MessageQueue = "ManageMessageQueue";
public const string MessageContactForm = "ManageMessageContactForm";
public const string Maintenance = "ManageMaintenance";
diff --git a/src/Business/Grand.Business.Core/Utilities/Common/Security/StandardPermissionSystem.cs b/src/Business/Grand.Business.Core/Utilities/Common/Security/StandardPermissionSystem.cs
index 8c22fcdde..7cbb08eee 100644
--- a/src/Business/Grand.Business.Core/Utilities/Common/Security/StandardPermissionSystem.cs
+++ b/src/Business/Grand.Business.Core/Utilities/Common/Security/StandardPermissionSystem.cs
@@ -5,14 +5,7 @@ namespace Grand.Business.Core.Utilities.Common.Security
public static partial class StandardPermission
{
private static string CategorySystem => "System";
-
- public static readonly Permission ManageSystemLog = new()
- {
- Name = "Manage System Log",
- SystemName = PermissionSystemName.SystemLog,
- Area = "Admin area",
- Category = CategorySystem
- };
+
public static readonly Permission ManageMessageQueue = new()
{
Name = "Manage Message Queue",
diff --git a/src/Business/Grand.Business.Core/Utilities/System/StandardAdminSiteMap.cs b/src/Business/Grand.Business.Core/Utilities/System/StandardAdminSiteMap.cs
index ccacaa9dd..e47b1e9f6 100644
--- a/src/Business/Grand.Business.Core/Utilities/System/StandardAdminSiteMap.cs
+++ b/src/Business/Grand.Business.Core/Utilities/System/StandardAdminSiteMap.cs
@@ -1037,20 +1037,11 @@ namespace Grand.Business.Core.Utilities.System
new () {
SystemName = "System",
ResourceName = "Admin.System",
- PermissionNames = new List<string> { PermissionSystemName.SystemLog, PermissionSystemName.MessageQueue, PermissionSystemName.MessageContactForm,
+ PermissionNames = new List<string> { PermissionSystemName.MessageQueue, PermissionSystemName.MessageContactForm,
PermissionSystemName.Maintenance, PermissionSystemName.ScheduleTasks, PermissionSystemName.System },
IconClass = "icon-info",
DisplayOrder = 10,
ChildNodes = new List<AdminSiteMap> {
- new () {
- SystemName = "Log",
- ResourceName = "Admin.System.Log",
- PermissionNames = new List<string> { PermissionSystemName.SystemLog },
- ControllerName = "Logger",
- ActionName = "List",
- DisplayOrder = 0,
- IconClass = "fa fa-dot-circle-o"
- },
new () {
SystemName = "System information",
ResourceName = "Admin.System.SystemInfo",
diff --git a/src/Business/Grand.Business.Marketing/Services/PushNotifications/PushNotificationsService.cs b/src/Business/Grand.Business.Marketing/Services/PushNotifications/PushNotificationsService.cs
index ccea57e32..5a4e48d38 100644
--- a/src/Business/Grand.Business.Marketing/Services/PushNotifications/PushNotificationsService.cs
+++ b/src/Business/Grand.Business.Marketing/Services/PushNotifications/PushNotificationsService.cs
@@ -1,11 +1,11 @@
-using Grand.Business.Core.Interfaces.Common.Logging;
-using Grand.Business.Core.Interfaces.Marketing.PushNotifications;
+using Grand.Business.Core.Interfaces.Marketing.PushNotifications;
using Grand.Business.Marketing.Utilities;
using Grand.Domain;
using Grand.Domain.Data;
using Grand.Domain.PushNotifications;
using Grand.Infrastructure.Extensions;
using MediatR;
+using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System.Net.Http;
@@ -17,7 +17,7 @@ namespace Grand.Business.Marketing.Services.PushNotifications
private readonly IRepository<PushMessage> _pushMessagesRepository;
private readonly IMediator _mediator;
private readonly PushNotificationsSettings _pushNotificationsSettings;
- private readonly ILogger _logger;
+ private readonly ILogger<PushNotificationsService> _logger;
private readonly HttpClient _httpClient;
private const string FcmUrl = "https://fcm.googleapis.com/fcm/send";
@@ -27,7 +27,7 @@ namespace Grand.Business.Marketing.Services.PushNotifications
IRepository<PushMessage> pushMessagesRepository,
IMediator mediator,
PushNotificationsSettings pushNotificationsSettings,
- ILogger logger,
+ ILogger<PushNotificationsService> logger,
HttpClient httpClient)
{
_pushRegistrationRepository = pushRegistrationRepository;
@@ -192,7 +192,7 @@ namespace Grand.Business.Marketing.Services.PushNotifications
var responseString = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode)
{
- await _logger.InsertLog(Domain.Logging.LogLevel.Error, "Error occured while sending push notification.", responseString);
+ _logger.LogError("Error occured while sending push notification {ResponseString}", responseString);
return (false, responseString);
}
diff --git a/src/Business/Grand.Business.Storage/Services/AmazonPictureService.cs b/src/Business/Grand.Business.Storage/Services/AmazonPictureService.cs
index 5eaa02807..962ff17b1 100644
--- a/src/Business/Grand.Business.Storage/Services/AmazonPictureService.cs
+++ b/src/Business/Grand.Business.Storage/Services/AmazonPictureService.cs
@@ -2,13 +2,13 @@
using Amazon.Runtime;
using Amazon.S3;
using Amazon.S3.Model;
-using Grand.Business.Core.Interfaces.Common.Logging;
using Grand.Business.Core.Interfaces.Storage;
using Grand.Domain.Data;
using Grand.Domain.Media;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Configuration;
using MediatR;
+using Microsoft.Extensions.Logging;
using System.Net;
namespace Grand.Business.Storage.Services
@@ -31,7 +31,7 @@ namespace Grand.Business.Storage.Services
#region Ctor
public AmazonPictureService(IRepository<Picture> pictureRepository,
- ILogger logger,
+ ILogger<AmazonPictureService> logger,
IMediator mediator,
ICacheBase cacheBase,
IMediaFileStore mediaFileStore,
diff --git a/src/Business/Grand.Business.Storage/Services/AzurePictureService.cs b/src/Business/Grand.Business.Storage/Services/AzurePictureService.cs
index 5eca8f5e6..26b3fd71e 100644
--- a/src/Business/Grand.Business.Storage/Services/AzurePictureService.cs
+++ b/src/Business/Grand.Business.Storage/Services/AzurePictureService.cs
@@ -1,6 +1,5 @@
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
-using Grand.Business.Core.Interfaces.Common.Logging;
using Grand.Business.Core.Interfaces.Messages;
using Grand.Business.Core.Interfaces.Storage;
using Grand.Domain.Data;
@@ -8,6 +7,7 @@ using Grand.Domain.Media;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Configuration;
using MediatR;
+using Microsoft.Extensions.Logging;
namespace Grand.Business.Storage.Services
{
@@ -27,7 +27,7 @@ namespace Grand.Business.Storage.Services
#region Ctor
public AzurePictureService(IRepository<Picture> pictureRepository,
- ILogger logger,
+ ILogger<AzurePictureService> logger,
IMediator mediator,
ICacheBase cacheBase,
IMediaFileStore mediaFileStore,
diff --git a/src/Business/Grand.Business.Storage/Services/PictureService.cs b/src/Business/Grand.Business.Storage/Services/PictureService.cs
index 6f3af1cb1..51bc3233f 100644
--- a/src/Business/Grand.Business.Storage/Services/PictureService.cs
+++ b/src/Business/Grand.Business.Storage/Services/PictureService.cs
@@ -1,5 +1,4 @@
using Grand.Business.Core.Extensions;
-using Grand.Business.Core.Interfaces.Common.Logging;
using Grand.Business.Core.Interfaces.Storage;
using Grand.Domain;
using Grand.Domain.Common;
@@ -10,6 +9,7 @@ using Grand.Infrastructure.Caching.Constants;
using Grand.Infrastructure.Extensions;
using Grand.SharedKernel.Extensions;
using MediatR;
+using Microsoft.Extensions.Logging;
using SkiaSharp;
using System.Linq.Expressions;
@@ -24,7 +24,7 @@ namespace Grand.Business.Storage.Services
#region Fields
private readonly IRepository<Picture> _pictureRepository;
- private readonly ILogger _logger;
+ private readonly ILogger<PictureService> _logger;
private readonly IMediator _mediator;
private readonly ICacheBase _cacheBase;
private readonly IMediaFileStore _mediaFileStore;
@@ -46,7 +46,7 @@ namespace Grand.Business.Storage.Services
/// <param name="mediaSettings">Media settings</param>
/// <param name="storageSettings">Storage settings</param>
public PictureService(IRepository<Picture> pictureRepository,
- ILogger logger,
+ ILogger<PictureService> logger,
IMediator mediator,
ICacheBase cacheBase,
IMediaFileStore mediaFileStore,
@@ -130,7 +130,7 @@ namespace Grand.Business.Storage.Services
}
catch (Exception ex)
{
- _logger.InsertLog(Domain.Logging.LogLevel.Error, ex.Message);
+ _logger.LogError(ex, ex.Message);
}
}
return Task.CompletedTask;
@@ -212,12 +212,12 @@ namespace Grand.Business.Storage.Services
File.WriteAllBytes(file, binary ?? Array.Empty<byte>());
}
else
- _logger.InsertLog(Domain.Logging.LogLevel.Error, "Directory thumb not exist.");
+ _logger.LogError("Directory thumb not exist");
}
catch (Exception ex)
{
- _logger.InsertLog(Domain.Logging.LogLevel.Error, ex.Message);
+ _logger.LogError(ex, ex.Message);
}
return Task.CompletedTask;
}
@@ -499,7 +499,7 @@ namespace Grand.Business.Storage.Services
}
catch (Exception ex)
{
- _ = _logger.Error(ex.Message, ex);
+ _logger.LogError(ex, ex.Message);
}
}
await Task.CompletedTask;
@@ -699,7 +699,7 @@ namespace Grand.Business.Storage.Services
File.WriteAllBytes(filepath, pictureBinary);
}
else
- _ = _logger.Error("Directory path not exist.");
+ _logger.LogError("Directory path not exist");
return Task.CompletedTask;
}
@@ -866,7 +866,7 @@ namespace Grand.Business.Storage.Services
}
catch (Exception ex)
{
- _logger.Error($"ApplyResize - format {format}", ex);
+ _logger.LogError(ex, "ApplyResize - format {Format}", format);
return null;
}
diff --git a/src/Business/Grand.Business.System/Services/BackgroundServices/ScheduleTasks/ClearLogScheduleTask.cs b/src/Business/Grand.Business.System/Services/BackgroundServices/ScheduleTasks/ClearLogScheduleTask.cs
deleted file mode 100644
index a869cb738..000000000
--- a/src/Business/Grand.Business.System/Services/BackgroundServices/ScheduleTasks/ClearLogScheduleTask.cs
+++ /dev/null
@@ -1,25 +0,0 @@
-using Grand.Business.Core.Interfaces.Common.Logging;
-using Grand.Business.Core.Interfaces.System.ScheduleTasks;
-
-namespace Grand.Business.System.Services.BackgroundServices.ScheduleTasks
-{
- /// <summary>
- /// Represents a task to clear Log table
- /// </summary>
- public class ClearLogScheduleTask : IScheduleTask
- {
- private readonly ILogger _logger;
- public ClearLogScheduleTask(ILogger logger)
- {
- _logger = logger;
- }
-
- /// <summary>
- /// Executes a task
- /// </summary>
- public async Task Execute()
- {
- await _logger.ClearLog();
- }
- }
-}
diff --git a/src/Business/Grand.Business.System/Services/BackgroundServices/ScheduleTasks/EndAuctionsTask.cs b/src/Business/Grand.Business.System/Services/BackgroundServices/ScheduleTasks/EndAuctionsTask.cs
index 5bf257f5d..4471ea37d 100644
--- a/src/Business/Grand.Business.System/Services/BackgroundServices/ScheduleTasks/EndAuctionsTask.cs
+++ b/src/Business/Grand.Business.System/Services/BackgroundServices/ScheduleTasks/EndAuctionsTask.cs
@@ -1,11 +1,11 @@
using Grand.Business.Core.Interfaces.Catalog.Products;
using Grand.Business.Core.Interfaces.Checkout.Orders;
-using Grand.Business.Core.Interfaces.Common.Logging;
using Grand.Business.Core.Interfaces.Customers;
using Grand.Business.Core.Interfaces.Messages;
using Grand.Business.Core.Interfaces.System.ScheduleTasks;
using Grand.Business.Core.Utilities.Checkout;
using Grand.Domain.Localization;
+using Microsoft.Extensions.Logging;
namespace Grand.Business.System.Services.BackgroundServices.ScheduleTasks
{
@@ -19,11 +19,11 @@ namespace Grand.Business.System.Services.BackgroundServices.ScheduleTasks
private readonly LanguageSettings _languageSettings;
private readonly IShoppingCartService _shoppingCartService;
private readonly ICustomerService _customerService;
- private readonly ILogger _logger;
+ private readonly ILogger<EndAuctionsTask> _logger;
public EndAuctionsTask(IAuctionService auctionService,
IMessageProviderService messageProviderService, LanguageSettings translationService, IShoppingCartService shoppingCartService,
- ICustomerService customerService, ILogger logger)
+ ICustomerService customerService, ILogger<EndAuctionsTask> logger)
{
_auctionService = auctionService;
_messageProviderService = messageProviderService;
@@ -64,7 +64,7 @@ namespace Grand.Business.System.Services.BackgroundServices.ScheduleTasks
}
else
{
- await _logger.InsertLog(Domain.Logging.LogLevel.Error, $"EndAuctionTask - Product {auctionToEnd.Name}", string.Join(",", warnings.ToArray()));
+ _logger.LogInformation("EndAuctionTask - Product {Name} - warnings {Join}", auctionToEnd.Name, string.Join(",", warnings.ToArray()));
}
}
}
diff --git a/src/Business/Grand.Business.System/Services/BackgroundServices/ScheduleTasks/QueuedMessagesSendScheduleTask.cs b/src/Business/Grand.Business.System/Services/BackgroundServices/ScheduleTasks/QueuedMessagesSendScheduleTask.cs
index d688770b1..a3251b525 100644
--- a/src/Business/Grand.Business.System/Services/BackgroundServices/ScheduleTasks/QueuedMessagesSendScheduleTask.cs
+++ b/src/Business/Grand.Business.System/Services/BackgroundServices/ScheduleTasks/QueuedMessagesSendScheduleTask.cs
@@ -1,7 +1,6 @@
using Grand.Business.Core.Interfaces.Messages;
using Grand.Business.Core.Interfaces.System.ScheduleTasks;
-using Grand.Business.Core.Interfaces.Common.Logging;
-using Grand.Business.Core.Extensions;
+using Microsoft.Extensions.Logging;
namespace Grand.Business.System.Services.BackgroundServices.ScheduleTasks
{
@@ -12,12 +11,12 @@ namespace Grand.Business.System.Services.BackgroundServices.ScheduleTasks
{
private readonly IQueuedEmailService _queuedEmailService;
private readonly IEmailSender _emailSender;
- private readonly ILogger _logger;
+ private readonly ILogger<QueuedMessagesSendScheduleTask> _logger;
private readonly IEmailAccountService _emailAccountService;
public QueuedMessagesSendScheduleTask(IQueuedEmailService queuedEmailService,
- IEmailSender emailSender, ILogger logger, IEmailAccountService emailAccountService)
+ IEmailSender emailSender, ILogger<QueuedMessagesSendScheduleTask> logger, IEmailAccountService emailAccountService)
{
_queuedEmailService = queuedEmailService;
_emailSender = emailSender;
@@ -63,7 +62,7 @@ namespace Grand.Business.System.Services.BackgroundServices.ScheduleTasks
}
catch (Exception exc)
{
- _ = _logger.Error($"Error sending e-mail. {exc.Message}", exc);
+ _logger.LogError(exc, "Error sending e-mail. {ExcMessage}", exc.Message);
}
finally
{
diff --git a/src/Business/Grand.Business.System/Services/Installation/InstallationService.cs b/src/Business/Grand.Business.System/Services/Installation/InstallationService.cs
index 452065a0f..0864338d2 100644
--- a/src/Business/Grand.Business.System/Services/Installation/InstallationService.cs
+++ b/src/Business/Grand.Business.System/Services/Installation/InstallationService.cs
@@ -60,7 +60,6 @@ namespace Grand.Business.System.Services.Installation
private readonly IRepository<TaxCategory> _taxCategoryRepository;
private readonly IRepository<Language> _languageRepository;
private readonly IRepository<TranslationResource> _lsrRepository;
- private readonly IRepository<Log> _logRepository;
private readonly IRepository<Currency> _currencyRepository;
private readonly IRepository<Customer> _customerRepository;
private readonly IRepository<CustomerGroup> _customerGroupRepository;
@@ -169,7 +168,6 @@ namespace Grand.Business.System.Services.Installation
IRepository<TaxCategory> taxCategoryRepository,
IRepository<Language> languageRepository,
IRepository<TranslationResource> lsrRepository,
- IRepository<Log> logRepository,
IRepository<Currency> currencyRepository,
IRepository<Customer> customerRepository,
IRepository<CustomerGroup> customerGroupRepository,
@@ -266,7 +264,6 @@ namespace Grand.Business.System.Services.Installation
_taxCategoryRepository = taxCategoryRepository;
_languageRepository = languageRepository;
_lsrRepository = lsrRepository;
- _logRepository = logRepository;
_currencyRepository = currencyRepository;
_customerRepository = customerRepository;
_customerGroupRepository = customerGroupRepository;
@@ -588,9 +585,6 @@ namespace Grand.Business.System.Services.Installation
await dbContext.CreateIndex(_newslettersubscriptionRepository, OrderBuilder<NewsLetterSubscription>.Create().Ascending(x => x.CustomerId), "CustomerId");
await dbContext.CreateIndex(_newslettersubscriptionRepository, OrderBuilder<NewsLetterSubscription>.Create().Ascending(x => x.Email), "Email");
- //Log
- await dbContext.CreateIndex(_logRepository, OrderBuilder<Log>.Create().Ascending(x => x.CreatedOnUtc), "CreatedOnUtc");
-
//Campaign
await dbContext.CreateIndex(_campaignRepository, OrderBuilder<Campaign>.Create().Ascending(x => x.CreatedOnUtc), "CreatedOnUtc");
await dbContext.CreateIndex(_campaignHistoryRepository, OrderBuilder<CampaignHistory>.Create().Ascending(x => x.CampaignId).Descending(x => x.CreatedDateUtc), "CampaignId");
diff --git a/src/Business/Grand.Business.System/Services/Migrations/1.1/MigrationSystemPermission.cs b/src/Business/Grand.Business.System/Services/Migrations/1.1/MigrationSystemPermission.cs
index 906a8c80f..f87861262 100644
--- a/src/Business/Grand.Business.System/Services/Migrations/1.1/MigrationSystemPermission.cs
+++ b/src/Business/Grand.Business.System/Services/Migrations/1.1/MigrationSystemPermission.cs
@@ -1,11 +1,11 @@
using Grand.Business.Core.Interfaces.Common.Directory;
-using Grand.Business.Core.Interfaces.Common.Logging;
using Grand.Business.Core.Utilities.Common.Security;
using Grand.Domain.Customers;
using Grand.Domain.Data;
using Grand.Domain.Permissions;
using Grand.Infrastructure.Migrations;
using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging;
namespace Grand.Business.System.Services.Migrations._1._1
{
@@ -26,7 +26,7 @@ namespace Grand.Business.System.Services.Migrations._1._1
{
var repository = serviceProvider.GetRequiredService<IRepository<Permission>>();
var groupService = serviceProvider.GetRequiredService<IGroupService>();
- var logService = serviceProvider.GetRequiredService<ILogger>();
+ var logService = serviceProvider.GetRequiredService<ILogger<MigrationSystemPermission>>();
try
{
@@ -46,7 +46,7 @@ namespace Grand.Business.System.Services.Migrations._1._1
}
catch (Exception ex)
{
- logService.InsertLog(Domain.Logging.LogLevel.Error, "UpgradeProcess - UpdateAdminSiteMap", ex.Message).GetAwaiter().GetResult();
+ logService.LogError(ex, "UpgradeProcess - UpdateAdminSiteMap");
}
return true;
}
diff --git a/src/Business/Grand.Business.System/Services/Migrations/1.1/MigrationUpdateAdminSiteMap.cs b/src/Business/Grand.Business.System/Services/Migrations/1.1/MigrationUpdateAdminSiteMap.cs
index d7d0a2e7a..fd2f90a9e 100644
--- a/src/Business/Grand.Business.System/Services/Migrations/1.1/MigrationUpdateAdminSiteMap.cs
+++ b/src/Business/Grand.Business.System/Services/Migrations/1.1/MigrationUpdateAdminSiteMap.cs
@@ -1,8 +1,8 @@
-using Grand.Business.Core.Interfaces.Common.Logging;
-using Grand.Business.Core.Utilities.Common.Security;
+using Grand.Business.Core.Utilities.Common.Security;
using Grand.Domain.Data;
using Grand.Infrastructure.Migrations;
using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging;
namespace Grand.Business.System.Services.Migrations._1._1
{
@@ -23,14 +23,14 @@ namespace Grand.Business.System.Services.Migrations._1._1
public bool UpgradeProcess(IDatabaseContext database, IServiceProvider serviceProvider)
{
var repository = serviceProvider.GetRequiredService<IRepository<Domain.Admin.AdminSiteMap>>();
- var logService = serviceProvider.GetRequiredService<ILogger>();
+ var logService = serviceProvider.GetRequiredService<ILogger<MigrationUpdateAdminSiteMap>>();
try
{
var sitemapSystem = repository.Table.FirstOrDefault(x => x.SystemName == "System");
if (sitemapSystem != null)
{
- sitemapSystem.PermissionNames = new List<string> { PermissionSystemName.SystemLog, PermissionSystemName.MessageQueue, PermissionSystemName.MessageContactForm,
+ sitemapSystem.PermissionNames = new List<string> { PermissionSystemName.MessageQueue, PermissionSystemName.MessageContactForm,
PermissionSystemName.Maintenance, PermissionSystemName.ScheduleTasks, PermissionSystemName.System };
var childnodeDevTools = sitemapSystem.ChildNodes.FirstOrDefault(x => x.SystemName == "Developer tools");
if (childnodeDevTools != null)
@@ -86,7 +86,7 @@ namespace Grand.Business.System.Services.Migrations._1._1
}
catch (Exception ex)
{
- logService.InsertLog(Domain.Logging.LogLevel.Error, "UpgradeProcess - UpdateAdminSiteMap", ex.Message).GetAwaiter().GetResult();
+ logService.LogError(ex, "UpgradeProcess - UpdateAdminSiteMap");
}
return true;
}
diff --git a/src/Business/Grand.Business.System/Services/Migrations/1.1/MigrationUpdateLogoSettings.cs b/src/Business/Grand.Business.System/Services/Migrations/1.1/MigrationUpdateLogoSettings.cs
index cc5c3cea3..07bc77b72 100644
--- a/src/Business/Grand.Business.System/Services/Migrations/1.1/MigrationUpdateLogoSettings.cs
+++ b/src/Business/Grand.Business.System/Services/Migrations/1.1/MigrationUpdateLogoSettings.cs
@@ -1,5 +1,4 @@
using Grand.Business.Core.Interfaces.Common.Configuration;
-using Grand.Business.Core.Interfaces.Common.Logging;
using Grand.Business.Core.Interfaces.Storage;
using Grand.Domain.Data;
using Grand.Domain.Stores;
@@ -7,6 +6,7 @@ using Grand.Infrastructure.Migrations;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging;
using System.Text.Json;
namespace Grand.Business.System.Services.Migrations._1._1
@@ -30,7 +30,7 @@ namespace Grand.Business.System.Services.Migrations._1._1
var repository = serviceProvider.GetRequiredService<IRepository<Domain.Configuration.Setting>>();
var storeSettings = repository.Table.Where(x => x.Name == "storeinformationsettings");
var settingService = serviceProvider.GetRequiredService<ISettingService>();
- var logService = serviceProvider.GetRequiredService<ILogger>();
+ var logService = serviceProvider.GetRequiredService<ILogger<MigrationUpdateLogoSettings>>();
var hostingEnvironment = serviceProvider.GetRequiredService<IWebHostEnvironment>();
//update logo settings
@@ -56,7 +56,7 @@ namespace Grand.Business.System.Services.Migrations._1._1
}
catch(Exception ex)
{
- logService.InsertLog(Domain.Logging.LogLevel.Error, "UpgradeProcess - MigrationUpdateSettings", ex.Message).GetAwaiter().GetResult();
+ logService.LogError(ex, "UpgradeProcess - MigrationUpdateSettings");
}
return true;
}
diff --git a/src/Business/Grand.Business.System/Services/Migrations/1.1/MigrationUpdateMediaSettings.cs b/src/Business/Grand.Business.System/Services/Migrations/1.1/MigrationUpdateMediaSettings.cs
index d27d52b2a..e9ad8ab55 100644
--- a/src/Business/Grand.Business.System/Services/Migrations/1.1/MigrationUpdateMediaSettings.cs
+++ b/src/Business/Grand.Business.System/Services/Migrations/1.1/MigrationUpdateMediaSettings.cs
@@ -1,9 +1,9 @@
using Grand.Business.Core.Interfaces.Common.Configuration;
-using Grand.Business.Core.Interfaces.Common.Logging;
using Grand.Domain.Data;
using Grand.Domain.Media;
using Grand.Infrastructure.Migrations;
using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging;
using System.Text.Json;
namespace Grand.Business.System.Services.Migrations._1._1
@@ -27,7 +27,7 @@ namespace Grand.Business.System.Services.Migrations._1._1
var repository = serviceProvider.GetRequiredService<IRepository<Domain.Configuration.Setting>>();
var mediaSettings = repository.Table.FirstOrDefault(x => x.Name == "mediasettings");
var settingService = serviceProvider.GetRequiredService<ISettingService>();
- var logService = serviceProvider.GetRequiredService<ILogger>();
+ var logService = serviceProvider.GetRequiredService<ILogger<MigrationUpdateMediaSettings>>();
try
{
@@ -43,7 +43,7 @@ namespace Grand.Business.System.Services.Migrations._1._1
}
catch (Exception ex)
{
- logService.InsertLog(Domain.Logging.LogLevel.Error, "UpgradeProcess - MigrationUpdateMediaSettings", ex.Message).GetAwaiter().GetResult();
+ logService.LogError(ex, "UpgradeProcess - MigrationUpdateMediaSettings");
}
return true;
}
diff --git a/src/Business/Grand.Business.System/Services/Migrations/1.1/MigrationUpdateStore.cs b/src/Business/Grand.Business.System/Services/Migrations/1.1/MigrationUpdateStore.cs
index a32342774..3f1fafb33 100644
--- a/src/Business/Grand.Business.System/Services/Migrations/1.1/MigrationUpdateStore.cs
+++ b/src/Business/Grand.Business.System/Services/Migrations/1.1/MigrationUpdateStore.cs
@@ -1,8 +1,8 @@
-using Grand.Business.Core.Interfaces.Common.Logging;
-using Grand.Domain.Data;
+using Grand.Domain.Data;
using Grand.Domain.Stores;
using Grand.Infrastructure.Migrations;
using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging;
namespace Grand.Business.System.Services.Migrations._1._1
{
@@ -22,7 +22,7 @@ namespace Grand.Business.System.Services.Migrations._1._1
public bool UpgradeProcess(IDatabaseContext database, IServiceProvider serviceProvider)
{
var repository = serviceProvider.GetRequiredService<IRepository<Store>>();
- var logService = serviceProvider.GetRequiredService<ILogger>();
+ var logService = serviceProvider.GetRequiredService<ILogger<MigrationUpdateStore>>();
try
{
foreach (var store in repository.Table)
@@ -43,7 +43,7 @@ namespace Grand.Business.System.Services.Migrations._1._1
}
catch (Exception ex)
{
- logService.InsertLog(Domain.Logging.LogLevel.Error, "UpgradeProcess - MigrationUpdateStore", ex.Message).GetAwaiter().GetResult();
+ logService.LogError(ex, "UpgradeProcess - MigrationUpdateStore");
}
return true;
}
diff --git a/src/Business/Grand.Business.System/Services/Migrations/2.1/MigrationActivityLogTypes.cs b/src/Business/Grand.Business.System/Services/Migrations/2.1/MigrationActivityLogTypes.cs
index a8d322685..196e1004c 100644
--- a/src/Business/Grand.Business.System/Services/Migrations/2.1/MigrationActivityLogTypes.cs
+++ b/src/Business/Grand.Business.System/Services/Migrations/2.1/MigrationActivityLogTypes.cs
@@ -1,8 +1,8 @@
-using Grand.Business.Core.Interfaces.Common.Logging;
-using Grand.Domain.Data;
+using Grand.Domain.Data;
using Grand.Domain.Logging;
using Grand.Infrastructure.Migrations;
using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging;
namespace Grand.Business.System.Services.Migrations._2._1
{
@@ -23,7 +23,7 @@ namespace Grand.Business.System.Services.Migrations._2._1
public bool UpgradeProcess(IDatabaseContext database, IServiceProvider serviceProvider)
{
var repository = serviceProvider.GetRequiredService<IRepository<ActivityLogType>>();
- var logService = serviceProvider.GetRequiredService<ILogger>();
+ var logService = serviceProvider.GetRequiredService<ILogger<MigrationActivityLogTypes>>();
try
{
var activityLogTypes = repository
@@ -46,7 +46,7 @@ namespace Grand.Business.System.Services.Migrations._2._1
}
catch (Exception ex)
{
- logService.InsertLog(LogLevel.Error, "UpgradeProcess - RemoveOldActivityLogType", ex.Message).GetAwaiter().GetResult();
+ logService.LogError(ex, "UpgradeProcess - RemoveOldActivityLogType");
}
return true;
diff --git a/src/Business/Grand.Business.System/Services/Migrations/2.1/MigrationProductRating.cs b/src/Business/Grand.Business.System/Services/Migrations/2.1/MigrationProductRating.cs
index 25897c987..2ed03265a 100644
--- a/src/Business/Grand.Business.System/Services/Migrations/2.1/MigrationProductRating.cs
+++ b/src/Business/Grand.Business.System/Services/Migrations/2.1/MigrationProductRating.cs
@@ -1,9 +1,8 @@
-using Grand.Business.Core.Interfaces.Common.Logging;
-using Grand.Domain.Catalog;
+using Grand.Domain.Catalog;
using Grand.Domain.Data;
-using Grand.Domain.Logging;
using Grand.Infrastructure.Migrations;
using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging;
namespace Grand.Business.System.Services.Migrations._2._1
{
@@ -24,7 +23,7 @@ namespace Grand.Business.System.Services.Migrations._2._1
public bool UpgradeProcess(IDatabaseContext database, IServiceProvider serviceProvider)
{
var productRepository = serviceProvider.GetRequiredService<IRepository<Product>>();
- var logService = serviceProvider.GetRequiredService<ILogger>();
+ var logService = serviceProvider.GetRequiredService<ILogger<MigrationProductRating>>();
try
{
foreach (var product in productRepository.Table)
@@ -37,7 +36,7 @@ namespace Grand.Business.System.Services.Migrations._2._1
}
catch (Exception ex)
{
- logService.InsertLog(LogLevel.Error, "UpgradeProcess - RemoveOldActivityLogType", ex.Message).GetAwaiter().GetResult();
+ logService.LogError(ex, "UpgradeProcess - RemoveOldActivityLogType");
}
return true;
diff --git a/src/Business/Grand.Business.System/Services/Migrations/2.1/MigrationScheduleTasks.cs b/src/Business/Grand.Business.System/Services/Migrations/2.1/MigrationScheduleTasks.cs
index 516300222..1fbd3de9d 100644
--- a/src/Business/Grand.Business.System/Services/Migrations/2.1/MigrationScheduleTasks.cs
+++ b/src/Business/Grand.Business.System/Services/Migrations/2.1/MigrationScheduleTasks.cs
@@ -1,9 +1,8 @@
-using Grand.Business.Core.Interfaces.Common.Logging;
-using Grand.Domain.Data;
-using Grand.Domain.Logging;
+using Grand.Domain.Data;
using Grand.Domain.Tasks;
using Grand.Infrastructure.Migrations;
using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging;
namespace Grand.Business.System.Services.Migrations._2._1
{
@@ -24,7 +23,7 @@ namespace Grand.Business.System.Services.Migrations._2._1
public bool UpgradeProcess(IDatabaseContext database, IServiceProvider serviceProvider)
{
var repository = serviceProvider.GetRequiredService<IRepository<ScheduleTask>>();
- var logService = serviceProvider.GetRequiredService<ILogger>();
+ var logService = serviceProvider.GetRequiredService<ILogger<MigrationScheduleTasks>>();
try
{
var scheduleTasks = repository
@@ -45,7 +44,7 @@ namespace Grand.Business.System.Services.Migrations._2._1
}
catch (Exception ex)
{
- logService.InsertLog(LogLevel.Error, "UpgradeProcess - RemoveOldScheduleTasks", ex.Message).GetAwaiter().GetResult();
+ logService.LogError(ex, "UpgradeProcess - RemoveOldScheduleTasks");
}
return true;
diff --git a/src/Business/Grand.Business.System/Services/Migrations/2.1/MigrationSystemPermission.cs b/src/Business/Grand.Business.System/Services/Migrations/2.1/MigrationSystemPermission.cs
index 3e53c99e3..c76441c73 100644
--- a/src/Business/Grand.Business.System/Services/Migrations/2.1/MigrationSystemPermission.cs
+++ b/src/Business/Grand.Business.System/Services/Migrations/2.1/MigrationSystemPermission.cs
@@ -1,8 +1,8 @@
-using Grand.Business.Core.Interfaces.Common.Logging;
-using Grand.Domain.Data;
+using Grand.Domain.Data;
using Grand.Domain.Permissions;
using Grand.Infrastructure.Migrations;
using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging;
namespace Grand.Business.System.Services.Migrations._2._1
{
@@ -22,7 +22,7 @@ namespace Grand.Business.System.Services.Migrations._2._1
public bool UpgradeProcess(IDatabaseContext database, IServiceProvider serviceProvider)
{
var repository = serviceProvider.GetRequiredService<IRepository<Permission>>();
- var logService = serviceProvider.GetRequiredService<ILogger>();
+ var logService = serviceProvider.GetRequiredService<ILogger<MigrationSystemPermission>>();
try
{
var permissionManageActions = repository.Table.FirstOrDefault(x => x.SystemName == "ManageActions");
@@ -33,7 +33,7 @@ namespace Grand.Business.System.Services.Migrations._2._1
}
catch (Exception ex)
{
- logService.InsertLog(Domain.Logging.LogLevel.Error, "UpgradeProcess - RemoveOldPermissions", ex.Message).GetAwaiter().GetResult();
+ logService.LogError(ex, "UpgradeProcess - RemoveOldPermissions");
}
return true;
}
diff --git a/src/Business/Grand.Business.System/Services/Migrations/2.1/MigrationUpdateAdminSiteMap.cs b/src/Business/Grand.Business.System/Services/Migrations/2.1/MigrationUpdateAdminSiteMap.cs
index 9bfe3cf65..ae5778013 100644
--- a/src/Business/Grand.Business.System/Services/Migrations/2.1/MigrationUpdateAdminSiteMap.cs
+++ b/src/Business/Grand.Business.System/Services/Migrations/2.1/MigrationUpdateAdminSiteMap.cs
@@ -1,8 +1,8 @@
-using Grand.Business.Core.Interfaces.Common.Logging;
-using Grand.Business.Core.Utilities.Common.Security;
+using Grand.Business.Core.Utilities.Common.Security;
using Grand.Domain.Data;
using Grand.Infrastructure.Migrations;
using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging;
namespace Grand.Business.System.Services.Migrations._2._1
{
@@ -23,7 +23,7 @@ namespace Grand.Business.System.Services.Migrations._2._1
public bool UpgradeProcess(IDatabaseContext database, IServiceProvider serviceProvider)
{
var repository = serviceProvider.GetRequiredService<IRepository<Domain.Admin.AdminSiteMap>>();
- var logService = serviceProvider.GetRequiredService<ILogger>();
+ var logService = serviceProvider.GetRequiredService<ILogger<MigrationUpdateAdminSiteMap>>();
try
{
@@ -43,7 +43,7 @@ namespace Grand.Business.System.Services.Migrations._2._1
}
catch (Exception ex)
{
- logService.InsertLog(Domain.Logging.LogLevel.Error, "UpgradeProcess - UpdateAdminSiteMap", ex.Message).GetAwaiter().GetResult();
+ logService.LogError(ex, "UpgradeProcess - UpdateAdminSiteMap");
}
return true;
}
diff --git a/src/Business/Grand.Business.System/Services/Migrations/2.2/MigrationScheduleTasks.cs b/src/Business/Grand.Business.System/Services/Migrations/2.2/MigrationScheduleTasks.cs
new file mode 100644
index 000000000..223e7db8a
--- /dev/null
+++ b/src/Business/Grand.Business.System/Services/Migrations/2.2/MigrationScheduleTasks.cs
@@ -0,0 +1,40 @@
+using Grand.Domain.Data;
+using Grand.Domain.Tasks;
+using Grand.Infrastructure.Migrations;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging;
+
+namespace Grand.Business.System.Services.Migrations._2._2
+{
+ public class MigrationScheduleTasks : IMigration
+ {
+ public int Priority => 0;
+ public DbVersion Version => new(2, 2);
+ public Guid Identity => new("17E09B6B-A8BB-45B4-B13D-4D76711DCD7A");
+ public string Name => "Remove ScheduleTask - Clear log";
+
+ /// <summary>
+ /// Upgrade process
+ /// </summary>
+ /// <param name="database"></param>
+ /// <param name="serviceProvider"></param>
+ /// <returns></returns>
+ public bool UpgradeProcess(IDatabaseContext database, IServiceProvider serviceProvider)
+ {
+ var repository = serviceProvider.GetRequiredService<IRepository<ScheduleTask>>();
+ var logService = serviceProvider.GetRequiredService<ILogger<MigrationScheduleTasks>>();
+ try
+ {
+ var scheduleTask = repository.Table.FirstOrDefault(x => x.ScheduleTaskName == "Clear log");
+ if (scheduleTask != null)
+ repository.Delete(scheduleTask);
+ }
+ catch (Exception ex)
+ {
+ logService.LogError(ex, "UpgradeProcess - Remove ScheduleTasks");
+ }
+
+ return true;
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.System/Services/Migrations/2.2/MigrationSystemPermission.cs b/src/Business/Grand.Business.System/Services/Migrations/2.2/MigrationSystemPermission.cs
index 2e7b9b1be..84772e565 100644
--- a/src/Business/Grand.Business.System/Services/Migrations/2.2/MigrationSystemPermission.cs
+++ b/src/Business/Grand.Business.System/Services/Migrations/2.2/MigrationSystemPermission.cs
@@ -1,11 +1,11 @@
using Grand.Business.Core.Interfaces.Common.Directory;
-using Grand.Business.Core.Interfaces.Common.Logging;
using Grand.Business.Core.Utilities.Common.Security;
using Grand.Domain.Customers;
using Grand.Domain.Data;
using Grand.Domain.Permissions;
using Grand.Infrastructure.Migrations;
using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging;
namespace Grand.Business.System.Services.Migrations._2._2
{
@@ -13,8 +13,8 @@ namespace Grand.Business.System.Services.Migrations._2._2
{
public int Priority => 0;
public DbVersion Version => new(2, 2);
- public Guid Identity => new("BFBAEB25-288A-4114-BC0D-0272B57B1725");
- public string Name => "Install new permission - ManageAccessVendorPanel";
+ public Guid Identity => new("3F4E87C6-8ECE-4034-8211-39C3D3EBC567");
+ public string Name => "Install new permission - ManageAccessVendorPanel / Delete permission - ManageSystemLog";
/// <summary>
/// Upgrade process
@@ -26,7 +26,7 @@ namespace Grand.Business.System.Services.Migrations._2._2
{
var repository = serviceProvider.GetRequiredService<IRepository<Permission>>();
var groupService = serviceProvider.GetRequiredService<IGroupService>();
- var logService = serviceProvider.GetRequiredService<ILogger>();
+ var logService = serviceProvider.GetRequiredService<ILogger<MigrationSystemPermission>>();
try
{
@@ -44,10 +44,16 @@ namespace Grand.Business.System.Services.Migrations._2._2
permissionAccessAdmin.CustomerGroups.Remove(customerGroupVendorId);
repository.Update(permissionAccessAdmin);
}
+ var permissionManageSystemLog = repository.Table.FirstOrDefault(x => x.SystemName == "ManageSystemLog");
+ if (permissionManageSystemLog != null)
+ {
+ repository.Delete(permissionManageSystemLog);
+ }
+
}
catch (Exception ex)
{
- logService.InsertLog(Domain.Logging.LogLevel.Error, "UpgradeProcess - add new permission", ex.Message).GetAwaiter().GetResult();
+ logService.LogError(ex, "UpgradeProcess - add new permission");
}
return true;
}
diff --git a/src/Business/Grand.Business.System/Services/Migrations/2.2/MigrationUpdateAdminSiteMap.cs b/src/Business/Grand.Business.System/Services/Migrations/2.2/MigrationUpdateAdminSiteMap.cs
index cb7edb196..f7aa34a3f 100644
--- a/src/Business/Grand.Business.System/Services/Migrations/2.2/MigrationUpdateAdminSiteMap.cs
+++ b/src/Business/Grand.Business.System/Services/Migrations/2.2/MigrationUpdateAdminSiteMap.cs
@@ -1,18 +1,17 @@
-using Grand.Business.Core.Interfaces.Common.Logging;
-using Grand.Business.Core.Utilities.Common.Security;
+using Grand.Business.Core.Utilities.Common.Security;
using Grand.Domain.Admin;
using Grand.Domain.Data;
using Grand.Infrastructure.Migrations;
using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging;
namespace Grand.Business.System.Services.Migrations._2._2
{
public class MigrationUpdateAdminSiteMap : IMigration
{
-
public int Priority => 0;
public DbVersion Version => new(2, 2);
- public Guid Identity => new("1025D405-FFF3-45E1-A240-2E5F2A92535F");
+ public Guid Identity => new("55E49962-66DD-4034-8AB2-7F4C33A5E0B2");
public string Name => "Update standard admin site map - add admin menu";
/// <summary>
@@ -24,14 +23,14 @@ namespace Grand.Business.System.Services.Migrations._2._2
public bool UpgradeProcess(IDatabaseContext database, IServiceProvider serviceProvider)
{
var repository = serviceProvider.GetRequiredService<IRepository<Domain.Admin.AdminSiteMap>>();
- var logService = serviceProvider.GetRequiredService<ILogger>();
+ var logService = serviceProvider.GetRequiredService<ILogger<MigrationUpdateAdminSiteMap>>();
try
{
- var sitemapSystem = repository.Table.FirstOrDefault(x => x.SystemName == "Configuration");
- if (sitemapSystem != null)
+ var sitemapConfiguration = repository.Table.FirstOrDefault(x => x.SystemName == "Configuration");
+ if (sitemapConfiguration != null)
{
- sitemapSystem.ChildNodes.Add(new AdminSiteMap() {
+ sitemapConfiguration.ChildNodes.Add(new AdminSiteMap() {
SystemName = "Admin menu",
ResourceName = "Admin.Configuration.Menu",
PermissionNames = new List<string> { PermissionSystemName.Maintenance },
@@ -40,14 +39,24 @@ namespace Grand.Business.System.Services.Migrations._2._2
DisplayOrder = 7,
IconClass = "fa fa-dot-circle-o"
});
+ repository.Update(sitemapConfiguration);
+ }
+
+ var sitemapSystem = repository.Table.FirstOrDefault(x => x.SystemName == "System");
+ if (sitemapSystem != null)
+ {
+ var log = sitemapSystem.ChildNodes.FirstOrDefault(x => x.SystemName == "Log");
+ sitemapSystem.ChildNodes.Remove(log);
+ sitemapSystem.PermissionNames.Remove("ManageSystemLog");
repository.Update(sitemapSystem);
}
}
catch (Exception ex)
{
- logService.InsertLog(Domain.Logging.LogLevel.Error, "UpgradeProcess - UpdateAdminSiteMap", ex.Message).GetAwaiter().GetResult();
+ logService.LogError(ex, "UpgradeProcess - UpdateAdminSiteMap");
}
+
return true;
}
}
-}
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.System/Services/Migrations/MigrationProcess.cs b/src/Business/Grand.Business.System/Services/Migrations/MigrationProcess.cs
index c63c610dd..b38133698 100644
--- a/src/Business/Grand.Business.System/Services/Migrations/MigrationProcess.cs
+++ b/src/Business/Grand.Business.System/Services/Migrations/MigrationProcess.cs
@@ -1,6 +1,6 @@
-using Grand.Business.Core.Interfaces.Common.Logging;
-using Grand.Domain.Data;
+using Grand.Domain.Data;
using Grand.Infrastructure.Migrations;
+using Microsoft.Extensions.Logging;
namespace Grand.Business.System.Services.Migrations
{
@@ -8,14 +8,14 @@ namespace Grand.Business.System.Services.Migrations
{
private readonly IDatabaseContext _databaseContext;
private readonly IServiceProvider _serviceProvider;
- private readonly ILogger _logger;
+ private readonly ILogger<MigrationProcess> _logger;
private readonly IRepository<MigrationDb> _repositoryMigration;
public MigrationProcess(
IDatabaseContext databaseContext,
IServiceProvider serviceProvider,
- ILogger logger,
+ ILogger<MigrationProcess> logger,
IRepository<MigrationDb> repositoryMigration)
{
_databaseContext = databaseContext;
@@ -32,7 +32,7 @@ namespace Grand.Business.System.Services.Migrations
if (result.Success)
SaveMigration(result);
else
- _logger.InsertLog(Domain.Logging.LogLevel.Error, $"Something went wrong during migration process {migration.Name}");
+ _logger.LogError("Something went wrong during migration process {MigrationName}", migration.Name);
return result;
}
catch (Exception ex)
diff --git a/src/Business/Grand.Business.System/Services/Migrations/MigrationUpdateResource.cs b/src/Business/Grand.Business.System/Services/Migrations/MigrationUpdateResource.cs
index 576a1f3bd..c1f445096 100644
--- a/src/Business/Grand.Business.System/Services/Migrations/MigrationUpdateResource.cs
+++ b/src/Business/Grand.Business.System/Services/Migrations/MigrationUpdateResource.cs
@@ -1,9 +1,9 @@
using Grand.Business.Core.Interfaces.Common.Localization;
-using Grand.Business.Core.Interfaces.Common.Logging;
using Grand.Domain.Data;
using Grand.Domain.Localization;
using Grand.SharedKernel.Extensions;
using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging;
namespace Grand.Business.System.Services.Migrations
{
@@ -13,7 +13,7 @@ namespace Grand.Business.System.Services.Migrations
string filename)
{
var langRepository = serviceProvider.GetRequiredService<IRepository<Language>>();
- var logService = serviceProvider.GetRequiredService<ILogger>();
+ var logService = serviceProvider.GetRequiredService<ILoggerFactory>().CreateLogger("ImportLanguageResourcesFromXml");
var translationService = serviceProvider.GetRequiredService<ITranslationService>();
try
@@ -29,7 +29,7 @@ namespace Grand.Business.System.Services.Migrations
}
catch (Exception ex)
{
- logService.InsertLog(Domain.Logging.LogLevel.Error, "UpgradeProcess - MigrationUpdateResourceString", ex.Message).GetAwaiter().GetResult();
+ logService.LogError(ex, "UpgradeProcess - ImportLanguageResourcesFromXml {Filename}", filename);
}
return true;
}
diff --git a/src/Business/Grand.Business.System/Startup/StartupApplication.cs b/src/Business/Grand.Business.System/Startup/StartupApplication.cs
index 2e3d6823e..697f2a4f3 100644
--- a/src/Business/Grand.Business.System/Startup/StartupApplication.cs
+++ b/src/Business/Grand.Business.System/Startup/StartupApplication.cs
@@ -43,7 +43,6 @@ namespace Grand.Business.System.Startup
serviceCollection.AddScoped<IScheduleTask, QueuedMessagesSendScheduleTask>();
serviceCollection.AddScoped<IScheduleTask, ClearCacheScheduleTask>();
- serviceCollection.AddScoped<IScheduleTask, ClearLogScheduleTask>();
serviceCollection.AddScoped<IScheduleTask, GenerateSitemapXmlTask>();
serviceCollection.AddScoped<IScheduleTask, DeleteGuestsScheduleTask>();
serviceCollection.AddScoped<IScheduleTask, UpdateExchangeRateScheduleTask>();
diff --git a/src/Core/Grand.Domain/Logging/Log.cs b/src/Core/Grand.Domain/Logging/Log.cs
deleted file mode 100644
index 9820a2e29..000000000
--- a/src/Core/Grand.Domain/Logging/Log.cs
+++ /dev/null
@@ -1,49 +0,0 @@
-namespace Grand.Domain.Logging
-{
- /// <summary>
- /// Represents a log
- /// </summary>
- public partial class Log : BaseEntity
- {
- /// <summary>
- /// Gets or sets the log level identifier
- /// </summary>
- public LogLevel LogLevelId { get; set; }
-
- /// <summary>
- /// Gets or sets the short message
- /// </summary>
- public string ShortMessage { get; set; }
-
- /// <summary>
- /// Gets or sets the full exception
- /// </summary>
- public string FullMessage { get; set; }
-
- /// <summary>
- /// Gets or sets the IP address
- /// </summary>
- public string IpAddress { get; set; }
-
- /// <summary>
- /// Gets or sets the customer identifier
- /// </summary>
- public string CustomerId { get; set; }
-
- /// <summary>
- /// Gets or sets the page URL
- /// </summary>
- public string PageUrl { get; set; }
-
- /// <summary>
- /// Gets or sets the referrer URL
- /// </summary>
- public string ReferrerUrl { get; set; }
-
- /// <summary>
- /// Gets or sets the date and time of instance creation
- /// </summary>
- public DateTime CreatedOnUtc { get; set; }
-
- }
-}
diff --git a/src/Core/Grand.Domain/Logging/LogLevel.cs b/src/Core/Grand.Domain/Logging/LogLevel.cs
deleted file mode 100644
index 982a9e34f..000000000
--- a/src/Core/Grand.Domain/Logging/LogLevel.cs
+++ /dev/null
@@ -1,14 +0,0 @@
-namespace Grand.Domain.Logging
-{
- /// <summary>
- /// Represents a log level
- /// </summary>
- public enum LogLevel
- {
- Debug = 10,
- Information = 20,
- Warning = 30,
- Error = 40 ,
- Fatal = 50
- }
-}
diff --git a/src/Core/Grand.Infrastructure/Configuration/AppConfig.cs b/src/Core/Grand.Infrastructure/Configuration/AppConfig.cs
index 3687f4331..19353c2df 100644
--- a/src/Core/Grand.Infrastructure/Configuration/AppConfig.cs
+++ b/src/Core/Grand.Infrastructure/Configuration/AppConfig.cs
@@ -43,6 +43,11 @@ namespace Grand.Infrastructure.Configuration
/// </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>
diff --git a/src/Plugins/Authentication.Google/Areas/Admin/Controllers/GoogleAuthenticationSettingsController.cs b/src/Plugins/Authentication.Google/Areas/Admin/Controllers/GoogleAuthenticationSettingsController.cs
index 838e44115..31925e51c 100644
--- a/src/Plugins/Authentication.Google/Areas/Admin/Controllers/GoogleAuthenticationSettingsController.cs
+++ b/src/Plugins/Authentication.Google/Areas/Admin/Controllers/GoogleAuthenticationSettingsController.cs
@@ -4,7 +4,6 @@ using Grand.Business.Core.Interfaces.Common.Localization;
using Grand.Business.Core.Interfaces.Common.Security;
using Grand.Business.Core.Utilities.Common.Security;
using Grand.Web.Common.Controllers;
-using Grand.Web.Common.Filters;
using Grand.Web.Common.Security.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
diff --git a/src/Plugins/DiscountRules.Standard/Areas/Admin/Controllers/CustomerGroupsController.cs b/src/Plugins/DiscountRules.Standard/Areas/Admin/Controllers/CustomerGroupsController.cs
index 316f0552c..6bb739e7a 100644
--- a/src/Plugins/DiscountRules.Standard/Areas/Admin/Controllers/CustomerGroupsController.cs
+++ b/src/Plugins/DiscountRules.Standard/Areas/Admin/Controllers/CustomerGroupsController.cs
@@ -5,7 +5,6 @@ using Grand.Business.Core.Interfaces.Common.Security;
using Grand.Business.Core.Utilities.Common.Security;
using Grand.Domain.Discounts;
using Grand.Web.Common.Controllers;
-using Grand.Web.Common.Filters;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
diff --git a/src/Plugins/DiscountRules.Standard/Areas/Admin/Controllers/HadSpentAmountController.cs b/src/Plugins/DiscountRules.Standard/Areas/Admin/Controllers/HadSpentAmountController.cs
index a68a5de70..74f02f7fb 100644
--- a/src/Plugins/DiscountRules.Standard/Areas/Admin/Controllers/HadSpentAmountController.cs
+++ b/src/Plugins/DiscountRules.Standard/Areas/Admin/Controllers/HadSpentAmountController.cs
@@ -4,7 +4,6 @@ using Grand.Business.Core.Interfaces.Common.Security;
using Grand.Business.Core.Utilities.Common.Security;
using Grand.Domain.Discounts;
using Grand.Web.Common.Controllers;
-using Grand.Web.Common.Filters;
using Microsoft.AspNetCore.Mvc;
using System.Globalization;
diff --git a/src/Plugins/DiscountRules.Standard/Areas/Admin/Controllers/HasAllProductsController.cs b/src/Plugins/DiscountRules.Standard/Areas/Admin/Controllers/HasAllProductsController.cs
index d56e2d750..dec8549d1 100644
--- a/src/Plugins/DiscountRules.Standard/Areas/Admin/Controllers/HasAllProductsController.cs
+++ b/src/Plugins/DiscountRules.Standard/Areas/Admin/Controllers/HasAllProductsController.cs
@@ -12,7 +12,6 @@ using Grand.Infrastructure;
using Grand.Web.Common.Controllers;
using Grand.Web.Common.DataSource;
using Grand.Web.Common.Extensions;
-using Grand.Web.Common.Filters;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
diff --git a/src/Plugins/DiscountRules.Standard/Areas/Admin/Controllers/HasOneProductController.cs b/src/Plugins/DiscountRules.Standard/Areas/Admin/Controllers/HasOneProductController.cs
index a832ee3da..9d32afbe5 100644
--- a/src/Plugins/DiscountRules.Standard/Areas/Admin/Controllers/HasOneProductController.cs
+++ b/src/Plugins/DiscountRules.Standard/Areas/Admin/Controllers/HasOneProductController.cs
@@ -12,7 +12,6 @@ using Grand.Infrastructure;
using Grand.Web.Common.Controllers;
using Grand.Web.Common.DataSource;
using Grand.Web.Common.Extensions;
-using Grand.Web.Common.Filters;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
diff --git a/src/Plugins/DiscountRules.Standard/Areas/Admin/Controllers/ShoppingCartAmountController.cs b/src/Plugins/DiscountRules.Standard/Areas/Admin/Controllers/ShoppingCartAmountController.cs
index 6ee9b061b..ba3f98967 100644
--- a/src/Plugins/DiscountRules.Standard/Areas/Admin/Controllers/ShoppingCartAmountController.cs
+++ b/src/Plugins/DiscountRules.Standard/Areas/Admin/Controllers/ShoppingCartAmountController.cs
@@ -4,7 +4,6 @@ using Grand.Business.Core.Interfaces.Common.Security;
using Grand.Business.Core.Utilities.Common.Security;
using Grand.Domain.Discounts;
using Grand.Web.Common.Controllers;
-using Grand.Web.Common.Filters;
using Microsoft.AspNetCore.Mvc;
using System.Globalization;
diff --git a/src/Plugins/Payments.PayPalStandard/Controllers/PaymentPayPalStandardController.cs b/src/Plugins/Payments.PayPalStandard/Controllers/PaymentPayPalStandardController.cs
index 83f897de3..a9a9332de 100644
--- a/src/Plugins/Payments.PayPalStandard/Controllers/PaymentPayPalStandardController.cs
+++ b/src/Plugins/Payments.PayPalStandard/Controllers/PaymentPayPalStandardController.cs
@@ -3,7 +3,6 @@ using Grand.Business.Core.Extensions;
using Grand.Business.Core.Interfaces.Checkout.Orders;
using Grand.Business.Core.Interfaces.Checkout.Payments;
using Grand.Business.Core.Queries.Checkout.Orders;
-using Grand.Business.Core.Interfaces.Common.Logging;
using Grand.Domain.Orders;
using Grand.Domain.Payments;
using Grand.Infrastructure;
@@ -11,6 +10,7 @@ using Grand.SharedKernel;
using Grand.Web.Common.Controllers;
using MediatR;
using Microsoft.AspNetCore.Mvc;
+using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Primitives;
using Payments.PayPalStandard.Services;
using System.Globalization;
@@ -23,7 +23,7 @@ namespace Payments.PayPalStandard.Controllers
private readonly IWorkContext _workContext;
private readonly IPaymentService _paymentService;
private readonly IOrderService _orderService;
- private readonly ILogger _logger;
+ private readonly ILogger<PaymentPayPalStandardController> _logger;
private readonly IMediator _mediator;
private readonly IPaymentTransactionService _paymentTransactionService;
private readonly IPaypalHttpClient _paypalHttpClient;
@@ -35,7 +35,7 @@ namespace Payments.PayPalStandard.Controllers
IWorkContext workContext,
IPaymentService paymentService,
IOrderService orderService,
- ILogger logger,
+ ILogger<PaymentPayPalStandardController> logger,
IMediator mediator,
IPaymentTransactionService paymentTransactionService,
IPaypalHttpClient paypalHttpClient,
@@ -94,7 +94,7 @@ namespace Payments.PayPalStandard.Controllers
}
catch (Exception exc)
{
- _ = _logger.Error("PayPal PDT. Error getting mc_gross", exc);
+ _logger.LogError(exc, "PayPal PDT. Error getting mc_gross");
}
values.TryGetValue("payer_status", out var payer_status);
@@ -139,7 +139,7 @@ namespace Payments.PayPalStandard.Controllers
{
var errorStr =
$"PayPal PDT. Returned order total {mc_gross} doesn't equal order total {order.OrderTotal * order.CurrencyRate}. Order# {order.OrderNumber}.";
- _ = _logger.Error(errorStr);
+ _logger.LogError(errorStr);
//order note
await _orderService.InsertOrderNote(new OrderNote {
@@ -286,7 +286,7 @@ namespace Payments.PayPalStandard.Controllers
var errorStr =
$"PayPal IPN. Returned order total {mcGross} doesn't equal order total {order.OrderTotal * order.CurrencyRate}. Order# {order.Id}.";
//log
- _ = _logger.Error(errorStr);
+ _logger.LogError(errorStr);
//order note
await _orderService.InsertOrderNote(new OrderNote {
Note = errorStr,
@@ -317,7 +317,7 @@ namespace Payments.PayPalStandard.Controllers
var errorStr =
$"PayPal IPN. Returned order total {mcGross} doesn't equal order total {order.OrderTotal * order.CurrencyRate}. Order# {order.Id}.";
//log
- _ = _logger.Error(errorStr);
+ _logger.LogError(errorStr);
//order note
await _orderService.InsertOrderNote(new OrderNote {
Note = errorStr,
@@ -371,7 +371,7 @@ namespace Payments.PayPalStandard.Controllers
}
else
{
- _ = _logger.Error("PayPal IPN. Order is not found", new GrandException(sb.ToString()));
+ _logger.LogError(new GrandException(sb.ToString()), "PayPal IPN. Order is not found");
}
}
#endregion
@@ -381,7 +381,7 @@ namespace Payments.PayPalStandard.Controllers
}
- _ = _logger.Error("PayPal IPN failed.", new GrandException(strRequest));
+ _logger.LogError(new GrandException(strRequest), "PayPal IPN failed");
return BadRequest();
diff --git a/src/Plugins/Payments.PayPalStandard/Services/PaypalHttpClient.cs b/src/Plugins/Payments.PayPalStandard/Services/PaypalHttpClient.cs
index 35417d871..58999ea97 100644
--- a/src/Plugins/Payments.PayPalStandard/Services/PaypalHttpClient.cs
+++ b/src/Plugins/Payments.PayPalStandard/Services/PaypalHttpClient.cs
@@ -1,4 +1,4 @@
-using Grand.Business.Core.Interfaces.Common.Logging;
+using Microsoft.Extensions.Logging;
using System.Net.Http;
namespace Payments.PayPalStandard.Services
@@ -7,8 +7,8 @@ namespace Payments.PayPalStandard.Services
{
private readonly HttpClient _client;
private readonly PayPalStandardPaymentSettings _paypalStandardPaymentSettings;
- private readonly ILogger _logger;
- public PaypalHttpClient(HttpClient client, PayPalStandardPaymentSettings paypalStandardPaymentSettings, ILogger logger)
+ private readonly ILogger<PaypalHttpClient> _logger;
+ public PaypalHttpClient(HttpClient client, PayPalStandardPaymentSettings paypalStandardPaymentSettings, ILogger<PaypalHttpClient> logger)
{
_client = client;
_paypalStandardPaymentSettings = paypalStandardPaymentSettings;
@@ -39,7 +39,7 @@ namespace Payments.PayPalStandard.Services
}
catch (Exception ex)
{
- await _logger.InsertLog(Grand.Domain.Logging.LogLevel.Error, "VerifyIpn", ex.Message);
+ _logger.LogError(ex, "VerifyIpn");
}
@@ -79,7 +79,7 @@ namespace Payments.PayPalStandard.Services
}
catch(Exception ex)
{
- await _logger.InsertLog(Grand.Domain.Logging.LogLevel.Error, "GetPdtDetails", ex.Message);
+ _logger.LogError(ex, "GetPdtDetails");
}
var content = await response.Content.ReadAsStringAsync();
diff --git a/src/Plugins/Tax.CountryStateZip/Areas/Admin/Controllers/TaxCountryStateZipController.cs b/src/Plugins/Tax.CountryStateZip/Areas/Admin/Controllers/TaxCountryStateZipController.cs
index 7441f4866..e3fa0f797 100644
--- a/src/Plugins/Tax.CountryStateZip/Areas/Admin/Controllers/TaxCountryStateZipController.cs
+++ b/src/Plugins/Tax.CountryStateZip/Areas/Admin/Controllers/TaxCountryStateZipController.cs
@@ -4,7 +4,6 @@ using Grand.Business.Core.Interfaces.Common.Stores;
using Grand.Business.Core.Utilities.Common.Security;
using Grand.Web.Common.Controllers;
using Grand.Web.Common.DataSource;
-using Grand.Web.Common.Filters;
using Grand.Web.Common.Security.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
diff --git a/src/Plugins/Tax.FixedRate/Areas/Admin/Controllers/TaxFixedRateController.cs b/src/Plugins/Tax.FixedRate/Areas/Admin/Controllers/TaxFixedRateController.cs
index 766da9d60..2e1b7018c 100644
--- a/src/Plugins/Tax.FixedRate/Areas/Admin/Controllers/TaxFixedRateController.cs
+++ b/src/Plugins/Tax.FixedRate/Areas/Admin/Controllers/TaxFixedRateController.cs
@@ -3,7 +3,6 @@ using Grand.Business.Core.Interfaces.Common.Configuration;
using Grand.Business.Core.Utilities.Common.Security;
using Grand.Web.Common.Controllers;
using Grand.Web.Common.DataSource;
-using Grand.Web.Common.Filters;
using Grand.Web.Common.Security.Authorization;
using Microsoft.AspNetCore.Mvc;
using Tax.FixedRate.Models;
diff --git a/src/Plugins/Widgets.GoogleAnalytics/Areas/Admin/Controllers/WidgetsGoogleAnalyticsController.cs b/src/Plugins/Widgets.GoogleAnalytics/Areas/Admin/Controllers/WidgetsGoogleAnalyticsController.cs
index 5914500b5..c795149af 100644
--- a/src/Plugins/Widgets.GoogleAnalytics/Areas/Admin/Controllers/WidgetsGoogleAnalyticsController.cs
+++ b/src/Plugins/Widgets.GoogleAnalytics/Areas/Admin/Controllers/WidgetsGoogleAnalyticsController.cs
@@ -6,7 +6,6 @@ using Grand.Domain.Common;
using Grand.Domain.Customers;
using Grand.Infrastructure;
using Grand.Web.Common.Controllers;
-using Grand.Web.Common.Filters;
using Grand.Web.Common.Security.Authorization;
using Microsoft.AspNetCore.Mvc;
using Widgets.GoogleAnalytics.Models;
diff --git a/src/Plugins/Widgets.GoogleAnalytics/Components/WidgetsGoogleAnalyticsViewComponent.cs b/src/Plugins/Widgets.GoogleAnalytics/Components/WidgetsGoogleAnalyticsViewComponent.cs
index 11ab6339b..d6f1ef9bb 100644
--- a/src/Plugins/Widgets.GoogleAnalytics/Components/WidgetsGoogleAnalyticsViewComponent.cs
+++ b/src/Plugins/Widgets.GoogleAnalytics/Components/WidgetsGoogleAnalyticsViewComponent.cs
@@ -3,12 +3,11 @@ using Grand.Business.Core.Interfaces.Catalog.Products;
using Grand.Business.Core.Interfaces.Checkout.Orders;
using Grand.Business.Core.Interfaces.Cms;
using Grand.Business.Core.Interfaces.Common.Directory;
-using Grand.Business.Core.Interfaces.Common.Logging;
-using Grand.Domain.Logging;
using Grand.Domain.Orders;
using Grand.Infrastructure;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging;
using System.Globalization;
namespace Widgets.GoogleAnalytics.Components
@@ -17,13 +16,13 @@ namespace Widgets.GoogleAnalytics.Components
public class WidgetsGoogleAnalyticsViewComponent : ViewComponent
{
private readonly IWorkContext _workContext;
- private readonly ILogger _logger;
+ private readonly ILogger<WidgetsGoogleAnalyticsViewComponent> _logger;
private readonly GoogleAnalyticsEcommerceSettings _googleAnalyticsEcommerceSettings;
private readonly ICookiePreference _cookiePreference;
private readonly IServiceProvider _serviceProvider;
public WidgetsGoogleAnalyticsViewComponent(IWorkContext workContext,
- ILogger logger,
+ ILogger<WidgetsGoogleAnalyticsViewComponent> logger,
GoogleAnalyticsEcommerceSettings googleAnalyticsEcommerceSettings,
ICookiePreference cookiePreference,
IServiceProvider serviceProvider
@@ -70,7 +69,7 @@ namespace Widgets.GoogleAnalytics.Components
}
catch (Exception ex)
{
- await _logger.InsertLog(LogLevel.Error, "Error creating scripts for google ecommerce tracking", ex.ToString());
+ _logger.LogError(ex, "Error creating scripts for google ecommerce tracking");
}
return View("Default", globalScript);
}
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/Directory/GeoLookupServiceTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/Directory/GeoLookupServiceTests.cs
index 75374186d..c96b731e2 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Services/Directory/GeoLookupServiceTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/Directory/GeoLookupServiceTests.cs
@@ -1,6 +1,7 @@
using Grand.Business.Catalog.Services.Directory;
using Grand.Business.Core.Interfaces.Common.Logging;
using Grand.SharedKernel.Extensions;
+using Microsoft.Extensions.Logging;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
@@ -9,14 +10,14 @@ namespace Grand.Business.Catalog.Tests.Services.Directory
[TestClass()]
public class GeoLookupServiceTests
{
- private Mock<ILogger> _loggerMock;
+ private Mock<ILogger<GeoLookupService>> _loggerMock;
private GeoLookupService _service;
private string IPAddressUS = "142.250.203.206";
[TestInitialize()]
public void Init()
{
CommonPath.BaseDirectory = "../../../../../Web/Grand.Web/";
- _loggerMock = new Mock<ILogger>();
+ _loggerMock = new Mock<ILogger<GeoLookupService>>();
_service = new GeoLookupService(_loggerMock.Object);
}
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/Tax/TaxServiceTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/Tax/TaxServiceTests.cs
index 6e99ccf4a..3acbb43e4 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Services/Tax/TaxServiceTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/Tax/TaxServiceTests.cs
@@ -9,6 +9,7 @@ using Grand.Domain.Customers;
using Grand.Domain.Tax;
using Grand.Infrastructure;
using Grand.SharedKernel.Extensions;
+using Microsoft.Extensions.Logging;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
@@ -28,7 +29,7 @@ namespace Grand.Business.Catalog.Tests.Services.Tax
private CustomerSettings _customerSettings;
private AddressSettings _addressSettings;
private Mock<IGroupService> _groupServiceMock;
- private Mock<ILogger> _loggerMock;
+ private Mock<ILogger<TaxService>> _loggerMock;
private IServiceProvider _serviceProvider;
[TestInitialize()]
@@ -50,7 +51,7 @@ namespace Grand.Business.Catalog.Tests.Services.Tax
_customerSettings = new CustomerSettings();
_addressSettings = new AddressSettings();
_groupServiceMock = new Mock<IGroupService>();
- _loggerMock = new Mock<ILogger>();
+ _loggerMock = new Mock<ILogger<TaxService>>();
var providers = new List<ITaxProvider>();
providers.Add(new FixedRateTestTaxProvider());
_taxService = new TaxService( _workContext,_groupServiceMock.Object,
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/CaptureCommandHandlerTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/CaptureCommandHandlerTests.cs
index 903bff86d..b5b74f807 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/CaptureCommandHandlerTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/CaptureCommandHandlerTests.cs
@@ -6,6 +6,7 @@ using Grand.Business.Core.Interfaces.Common.Logging;
using Grand.Business.Core.Queries.Checkout.Orders;
using Grand.Domain.Payments;
using MediatR;
+using Microsoft.Extensions.Logging;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
@@ -20,13 +21,13 @@ namespace Grand.Business.Checkout.Tests.Commands.Handlers.Orders
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>();
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/PartiallyRefundCommandHandlerTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/PartiallyRefundCommandHandlerTests.cs
index 7e842271f..ccc2786dd 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/PartiallyRefundCommandHandlerTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/PartiallyRefundCommandHandlerTests.cs
@@ -9,6 +9,7 @@ using Grand.Business.Core.Utilities.Checkout;
using Grand.Domain.Orders;
using Grand.Domain.Payments;
using MediatR;
+using Microsoft.Extensions.Logging;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
@@ -23,7 +24,7 @@ namespace Grand.Business.Checkout.Tests.Commands.Handlers.Orders
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()
@@ -33,7 +34,7 @@ namespace Grand.Business.Checkout.Tests.Commands.Handlers.Orders
_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());
}
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/RefundCommandHandlerTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/RefundCommandHandlerTests.cs
index 18247bf25..c30dfd91f 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/RefundCommandHandlerTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/RefundCommandHandlerTests.cs
@@ -9,6 +9,7 @@ using Grand.Business.Core.Utilities.Checkout;
using Grand.Domain.Orders;
using Grand.Domain.Payments;
using MediatR;
+using Microsoft.Extensions.Logging;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
@@ -23,7 +24,7 @@ namespace Grand.Business.Checkout.Tests.Commands.Handlers.Orders
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()
@@ -33,7 +34,7 @@ namespace Grand.Business.Checkout.Tests.Commands.Handlers.Orders
_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());
}
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/VoidCommandHandlerTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/VoidCommandHandlerTests.cs
index b55f8313c..856538406 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/VoidCommandHandlerTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/VoidCommandHandlerTests.cs
@@ -9,6 +9,7 @@ using Grand.Business.Core.Utilities.Checkout;
using Grand.Domain.Orders;
using Grand.Domain.Payments;
using MediatR;
+using Microsoft.Extensions.Logging;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
@@ -23,7 +24,7 @@ namespace Grand.Business.Checkout.Tests.Commands.Handlers.Orders
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()
@@ -33,7 +34,7 @@ namespace Grand.Business.Checkout.Tests.Commands.Handlers.Orders
_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,
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Services/Shipping/ShippingServiceTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Services/Shipping/ShippingServiceTests.cs
index 1e8ba7bf8..ef12dc425 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Services/Shipping/ShippingServiceTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Services/Shipping/ShippingServiceTests.cs
@@ -8,6 +8,7 @@ using Grand.Domain.Customers;
using Grand.Domain.Orders;
using Grand.Domain.Shipping;
using Grand.Domain.Stores;
+using Microsoft.Extensions.Logging;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
@@ -16,7 +17,7 @@ namespace Grand.Business.Checkout.Tests.Services.Shipping
[TestClass]
public class ShippingServiceTests
{
- private Mock<ILogger> _loggerMock;
+ private Mock<ILogger<ShippingService>> _loggerMock;
private Mock<ITranslationService> _translationServiceMock;
private Mock<ICountryService> _countryServiceMokc;
private ShippingProviderSettings _shippingProviderSettings;
@@ -27,7 +28,7 @@ namespace Grand.Business.Checkout.Tests.Services.Shipping
[TestInitialize]
public void Init()
{
- _loggerMock = new Mock<ILogger>();
+ _loggerMock = new Mock<ILogger<ShippingService>>();
_translationServiceMock = new Mock<ITranslationService>();
_countryServiceMokc = new Mock<ICountryService>();
_shippingProviderSettings = new ShippingProviderSettings();
diff --git a/src/Tests/Grand.Business.Common.Tests/Services/Logging/DefaultLoggerTests.cs b/src/Tests/Grand.Business.Common.Tests/Services/Logging/DefaultLoggerTests.cs
deleted file mode 100644
index b7453b8ef..000000000
--- a/src/Tests/Grand.Business.Common.Tests/Services/Logging/DefaultLoggerTests.cs
+++ /dev/null
@@ -1,95 +0,0 @@
-using Grand.Business.Common.Services.Logging;
-using Grand.Data.Tests.MongoDb;
-using Grand.Domain.Data;
-using Grand.Domain.Logging;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-
-namespace Grand.Business.Common.Tests.Services.Logging
-{
- [TestClass()]
- public class DefaultLoggerTests
- {
- private IRepository<Log> _repository;
- private DefaultLogger _logger;
-
- [TestInitialize()]
- public void Init()
- {
- _repository = new MongoDBRepositoryTest<Log>();
- _logger = new DefaultLogger(_repository);
- }
-
- [TestMethod()]
- public async Task GetAllLogsTest()
- {
- //Arrange
- await _repository.InsertAsync(new Log());
- await _repository.InsertAsync(new Log());
- await _repository.InsertAsync(new Log());
- //Act
- var result = await _logger.GetAllLogs();
- //Assert
- Assert.IsTrue(result.Any());
- }
-
- [TestMethod()]
- public async Task GetLogByIdTest()
- {
- //Arrange
- var log = new Log();
- await _repository.InsertAsync(log);
- //Act
- var result = await _logger.GetLogById(log.Id);
- //Assert
- Assert.IsNotNull(result);
- }
-
- [TestMethod()]
- public async Task GetLogByIdsTest()
- {
- //Arrange
- var log = new Log();
- await _repository.InsertAsync(log);
- //Act
- var result = await _logger.GetLogByIds(new[] { log.Id });
- //Assert
- Assert.IsTrue(result.Any());
- }
-
- [TestMethod()]
- public async Task InsertLogTest()
- {
- //Act
- await _logger.InsertLog(LogLevel.Debug, "message");
- //Assert
- Thread.Sleep(100);
- Assert.IsTrue(_repository.Table.Any());
- }
-
- [TestMethod()]
- public async Task DeleteLogTest()
- {
- //Arrange
- var log = new Log();
- await _repository.InsertAsync(log);
- //Act
- await _logger.DeleteLog(log);
- var result = await _logger.GetLogById(log.Id);
- //Assert
- Assert.IsNull(result);
- }
-
- [TestMethod()]
- public async Task ClearLogTest()
- {
- //Arrange
- await _repository.InsertAsync(new Log());
- await _repository.InsertAsync(new Log());
- await _repository.InsertAsync(new Log());
- //Act
- await _logger.ClearLog();
- //Assert
- Assert.IsFalse(_repository.Table.Any());
- }
- }
-}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Marketing.Tests/Services/PushNotifications/PushNotificationsServiceTests.cs b/src/Tests/Grand.Business.Marketing.Tests/Services/PushNotifications/PushNotificationsServiceTests.cs
index 2961523fe..207d7c58d 100644
--- a/src/Tests/Grand.Business.Marketing.Tests/Services/PushNotifications/PushNotificationsServiceTests.cs
+++ b/src/Tests/Grand.Business.Marketing.Tests/Services/PushNotifications/PushNotificationsServiceTests.cs
@@ -5,6 +5,7 @@ using Grand.Data.Tests.MongoDb;
using Grand.Domain.Data;
using Grand.Domain.PushNotifications;
using MediatR;
+using Microsoft.Extensions.Logging;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using Moq.Protected;
@@ -21,7 +22,7 @@ namespace Grand.Business.Marketing.Tests.Services.PushNotifications
private IRepository<PushRegistration> _repositoryPushRegistration;
private IRepository<PushMessage> _repositoryPushMessage;
private Mock<IMediator> _mediatorMock;
- private Mock<ILogger> _loggerMock;
+ private Mock<ILogger<PushNotificationsService>> _loggerMock;
[TestInitialize()]
@@ -30,7 +31,7 @@ namespace Grand.Business.Marketing.Tests.Services.PushNotifications
_repositoryPushRegistration = new MongoDBRepositoryTest<PushRegistration>();
_repositoryPushMessage = new MongoDBRepositoryTest<PushMessage>();
_mediatorMock = new Mock<IMediator>();
- _loggerMock = new Mock<ILogger>();
+ _loggerMock = new Mock<ILogger<PushNotificationsService>>();
var mockMessageHandler = new Mock<HttpMessageHandler>();
diff --git a/src/Tests/Grand.Business.Storage.Tests/Services/PictureServiceTests.cs b/src/Tests/Grand.Business.Storage.Tests/Services/PictureServiceTests.cs
index 65f31fb5e..065d4f8bf 100644
--- a/src/Tests/Grand.Business.Storage.Tests/Services/PictureServiceTests.cs
+++ b/src/Tests/Grand.Business.Storage.Tests/Services/PictureServiceTests.cs
@@ -8,6 +8,7 @@ using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Events;
using MediatR;
using Microsoft.AspNetCore.Hosting;
+using Microsoft.Extensions.Logging;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
@@ -17,7 +18,7 @@ namespace Grand.Business.Storage.Tests.Services
public class PictureServiceTests
{
private Mock<IRepository<Picture>> _repoMock;
- private Mock<ILogger> _logerMock;
+ private Mock<ILogger<PictureService>> _logerMock;
private Mock<IMediator> _mediatorMock;
private Mock<IWebHostEnvironment> _webHostMock;
private Mock<IWorkContext> _workContextMock;
@@ -33,7 +34,7 @@ namespace Grand.Business.Storage.Tests.Services
{
_webHostMock = new Mock<IWebHostEnvironment>();
_repoMock = new Mock<IRepository<Picture>>();
- _logerMock = new Mock<ILogger>();
+ _logerMock = new Mock<ILogger<PictureService>>();
_mediatorMock = new Mock<IMediator>();
_workContextMock = new Mock<IWorkContext>();
_cacheMock = new Mock<ICacheBase>();
diff --git a/src/Tests/Grand.Business.System.Tests/Services/BackgroundService/ClearLogScheduleTaskTests.cs b/src/Tests/Grand.Business.System.Tests/Services/BackgroundService/ClearLogScheduleTaskTests.cs
deleted file mode 100644
index 4099b77ea..000000000
--- a/src/Tests/Grand.Business.System.Tests/Services/BackgroundService/ClearLogScheduleTaskTests.cs
+++ /dev/null
@@ -1,28 +0,0 @@
-using Grand.Business.Core.Interfaces.Common.Logging;
-using Grand.Business.System.Services.BackgroundServices.ScheduleTasks;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Moq;
-
-namespace Grand.Business.System.Tests.Services.BackgroundService
-{
- [TestClass]
- public class ClearLogScheduleTaskTests
- {
- private Mock<ILogger> _loggerMock;
- private ClearLogScheduleTask _task;
-
- [TestInitialize]
- public void Init()
- {
- _loggerMock = new Mock<ILogger>();
- _task = new ClearLogScheduleTask(_loggerMock.Object);
- }
-
- [TestMethod]
- public async Task Execute_InvokeClearLogs()
- {
- await _task.Execute();
- _loggerMock.Verify(c => c.ClearLog(), Times.Once);
- }
- }
-}
diff --git a/src/Tests/Grand.Business.System.Tests/Services/BackgroundService/EndAuctionsTaskTests.cs b/src/Tests/Grand.Business.System.Tests/Services/BackgroundService/EndAuctionsTaskTests.cs
index 3c8812142..bcc8aaebd 100644
--- a/src/Tests/Grand.Business.System.Tests/Services/BackgroundService/EndAuctionsTaskTests.cs
+++ b/src/Tests/Grand.Business.System.Tests/Services/BackgroundService/EndAuctionsTaskTests.cs
@@ -13,6 +13,7 @@ using Grand.Domain.Orders;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using Grand.Business.Core.Utilities.Checkout;
+using Microsoft.Extensions.Logging;
namespace Grand.Business.System.Tests.Services.BackgroundService
{
@@ -23,7 +24,7 @@ namespace Grand.Business.System.Tests.Services.BackgroundService
private Mock<IMessageProviderService> _messageProviderMock;
private Mock<IShoppingCartService> _shoppingCartMock;
private Mock<ICustomerService> _customerServiceMock;
- private Mock<ILogger> _loggerMock;
+ private Mock<ILogger<EndAuctionsTask>> _loggerMock;
private LanguageSettings _settings;
private EndAuctionsTask _task;
@@ -34,7 +35,7 @@ namespace Grand.Business.System.Tests.Services.BackgroundService
_messageProviderMock = new Mock<IMessageProviderService>();
_shoppingCartMock = new Mock<IShoppingCartService>();
_customerServiceMock = new Mock<ICustomerService>();
- _loggerMock = new Mock<ILogger>();
+ _loggerMock = new Mock<ILogger<EndAuctionsTask>>();
_settings = new LanguageSettings();
_task = new EndAuctionsTask(_auctionMock.Object, _messageProviderMock.Object, _settings, _shoppingCartMock.Object, _customerServiceMock.Object,
_loggerMock.Object);
@@ -63,7 +64,12 @@ namespace Grand.Business.System.Tests.Services.BackgroundService
.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.Log(
+ It.IsAny<LogLevel>(),
+ It.IsAny<EventId>(),
+ It.IsAny<It.IsAnyType>(),
+ It.IsAny<Exception>(),
+ (Func<It.IsAnyType, Exception, string>)It.IsAny<object>()), Times.Once);
}
[TestMethod]
@@ -77,7 +83,12 @@ namespace Grand.Business.System.Tests.Services.BackgroundService
.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.Log(
+ It.IsAny<LogLevel>(),
+ It.IsAny<EventId>(),
+ It.IsAny<It.IsAnyType>(),
+ It.IsAny<Exception>(),
+ (Func<It.IsAnyType, Exception, string>)It.IsAny<object>()), 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);
diff --git a/src/Tests/Grand.Business.System.Tests/Services/BackgroundService/QueuedMessagesSendScheduleTaskTests.cs b/src/Tests/Grand.Business.System.Tests/Services/BackgroundService/QueuedMessagesSendScheduleTaskTests.cs
index 489f36f09..fccab6da3 100644
--- a/src/Tests/Grand.Business.System.Tests/Services/BackgroundService/QueuedMessagesSendScheduleTaskTests.cs
+++ b/src/Tests/Grand.Business.System.Tests/Services/BackgroundService/QueuedMessagesSendScheduleTaskTests.cs
@@ -4,6 +4,7 @@ using Grand.Business.System.Services.BackgroundServices.ScheduleTasks;
using Grand.Domain;
using Grand.Domain.Customers;
using Grand.Domain.Messages;
+using Microsoft.Extensions.Logging;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
@@ -15,7 +16,7 @@ namespace Grand.Business.System.Tests.Services.BackgroundService
private Mock<IQueuedEmailService> _queuedEmailServiceMock;
private Mock<IEmailSender> _emailSenderMock;
private Mock<IEmailAccountService> _emailAccountServiceMock;
- private Mock<ILogger> _loggerMock;
+ private Mock<ILogger<QueuedMessagesSendScheduleTask>> _loggerMock;
private QueuedMessagesSendScheduleTask _task;
[TestInitialize]
@@ -24,7 +25,7 @@ namespace Grand.Business.System.Tests.Services.BackgroundService
_queuedEmailServiceMock = new Mock<IQueuedEmailService>();
_emailSenderMock = new Mock<IEmailSender>();
_emailAccountServiceMock = new Mock<IEmailAccountService>();
- _loggerMock = new Mock<ILogger>();
+ _loggerMock = new Mock<ILogger<QueuedMessagesSendScheduleTask>>();
_task = new QueuedMessagesSendScheduleTask(_queuedEmailServiceMock.Object, _emailSenderMock.Object, _loggerMock.Object, _emailAccountServiceMock.Object);
}
@@ -58,7 +59,12 @@ namespace Grand.Business.System.Tests.Services.BackgroundService
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.Log(
+ It.IsAny<LogLevel>(),
+ It.IsAny<EventId>(),
+ It.IsAny<It.IsAnyType>(),
+ It.IsAny<Exception>(),
+ (Func<It.IsAnyType, Exception, string>)It.IsAny<object>()), Times.Once);
_queuedEmailServiceMock.Verify(c => c.UpdateQueuedEmail(It.IsAny<QueuedEmail>()), Times.Once);
}
}
diff --git a/src/Tests/Grand.Business.System.Tests/Services/Migrations/MigrationProcessTest.cs b/src/Tests/Grand.Business.System.Tests/Services/Migrations/MigrationProcessTest.cs
index baf2f980e..de1e882b8 100644
--- a/src/Tests/Grand.Business.System.Tests/Services/Migrations/MigrationProcessTest.cs
+++ b/src/Tests/Grand.Business.System.Tests/Services/Migrations/MigrationProcessTest.cs
@@ -1,6 +1,7 @@
using Grand.Business.Core.Interfaces.Common.Logging;
using Grand.Business.System.Services.Migrations;
using Grand.Domain.Data;
+using Microsoft.Extensions.Logging;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
@@ -12,7 +13,7 @@ namespace Grand.Business.System.Tests.Services.Migrations
private Mock<IRepository<MigrationDb>> _repository;
private MigrationProcess _service;
private Mock<IDatabaseContext> _dbContext;
- private Mock<ILogger> _loggerMock;
+ private Mock<ILogger<MigrationProcess>> _loggerMock;
private IServiceProvider _serviceProvider;
[TestInitialize]
@@ -23,7 +24,7 @@ namespace Grand.Business.System.Tests.Services.Migrations
_repository = new Mock<IRepository<MigrationDb>>();
_dbContext = new Mock<IDatabaseContext>();
- _loggerMock = new Mock<ILogger>();
+ _loggerMock = new Mock<ILogger<MigrationProcess>>();
_service = new MigrationProcess(_dbContext.Object, _serviceProvider, _loggerMock.Object, _repository.Object);
}
//TODO
diff --git a/src/Web/Grand.Web.Admin/App_Data/appsettings.json b/src/Web/Grand.Web.Admin/App_Data/appsettings.json
index bdc313990..91fb8dd26 100644
--- a/src/Web/Grand.Web.Admin/App_Data/appsettings.json
+++ b/src/Web/Grand.Web.Admin/App_Data/appsettings.json
@@ -216,36 +216,25 @@
"InstalledPlugins": ""
},
+ "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",
+ "Enrich": [ "FromLogContext" ],
+ "WriteTo": [
+ {
+ "Name": "Console"
+ }
+ ]
},
-
"ApplicationInsights": {
"Enabled": false,
- "ConnectionString": ""
+ "InstrumentationKey": "",
+ "EnableAdaptiveSampling": false
}
- //https://docs.microsoft.com/en-us/azure/azure-monitor/app/asp-net-core
- //The following configuration allows ApplicationInsights to capture
- //all Information logs and more severe logs
- //"Logging": {
- // "LogLevel": {
- // "Default": "Warning"
- // },
- // "ApplicationInsights": {
- // "LogLevel": {
- // "Default": "Information"
- // }
- // }
- //}
}
\ No newline at end of file
diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/ActivityLog/ListLogs.cshtml b/src/Web/Grand.Web.Admin/Areas/Admin/Views/ActivityLog/ListLogs.cshtml
index afdda9b2c..8194b4f28 100644
--- a/src/Web/Grand.Web.Admin/Areas/Admin/Views/ActivityLog/ListLogs.cshtml
+++ b/src/Web/Grand.Web.Admin/Areas/Admin/Views/ActivityLog/ListLogs.cshtml
@@ -151,7 +151,7 @@
title: "@Loc["Admin.Configuration.ActivityLog.ActivityLog.Fields.Comment"]"
}, {
field: "CreatedOn",
- title: "@Loc["Admin.System.Log.Fields.CreatedOn"]",
+ title: "@Loc["Admin.Configuration.ActivityLog.ActivityLog.Fields.CreatedOn"]",
width: 200,
type: "date",
format: "{0:G}"
diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/CreateOrUpdate.TabOrders.cshtml b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/CreateOrUpdate.TabOrders.cshtml
index e81a991de..1cc01e98c 100644
--- a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/CreateOrUpdate.TabOrders.cshtml
+++ b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/CreateOrUpdate.TabOrders.cshtml
@@ -89,7 +89,7 @@
}
{
field: "CreatedOn",
- title: "@Loc["Admin.System.Log.Fields.CreatedOn"]",
+ title: "@Loc["Admin.Customers.Customers.Orders.CreatedOn"]",
width: 220,
type: "date",
format: "{0:G}"
diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Logger/List.cshtml b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Logger/List.cshtml
deleted file mode 100644
index f54a9df50..000000000
--- a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Logger/List.cshtml
+++ /dev/null
@@ -1,253 +0,0 @@
-@model LogListModel
-@inject AdminAreaSettings adminAreaSettings
-@{
- //page title
- ViewBag.Title = Loc["Admin.System.Log"];
-}
-<form asp-area="@Constants.AreaAdmin" asp-controller="Logger" asp-action="List" method="post">
-
- <div class="row">
- <div class="col-md-12">
- <div class="x_panel light form-fit popup-window">
- <div class="x_title">
- <div class="caption">
- <i class="fa fa-bolt"></i>
- @Loc["Admin.System.Log"]
- </div>
- <div class="actions btn-group btn-group-devided">
- <input type="button" name="delete-selected" id="delete-selected" class="btn green" value="@Loc["Admin.System.Log.DeleteSelected"]" />
- <input type="submit" name="clearall" asp-action="ClearAll" class="btn red" value="@Loc["Admin.System.Log.ClearLog"]" onclick="return confirm('@Loc["Admin.Common.AreYouSure"]'); " />
- <vc:admin-widget widget-zone="log_list_buttons" additional-data="null" />
- </div>
- </div>
- <div class="x_content form">
- <div class="form-horizontal">
- <div class="form-body">
- <div class="main-header col-12 px-0">
- <div class="row align-items-end">
- <div class="col-md-4 col-ms-12 col-12">
- <div class="form-group mb-0">
- <admin-label asp-for="Message" class="control-label" />
- <admin-input asp-for="Message" />
- </div>
- </div>
- <div class="col-md-4 col-ms-12 col-12">
- <div class="form-group mb-0">
- <admin-label asp-for="LogLevelId" class="control-label" />
- <admin-select asp-for="LogLevelId" asp-items="Model.AvailableLogLevels" />
- </div>
- </div>
- <div class="col-md-4 col-sm-12 col-12">
- <div class="form-actions">
- <div class="btn-group">
- <button class="btn btn-success filter-submit" id="search-log">
- <i class="fa fa-search"></i> @Loc["Admin.Common.Search"]
- </button>
- <button class="btn btn-info" type="button" data-toggle="collapse" data-target="#filterCollapse" aria-expanded="false" aria-controls="filterCollapse">
- <i class="fa fa-filter"></i>&nbsp; @Loc["Admin.Common.Filters"]
- </button>
- </div>
- </div>
- </div>
- </div>
- </div>
- <div class="collapse" id="filterCollapse">
- <div class="drop-filters-container w-100">
- <div class="form-group">
- <admin-label asp-for="CreatedOnFrom" class="col-sm-3 control-label" />
- <div class="col-md-9 col-sm-9">
- <admin-input asp-for="CreatedOnFrom" />
- </div>
- </div>
- <div class="form-group">
- <admin-label asp-for="CreatedOnTo" class="col-sm-3 control-label" />
- <div class="col-md-9 col-sm-9">
- <admin-input asp-for="CreatedOnTo" />
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
- <div class="x_content">
- <div id="log-grid"></div>
- </div>
- </div>
- </div>
- </div>
-
- <script>
- $(document).ready(function () {
- $("#log-grid").kendoGrid({
- dataSource: {
- transport: {
- read: {
- url: "@Html.Raw(Url.Action("LogList", "Logger", new { area = Constants.AreaAdmin }))",
- type: "POST",
- dataType: "json",
- data: additionalData
- }
- },
- schema: {
- data: "Data",
- total: "Total",
- errors: "Errors"
- },
- error: function(e) {
- display_kendoui_grid_error(e);
- // Cancel the changes
- this.cancelChanges();
- },
- pageSize: @(adminAreaSettings.DefaultGridPageSize),
- serverPaging: true,
- serverFiltering: true,
- serverSorting: true
- },
- pageable: {
- refresh: true,
- pageSizes: [@(adminAreaSettings.GridPageSizes)]
- },
- scrollable: false,
- dataBound: onDataBound,
- columns: [{
- field: "Id",
- headerTemplate: "<label class='mt-checkbox mt-checkbox-outline control control-checkbox'><input id='mastercheckbox' type='checkbox'/> <div class='control__indicator'></div></label>",
- headerAttributes: { style: "text-align:center" },
- attributes: { style: "text-align:center" },
- template: "<label class='mt-checkbox mt-checkbox-outline control control-checkbox'><input type='checkbox' value='#=Id#' class='checkboxGroups'/> <div class='control__indicator'></div></label>",
- width: 60
- }, {
- field: "LogLevel",
- title: "@Loc["Admin.System.Log.Fields.LogLevel"]",
- width: 100
- }, {
- field: "ShortMessage",
- title: "@Loc["Admin.System.Log.Fields.ShortMessage"]",
- template: '<a class="k-link" href="View/#=Id#">#=kendo.htmlEncode(ShortMessage)#</a>'
- }, {
- field: "CreatedOn",
- title: "@Loc["Admin.System.Log.Fields.CreatedOn"]",
- width: 200,
- type: "date",
- format: "{0:G}"
- }]
- });
- });
- </script>
-
-
- <script>
-
- var selectedIds = [];
-
- $(document).ready(function () {
-
- //search button
- $('#search-log').click(function () {
- //search
- var grid = $('#log-grid').data('kendoGrid');
- grid.dataSource.page(1); //new search. Set page size to 1
- //grid.dataSource.read(); we already loaded the grid above using "page" function
- //clear selected checkboxes
- $('.checkboxGroups').prop('checked', false).change();
- selectedIds = [];
- return false;
- });
-
- $("#@Html.IdFor(model => model.Message)").keydown(function (event) {
- if (event.keyCode == 13) {
- $("#search-log").click();
- return false;
- }
- });
-
- //"delete selected" button
- $('#delete-selected').click(function (e) {
- e.preventDefault();
-
- var postData = {
- selectedIds: selectedIds
- };
- addAntiForgeryToken(postData);
-
- $.ajax({
- cache:false,
- type: "POST",
- url: "@(Url.Action("DeleteSelected", "Logger", new { area = Constants.AreaAdmin }))",
- data: postData,
- complete: function (data) {
- //reload grid
- var grid = $('#log-grid').data('kendoGrid');
- grid.dataSource.page(1); //new search. Set page size to 1
- //grid.dataSource.read(); we already loaded the grid above using "page" function
- //clear selected checkboxes
- $('.checkboxGroups').prop('checked', false).change();
- selectedIds = [];
- },
- error:function (xhr, ajaxOptions, thrownError){
- alert(thrownError);
- },
- traditional: true
- });
- return false;
- });
-
-
- $('#mastercheckbox').click(function () {
- $('.checkboxGroups').prop('checked', $(this).is(':checked')).change();
- });
-
- //wire up checkboxes.
- $('#log-grid').on('change', 'input[type=checkbox][id!=mastercheckbox]', function (e) {
- var $check = $(this);
- if ($check.is(":checked") == true) {
- var checked = jQuery.inArray($check.val(), selectedIds);
- if (checked == -1) {
- //add id to selectedIds.
- selectedIds.push($check.val());
- }
- }
- else {
- var checked = jQuery.inArray($check.val(), selectedIds);
- if (checked > -1) {
- //remove id from selectedIds.
- selectedIds = $.grep(selectedIds, function (item, index) {
- return item != $check.val();
- });
- }
- }
- updateMasterCheckbox();
- });
- });
-
- function additionalData() {
- var data = {
- CreatedOnFrom: $('#@Html.IdFor(model => model.CreatedOnFrom)').val(),
- CreatedOnTo: $('#@Html.IdFor(model => model.CreatedOnTo)').val(),
- Message: $('#@Html.IdFor(model => model.Message)').val(),
- LogLevelId: $('#@Html.IdFor(model => model.LogLevelId)').val()
- };
- addAntiForgeryToken(data);
- return data;
- }
-
-
- function onDataBound(e) {
- $('#log-grid input[type=checkbox][id!=mastercheckbox]').each(function () {
- var currentId = $(this).val();
- var checked = jQuery.inArray(currentId, selectedIds);
- //set checked based on if current checkbox's value is in selectedIds.
- $(this).prop('checked', checked > -1);
- });
-
- updateMasterCheckbox();
- }
-
- function updateMasterCheckbox() {
- var numChkBoxes = $('#log-grid input[type=checkbox][id!=mastercheckbox]').length;
- var numChkBoxesChecked = $('#log-grid input[type=checkbox][id!=mastercheckbox]:checked').length;
- $('#mastercheckbox').prop('checked', numChkBoxes == numChkBoxesChecked && numChkBoxes > 0);
- }
- </script>
-</form>
diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Logger/View.cshtml b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Logger/View.cshtml
deleted file mode 100644
index fc85c709c..000000000
--- a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Logger/View.cshtml
+++ /dev/null
@@ -1,83 +0,0 @@
-@model LogModel
-@{
- //page title
- ViewBag.Title = Loc["Admin.System.Log.ViewLogDetails"];
-}
-<div class="row">
- <div class="col-md-12">
- <div class="x_panel light form-fit">
- <div class="x_title">
- <div class="caption">
- <i class="fa fa-tag"></i>
- @Loc["Admin.System.Log.ViewLogDetails"]
- <small><i class="fa fa-arrow-circle-left"></i>@Html.ActionLink(Loc["Admin.System.Log.BackToList"], "List")</small>
- </div>
- <div class="actions">
- <span id="log-delete" class="btn red"><i class="fa fa-trash-o"></i> @Loc["Admin.Common.Delete"]</span>
- </div>
- <vc:admin-widget widget-zone="log_details_buttons" additional-data="Model" />
- </div>
- <div class="x_content form">
- <div class="form-horizontal">
- <div class="form-body">
- <div class="form-group">
- <admin-label asp-for="LogLevel" />
- <div class="col-md-9 col-sm-9">
- <label class="control-label">@Model.LogLevel</label>
- </div>
- </div>
- <div class="form-group">
- <admin-label asp-for="ShortMessage" />
- <div class="col-md-9 col-sm-9">
- <label class="control-label" style="text-align:left">@Model.ShortMessage</label>
- </div>
- </div>
- <div class="form-group">
- <admin-label asp-for="FullMessage" />
- <div class="col-md-9 col-sm-9">
- <label class="control-label" style="text-align:left">@Model.FullMessage</label>
- </div>
- </div>
- <div class="form-group">
- <admin-label asp-for="IpAddress" />
- <div class="col-md-9 col-sm-9">
- <label class="control-label">@Model.IpAddress</label>
- </div>
- </div>
- <div class="form-group">
- <admin-label asp-for="CustomerId" />
- <div class="col-md-9 col-sm-9">
- @if (!string.IsNullOrEmpty(Model.CustomerId))
- {
- <label class="control-label">
- @Html.ActionLink(!string.IsNullOrEmpty(Model.CustomerEmail) ? Model.CustomerEmail : Loc["Admin.Customers.Guest"], "Edit", "Customer", new { id = Model.CustomerId }, new { })
- </label>
- }
- </div>
- </div>
- <div class="form-group">
- <admin-label asp-for="PageUrl" />
- <div class="col-md-9 col-sm-9">
- <label class="control-label">@Model.PageUrl</label>
- </div>
- </div>
- <div class="form-group">
- <admin-label asp-for="ReferrerUrl" />
- <div class="col-md-9 col-sm-9">
- <label class="control-label">@Model.ReferrerUrl</label>
- </div>
- </div>
- <div class="form-group">
- <admin-label asp-for="CreatedOn" />
- <div class="col-md-9 col-sm-9">
- <label class="control-label">@Model.CreatedOn</label>
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
-</div>
-
-<admin-delete-confirmation button-id="log-delete"/>
diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Maintenance/Maintenance.cshtml b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Maintenance/Maintenance.cshtml
index 449223f5d..466d8068b 100644
--- a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Maintenance/Maintenance.cshtml
+++ b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Maintenance/Maintenance.cshtml
@@ -103,20 +103,6 @@
</div>
}
</div>
- <div class="form-body panel panel-default">
- <div class="note note-info">
- <strong>@Loc["Admin.System.Maintenance.DeleteSystemLog"]</strong>
- </div>
- <div class="form-group">
- <input type="submit" name="delete-systemlog" asp-action="MaintenanceDeleteSystemlog" class="btn red offset-md-3" value="@Loc["Admin.Common.Delete"]" />
- </div>
- @if (Model.DeleteSystemLog)
- {
- <div class="form-group">
- <label class="offset-md-3">@Loc["Admin.System.Maintenance.DeleteSystemLog.Deleted"]</label>
- </div>
- }
- </div>
<div class="form-body panel panel-default">
<div class="note note-info form-actions">
<strong>@Loc["Admin.System.Maintenance.ConvertPicture"]</strong>
diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/_ViewImports.cshtml b/src/Web/Grand.Web.Admin/Areas/Admin/Views/_ViewImports.cshtml
index 5ac2d8b37..5802f6f0a 100644
--- a/src/Web/Grand.Web.Admin/Areas/Admin/Views/_ViewImports.cshtml
+++ b/src/Web/Grand.Web.Admin/Areas/Admin/Views/_ViewImports.cshtml
@@ -24,6 +24,7 @@
@using Grand.Web.Common.Page
@using Grand.Web.Common.Link;
@using Grand.Web.Admin.Extensions;
+@using Grand.Web.Admin.Models.ActivityLog;
@using Grand.Web.Admin.Models.Affiliates
@using Grand.Web.Admin.Models.Blogs
@using Grand.Web.Admin.Models.Catalog
@@ -39,7 +40,6 @@
@using Grand.Web.Admin.Models.Home
@using Grand.Web.Admin.Models.Layouts
@using Grand.Web.Admin.Models.Localization
-@using Grand.Web.Admin.Models.Logging
@using Grand.Web.Admin.Models.Menu
@using Grand.Web.Admin.Models.Messages
@using Grand.Web.Admin.Models.News
diff --git a/src/Web/Grand.Web.Admin/Controllers/ActivityLogController.cs b/src/Web/Grand.Web.Admin/Controllers/ActivityLogController.cs
index 725a5ac7c..d34e336a9 100644
--- a/src/Web/Grand.Web.Admin/Controllers/ActivityLogController.cs
+++ b/src/Web/Grand.Web.Admin/Controllers/ActivityLogController.cs
@@ -5,7 +5,6 @@ using Grand.Web.Common.DataSource;
using Grand.Web.Common.Security.Authorization;
using Grand.Web.Admin.Interfaces;
using Grand.Web.Admin.Models.ActivityLog;
-using Grand.Web.Admin.Models.Logging;
using Microsoft.AspNetCore.Mvc;
namespace Grand.Web.Admin.Controllers
diff --git a/src/Web/Grand.Web.Admin/Controllers/HomeController.cs b/src/Web/Grand.Web.Admin/Controllers/HomeController.cs
index b6699e85f..3cd257172 100644
--- a/src/Web/Grand.Web.Admin/Controllers/HomeController.cs
+++ b/src/Web/Grand.Web.Admin/Controllers/HomeController.cs
@@ -1,9 +1,7 @@
using Grand.Business.Core.Interfaces.Authentication;
using Grand.Business.Core.Queries.Checkout.Orders;
-using Grand.Business.Core.Extensions;
using Grand.Business.Core.Interfaces.Common.Directory;
using Grand.Business.Core.Interfaces.Common.Localization;
-using Grand.Business.Core.Interfaces.Common.Logging;
using Grand.Business.Core.Interfaces.Common.Stores;
using Grand.Business.Core.Queries.Customers;
using Grand.Business.Core.Interfaces.System.Reports;
@@ -15,6 +13,7 @@ using Grand.Web.Admin.Extensions;
using Grand.Web.Admin.Models.Home;
using MediatR;
using Microsoft.AspNetCore.Mvc;
+using Microsoft.Extensions.Logging;
namespace Grand.Web.Admin.Controllers
{
@@ -29,7 +28,7 @@ namespace Grand.Web.Admin.Controllers
private readonly IGroupService _groupService;
private readonly IOrderReportService _orderReportService;
private readonly IProductsReportService _productsReportService;
- private readonly ILogger _logger;
+ private readonly ILogger<HomeController> _logger;
private readonly IGrandAuthenticationService _authenticationService;
private readonly IMediator _mediator;
@@ -45,7 +44,7 @@ namespace Grand.Web.Admin.Controllers
IGroupService groupService,
IOrderReportService orderReportService,
IProductsReportService productsReportService,
- ILogger logger,
+ ILogger<HomeController> logger,
IGrandAuthenticationService authenticationService,
IMediator mediator)
{
@@ -200,13 +199,11 @@ namespace Grand.Web.Admin.Controllers
var currentCustomer = _workContext.CurrentCustomer;
if (currentCustomer == null || await _groupService.IsGuest(currentCustomer))
{
- _ = _logger.Information($"Access denied to anonymous request on {pageUrl}");
+ _logger.LogInformation("Access denied to anonymous request on {PageUrl}", pageUrl);
return View();
}
- _ = _logger.Information(
- $"Access denied to user #{currentCustomer.Email} '{currentCustomer.Email}' on {pageUrl}");
-
+ _logger.LogInformation("Access denied to user #{CurrentCustomerEmail} \'{CurrentCustomerEmail}\' on {PageUrl}", currentCustomer.Email, currentCustomer.Email, pageUrl);
return View();
}
diff --git a/src/Web/Grand.Web.Admin/Controllers/LoggerController.cs b/src/Web/Grand.Web.Admin/Controllers/LoggerController.cs
deleted file mode 100644
index 346809b6f..000000000
--- a/src/Web/Grand.Web.Admin/Controllers/LoggerController.cs
+++ /dev/null
@@ -1,102 +0,0 @@
-using Grand.Business.Core.Interfaces.Common.Localization;
-using Grand.Business.Core.Interfaces.Common.Logging;
-using Grand.Business.Core.Utilities.Common.Security;
-using Grand.Web.Admin.Interfaces;
-using Grand.Web.Admin.Models.Logging;
-using Grand.Web.Common.DataSource;
-using Grand.Web.Common.Security.Authorization;
-using Microsoft.AspNetCore.Mvc;
-
-namespace Grand.Web.Admin.Controllers
-{
- [PermissionAuthorize(PermissionSystemName.SystemLog)]
- public class LoggerController : BaseAdminController
- {
- private readonly ILogViewModelService _logViewModelService;
- private readonly ILogger _logger;
- private readonly ITranslationService _translationService;
-
- public LoggerController(ILogViewModelService logViewModelService, ILogger logger,
- ITranslationService translationService)
- {
- _logViewModelService = logViewModelService;
- _logger = logger;
- _translationService = translationService;
- }
-
- public IActionResult Index() => RedirectToAction("List");
-
- public IActionResult List()
- {
- var model = _logViewModelService.PrepareLogListModel();
- return View(model);
- }
-
- [HttpPost]
- public async Task<IActionResult> LogList(DataSourceRequest command, LogListModel model)
- {
- var (logModels, totalCount) = await _logViewModelService.PrepareLogModel(model, command.Page, command.PageSize);
- var gridModel = new DataSourceResult
- {
- Data = logModels.ToList(),
- Total = totalCount
- };
-
- return Json(gridModel);
- }
-
- [HttpPost]
- public async Task<IActionResult> ClearAll()
- {
- await _logger.ClearLog();
-
- Success(_translationService.GetResource("Admin.System.Log.Cleared"));
- return RedirectToAction("List");
- }
-
- public new async Task<IActionResult> View(string id)
- {
- var log = await _logger.GetLogById(id);
- if (log == null)
- //No log found with the specified id
- return RedirectToAction("List");
-
- var model = await _logViewModelService.PrepareLogModel(log);
-
- return View(model);
- }
-
- [HttpPost]
- public async Task<IActionResult> Delete(string id)
- {
- var log = await _logger.GetLogById(id);
- if (log == null)
- //No log found with the specified id
- return RedirectToAction("List");
- if (ModelState.IsValid)
- {
- await _logger.DeleteLog(log);
- Success(_translationService.GetResource("Admin.System.Log.Deleted"));
- return RedirectToAction("List");
- }
- Error(ModelState);
- return RedirectToAction("View", id);
- }
-
- [HttpPost]
- public async Task<IActionResult> DeleteSelected(ICollection<string> selectedIds)
- {
- if (ModelState.IsValid)
- {
- if (selectedIds != null)
- {
- var logItems = await _logger.GetLogByIds(selectedIds.ToArray());
- foreach (var logItem in logItems)
- await _logger.DeleteLog(logItem);
- }
- return Json(new { Result = true });
- }
- return ErrorForKendoGridJson(ModelState);
- }
- }
-}
diff --git a/src/Web/Grand.Web.Admin/Controllers/MaintenanceController.cs b/src/Web/Grand.Web.Admin/Controllers/MaintenanceController.cs
index 6da9e6790..72fc6464f 100644
--- a/src/Web/Grand.Web.Admin/Controllers/MaintenanceController.cs
+++ b/src/Web/Grand.Web.Admin/Controllers/MaintenanceController.cs
@@ -1,8 +1,6 @@
using Grand.Business.Core.Interfaces.Cms;
-using Grand.Business.Core.Extensions;
using Grand.Business.Core.Interfaces.Common.Directory;
using Grand.Business.Core.Interfaces.Common.Localization;
-using Grand.Business.Core.Interfaces.Common.Logging;
using Grand.Business.Core.Interfaces.Common.Seo;
using Grand.Business.Core.Utilities.Common.Security;
using Grand.Business.Core.Interfaces.Customers;
@@ -18,6 +16,7 @@ using Grand.Web.Common.Security.Authorization;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
+using Microsoft.Extensions.Logging;
namespace Grand.Web.Admin.Controllers
{
@@ -79,9 +78,6 @@ namespace Grand.Web.Admin.Controllers
if (TempData["DeleteActivityLog"] != null)
model.DeleteActivityLog = (bool)TempData["DeleteActivityLog"];
- if (TempData["DeleteSystemLog"] != null)
- model.DeleteSystemLog = (bool)TempData["DeleteSystemLog"];
-
if (TempData["NumberOfConvertItems"] != null)
{
model.ConvertedPictureModel = new MaintenanceModel.ConvertPictureModel {
@@ -128,21 +124,12 @@ namespace Grand.Web.Admin.Controllers
return RedirectToAction("Maintenance");
}
- [HttpPost]
- public async Task<IActionResult> MaintenanceDeleteSystemlog(MaintenanceModel model, [FromServices] ILogger logger)
- {
- await logger.ClearLog();
- TempData["DeleteSystemLog"] = true;
- return RedirectToAction("Maintenance");
- }
-
-
[HttpPost]
public async Task<IActionResult> MaintenanceConvertPicture(
[FromServices] IPictureService pictureService,
[FromServices] StorageSettings storageSettings,
[FromServices] MediaSettings mediaSettings,
- [FromServices] ILogger logger)
+ [FromServices] ILogger<MaintenanceController> logger)
{
var numberOfConvertItems = 0;
if (storageSettings.PictureStoreInDb)
@@ -159,7 +146,7 @@ namespace Grand.Web.Admin.Controllers
}
catch (Exception ex)
{
- _ = logger.Error($"Error on converting picture with id {picture.Id} to webp format", ex);
+ logger.LogError(ex, "Error on converting picture with id {PictureId} to webp format", picture.Id);
}
}
diff --git a/src/Web/Grand.Web.Admin/Controllers/PermissionController.cs b/src/Web/Grand.Web.Admin/Controllers/PermissionController.cs
index 47e74822b..1f0b96842 100644
--- a/src/Web/Grand.Web.Admin/Controllers/PermissionController.cs
+++ b/src/Web/Grand.Web.Admin/Controllers/PermissionController.cs
@@ -1,5 +1,4 @@
-using DotLiquid.Util;
-using Grand.Business.Core.Extensions;
+using Grand.Business.Core.Extensions;
using Grand.Business.Core.Interfaces.Common.Directory;
using Grand.Business.Core.Interfaces.Common.Localization;
using Grand.Business.Core.Interfaces.Common.Security;
diff --git a/src/Web/Grand.Web.Admin/Controllers/PluginController.cs b/src/Web/Grand.Web.Admin/Controllers/PluginController.cs
index 030b041b0..4531c999a 100644
--- a/src/Web/Grand.Web.Admin/Controllers/PluginController.cs
+++ b/src/Web/Grand.Web.Admin/Controllers/PluginController.cs
@@ -1,6 +1,4 @@
-using Grand.Business.Core.Extensions;
-using Grand.Business.Core.Interfaces.Common.Localization;
-using Grand.Business.Core.Interfaces.Common.Logging;
+using Grand.Business.Core.Interfaces.Common.Localization;
using Grand.Business.Core.Utilities.Common.Security;
using Grand.Infrastructure;
using Grand.Infrastructure.Configuration;
@@ -16,6 +14,7 @@ using Grand.Web.Common.Themes;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Hosting;
+using Microsoft.Extensions.Logging;
using System.IO.Compression;
using System.Reflection;
@@ -28,7 +27,7 @@ namespace Grand.Web.Admin.Controllers
private readonly ITranslationService _translationService;
private readonly IThemeProvider _themeProvider;
- private readonly ILogger _logger;
+ private readonly ILogger<PluginController> _logger;
private readonly IHostApplicationLifetime _applicationLifetime;
private readonly IServiceProvider _serviceProvider;
private readonly IWorkContext _workContext;
@@ -40,7 +39,7 @@ namespace Grand.Web.Admin.Controllers
public PluginController(
ITranslationService translationService,
IThemeProvider themeProvider,
- ILogger logger,
+ ILogger<PluginController> logger,
IHostApplicationLifetime applicationLifetime,
IWorkContext workContext,
IServiceProvider serviceProvider,
@@ -187,7 +186,7 @@ namespace Grand.Web.Admin.Controllers
Success(_translationService.GetResource("Admin.Plugins.Installed"));
- _ = _logger.InsertLog(Domain.Logging.LogLevel.Information, $"The plugin has been installed by the user {_workContext.CurrentCustomer.Email}");
+ _logger.LogInformation("The plugin has been installed by the user {CurrentCustomerEmail}", _workContext.CurrentCustomer.Email);
//stop application
_applicationLifetime.StopApplication();
@@ -220,7 +219,7 @@ namespace Grand.Web.Admin.Controllers
Success(_translationService.GetResource("Admin.Plugins.Uninstalled"));
- _ = _logger.InsertLog(Domain.Logging.LogLevel.Information, $"The plugin has been uninstalled by the user {_workContext.CurrentCustomer.Email}");
+ _logger.LogInformation("The plugin has been uninstalled by the user {CurrentCustomerEmail}", _workContext.CurrentCustomer.Email);
//stop application
_applicationLifetime.StopApplication();
@@ -262,7 +261,7 @@ namespace Grand.Web.Admin.Controllers
//uninstall plugin
Success(_translationService.GetResource("Admin.Plugins.Removed"));
- _ = _logger.InsertLog(Domain.Logging.LogLevel.Information, $"The plugin has been removed by the user {_workContext.CurrentCustomer.Email}");
+ _logger.LogInformation("The plugin has been removed by the user {CurrentCustomerEmail}", _workContext.CurrentCustomer.Email);
//stop application
_applicationLifetime.StopApplication();
@@ -277,7 +276,7 @@ namespace Grand.Web.Admin.Controllers
public IActionResult ReloadList()
{
- _ = _logger.InsertLog(Domain.Logging.LogLevel.Information, $"Reload list of plugins by the user {_workContext.CurrentCustomer.Email}");
+ _logger.LogInformation("Reload list of plugins by the user {CurrentCustomerEmail}", _workContext.CurrentCustomer.Email);
//stop application
_applicationLifetime.StopApplication();
@@ -326,7 +325,7 @@ namespace Grand.Web.Admin.Controllers
System.IO.File.Delete(zipFilePath);
}
- _ = _logger.InsertLog(Domain.Logging.LogLevel.Information, $"The plugin has been uploaded by the user {_workContext.CurrentCustomer.Email}");
+ _logger.LogInformation("The plugin has been uploaded by the user {CurrentCustomerEmail}", _workContext.CurrentCustomer.Email);
//stop application
_applicationLifetime.StopApplication();
@@ -436,7 +435,7 @@ namespace Grand.Web.Admin.Controllers
}
catch (Exception ex)
{
- _ = _logger.Error(ex.Message);
+ _logger.LogError(ex, ex.Message);
}
}
if (!supportedVersion)
diff --git a/src/Web/Grand.Web.Admin/Controllers/ProductTagsController.cs b/src/Web/Grand.Web.Admin/Controllers/ProductTagsController.cs
index dbcaf15af..3717f6396 100644
--- a/src/Web/Grand.Web.Admin/Controllers/ProductTagsController.cs
+++ b/src/Web/Grand.Web.Admin/Controllers/ProductTagsController.cs
@@ -6,7 +6,6 @@ using Grand.Web.Common.DataSource;
using Grand.Web.Common.Extensions;
using Grand.Web.Common.Security.Authorization;
using Grand.Domain.Seo;
-using Grand.Web.Admin.Extensions;
using Grand.Web.Admin.Models.Catalog;
using Microsoft.AspNetCore.Mvc;
diff --git a/src/Web/Grand.Web.Admin/Controllers/ShipmentController.cs b/src/Web/Grand.Web.Admin/Controllers/ShipmentController.cs
index f4ff51b5d..787608178 100644
--- a/src/Web/Grand.Web.Admin/Controllers/ShipmentController.cs
+++ b/src/Web/Grand.Web.Admin/Controllers/ShipmentController.cs
@@ -8,7 +8,6 @@ using Grand.Business.Core.Utilities.Common.Security;
using Grand.Domain.Orders;
using Grand.Domain.Shipping;
using Grand.Infrastructure;
-using Grand.Web.Admin.Extensions;
using Grand.Web.Admin.Interfaces;
using Grand.Web.Admin.Models.Orders;
using Grand.Web.Common.DataSource;
diff --git a/src/Web/Grand.Web.Admin/Controllers/SystemController.cs b/src/Web/Grand.Web.Admin/Controllers/SystemController.cs
index d7c8edc79..50077dab5 100644
--- a/src/Web/Grand.Web.Admin/Controllers/SystemController.cs
+++ b/src/Web/Grand.Web.Admin/Controllers/SystemController.cs
@@ -4,7 +4,6 @@ using Grand.Business.Core.Interfaces.Checkout.Payments;
using Grand.Business.Core.Interfaces.Checkout.Shipping;
using Grand.Business.Core.Interfaces.Common.Directory;
using Grand.Business.Core.Interfaces.Common.Localization;
-using Grand.Business.Core.Interfaces.Common.Logging;
using Grand.Business.Core.Utilities.Common.Security;
using Grand.Business.Core.Interfaces.System.MachineNameProvider;
using Grand.Domain.Directory;
@@ -19,6 +18,7 @@ using Grand.Web.Common.Security.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Hosting;
+using Microsoft.Extensions.Logging;
using System.Runtime.InteropServices;
namespace Grand.Web.Admin.Controllers
@@ -38,7 +38,7 @@ namespace Grand.Web.Admin.Controllers
private readonly IMachineNameProvider _machineNameProvider;
private readonly IHostApplicationLifetime _applicationLifetime;
private readonly IWebHostEnvironment _webHostEnvironment;
- private readonly ILogger _logger;
+ private readonly ILogger<SystemController> _logger;
private readonly CurrencySettings _currencySettings;
private readonly MeasureSettings _measureSettings;
@@ -59,7 +59,7 @@ namespace Grand.Web.Admin.Controllers
IMachineNameProvider machineNameProvider,
IHostApplicationLifetime applicationLifetime,
IWebHostEnvironment webHostEnvironment,
- ILogger logger,
+ ILogger<SystemController> logger,
CurrencySettings currencySettings,
MeasureSettings measureSettings,
ExtensionsConfig extConfig, AccessControlConfig accessControlConfig)
@@ -279,7 +279,7 @@ namespace Grand.Web.Admin.Controllers
public async Task<IActionResult> ClearCache(string returnUrl, [FromServices] ICacheBase cacheBase)
{
- _ = _logger.InsertLog(Domain.Logging.LogLevel.Information, $"Clear cache has been done by the user: {_workContext.CurrentCustomer.Email}");
+ _logger.LogInformation($"Clear cache has been done by the user: {_workContext.CurrentCustomer.Email}");
await cacheBase.Clear();
@@ -295,7 +295,7 @@ namespace Grand.Web.Admin.Controllers
public IActionResult RestartApplication(string returnUrl = "")
{
- _ = _logger.InsertLog(Domain.Logging.LogLevel.Information, $"The application has been restarted by the user {_workContext.CurrentCustomer.Email}");
+ _logger.LogInformation($"The application has been restarted by the user {_workContext.CurrentCustomer.Email}");
//stop application
_applicationLifetime.StopApplication();
diff --git a/src/Web/Grand.Web.Admin/Extensions/Mapping/ActivityLogMappingExtensions.cs b/src/Web/Grand.Web.Admin/Extensions/Mapping/ActivityLogMappingExtensions.cs
new file mode 100644
index 000000000..4512edfe7
--- /dev/null
+++ b/src/Web/Grand.Web.Admin/Extensions/Mapping/ActivityLogMappingExtensions.cs
@@ -0,0 +1,23 @@
+using Grand.Domain.Logging;
+using Grand.Infrastructure.Mapper;
+using Grand.Web.Admin.Models.ActivityLog;
+
+namespace Grand.Web.Admin.Extensions.Mapping;
+
+public static class ActivityLogMappingExtensions
+{
+ public static ActivityLogTypeModel ToModel(this ActivityLogType entity)
+ {
+ return entity.MapTo<ActivityLogType, ActivityLogTypeModel>();
+ }
+
+ public static ActivityLogModel ToModel(this ActivityLog entity)
+ {
+ return entity.MapTo<ActivityLog, ActivityLogModel>();
+ }
+
+ public static ActivityStatsModel ToModel(this ActivityStats entity)
+ {
+ return entity.MapTo<ActivityStats, ActivityStatsModel>();
+ }
+}
\ No newline at end of file
diff --git a/src/Web/Grand.Web.Admin/Extensions/Mapping/LogMappingExtensions.cs b/src/Web/Grand.Web.Admin/Extensions/Mapping/LogMappingExtensions.cs
deleted file mode 100644
index ffa830a5e..000000000
--- a/src/Web/Grand.Web.Admin/Extensions/Mapping/LogMappingExtensions.cs
+++ /dev/null
@@ -1,39 +0,0 @@
-using Grand.Domain.Logging;
-using Grand.Infrastructure.Mapper;
-using Grand.Web.Admin.Models.Logging;
-
-namespace Grand.Web.Admin.Extensions.Mapping
-{
- public static class LogMappingExtensions
- {
- public static LogModel ToModel(this Log entity)
- {
- return entity.MapTo<Log, LogModel>();
- }
-
- public static Log ToEntity(this LogModel model)
- {
- return model.MapTo<LogModel, Log>();
- }
-
- public static Log ToEntity(this LogModel model, Log destination)
- {
- return model.MapTo(destination);
- }
-
- public static ActivityLogTypeModel ToModel(this ActivityLogType entity)
- {
- return entity.MapTo<ActivityLogType, ActivityLogTypeModel>();
- }
-
- public static ActivityLogModel ToModel(this ActivityLog entity)
- {
- return entity.MapTo<ActivityLog, ActivityLogModel>();
- }
-
- public static ActivityStatsModel ToModel(this ActivityStats entity)
- {
- return entity.MapTo<ActivityStats, ActivityStatsModel>();
- }
- }
-}
\ No newline at end of file
diff --git a/src/Web/Grand.Web.Admin/Interfaces/IActivityLogViewModelService.cs b/src/Web/Grand.Web.Admin/Interfaces/IActivityLogViewModelService.cs
index 9696c5423..3c31b6974 100644
--- a/src/Web/Grand.Web.Admin/Interfaces/IActivityLogViewModelService.cs
+++ b/src/Web/Grand.Web.Admin/Interfaces/IActivityLogViewModelService.cs
@@ -1,4 +1,4 @@
-using Grand.Web.Admin.Models.Logging;
+using Grand.Web.Admin.Models.ActivityLog;
namespace Grand.Web.Admin.Interfaces
{
diff --git a/src/Web/Grand.Web.Admin/Interfaces/ILogViewModelService.cs b/src/Web/Grand.Web.Admin/Interfaces/ILogViewModelService.cs
deleted file mode 100644
index 8609c6e62..000000000
--- a/src/Web/Grand.Web.Admin/Interfaces/ILogViewModelService.cs
+++ /dev/null
@@ -1,12 +0,0 @@
-using Grand.Domain.Logging;
-using Grand.Web.Admin.Models.Logging;
-
-namespace Grand.Web.Admin.Interfaces
-{
- public interface ILogViewModelService
- {
- LogListModel PrepareLogListModel();
- Task<(IEnumerable<LogModel> logModels, int totalCount)> PrepareLogModel(LogListModel model, int pageIndex, int pageSize);
- Task<LogModel> PrepareLogModel(Log log);
- }
-}
diff --git a/src/Web/Grand.Web.Admin/Mapper/ActivityLogTypeProfile.cs b/src/Web/Grand.Web.Admin/Mapper/ActivityLogTypeProfile.cs
index 0a2838332..15d2c87c5 100644
--- a/src/Web/Grand.Web.Admin/Mapper/ActivityLogTypeProfile.cs
+++ b/src/Web/Grand.Web.Admin/Mapper/ActivityLogTypeProfile.cs
@@ -1,7 +1,7 @@
using AutoMapper;
using Grand.Domain.Logging;
using Grand.Infrastructure.Mapper;
-using Grand.Web.Admin.Models.Logging;
+using Grand.Web.Admin.Models.ActivityLog;
namespace Grand.Web.Admin.Mapper
{
diff --git a/src/Web/Grand.Web.Admin/Mapper/AddressAttributeProfile.cs b/src/Web/Grand.Web.Admin/Mapper/AddressAttributeProfile.cs
index de6d5c373..162ab291b 100644
--- a/src/Web/Grand.Web.Admin/Mapper/AddressAttributeProfile.cs
+++ b/src/Web/Grand.Web.Admin/Mapper/AddressAttributeProfile.cs
@@ -1,7 +1,6 @@
using AutoMapper;
using Grand.Domain.Common;
using Grand.Infrastructure.Mapper;
-using Grand.Web.Admin.Extensions;
using Grand.Web.Admin.Models.Common;
using Grand.Web.Common.Extensions;
diff --git a/src/Web/Grand.Web.Admin/Mapper/AddressAttributeValueProfile.cs b/src/Web/Grand.Web.Admin/Mapper/AddressAttributeValueProfile.cs
index db6bb210d..cbb9aa8a0 100644
--- a/src/Web/Grand.Web.Admin/Mapper/AddressAttributeValueProfile.cs
+++ b/src/Web/Grand.Web.Admin/Mapper/AddressAttributeValueProfile.cs
@@ -1,7 +1,6 @@
using AutoMapper;
using Grand.Domain.Common;
using Grand.Infrastructure.Mapper;
-using Grand.Web.Admin.Extensions;
using Grand.Web.Admin.Models.Common;
using Grand.Web.Common.Extensions;
diff --git a/src/Web/Grand.Web.Admin/Mapper/BlogCategoryProfile.cs b/src/Web/Grand.Web.Admin/Mapper/BlogCategoryProfile.cs
index d370e328d..4a82c9f13 100644
--- a/src/Web/Grand.Web.Admin/Mapper/BlogCategoryProfile.cs
+++ b/src/Web/Grand.Web.Admin/Mapper/BlogCategoryProfile.cs
@@ -1,7 +1,6 @@
using AutoMapper;
using Grand.Domain.Blogs;
using Grand.Infrastructure.Mapper;
-using Grand.Web.Admin.Extensions;
using Grand.Web.Admin.Models.Blogs;
using Grand.Web.Common.Extensions;
diff --git a/src/Web/Grand.Web.Admin/Mapper/CheckoutAttributeProfile.cs b/src/Web/Grand.Web.Admin/Mapper/CheckoutAttributeProfile.cs
index 959de22ca..c6f2694a9 100644
--- a/src/Web/Grand.Web.Admin/Mapper/CheckoutAttributeProfile.cs
+++ b/src/Web/Grand.Web.Admin/Mapper/CheckoutAttributeProfile.cs
@@ -1,7 +1,6 @@
using AutoMapper;
using Grand.Domain.Orders;
using Grand.Infrastructure.Mapper;
-using Grand.Web.Admin.Extensions;
using Grand.Web.Admin.Models.Orders;
using Grand.Web.Common.Extensions;
diff --git a/src/Web/Grand.Web.Admin/Mapper/ContactAttributeProfile.cs b/src/Web/Grand.Web.Admin/Mapper/ContactAttributeProfile.cs
index 9bd47001b..2be7949a0 100644
--- a/src/Web/Grand.Web.Admin/Mapper/ContactAttributeProfile.cs
+++ b/src/Web/Grand.Web.Admin/Mapper/ContactAttributeProfile.cs
@@ -1,7 +1,6 @@
using AutoMapper;
using Grand.Domain.Messages;
using Grand.Infrastructure.Mapper;
-using Grand.Web.Admin.Extensions;
using Grand.Web.Admin.Models.Messages;
using Grand.Web.Common.Extensions;
diff --git a/src/Web/Grand.Web.Admin/Mapper/CountryProfile.cs b/src/Web/Grand.Web.Admin/Mapper/CountryProfile.cs
index 62ba215c1..6d22c9d9d 100644
--- a/src/Web/Grand.Web.Admin/Mapper/CountryProfile.cs
+++ b/src/Web/Grand.Web.Admin/Mapper/CountryProfile.cs
@@ -1,7 +1,6 @@
using AutoMapper;
using Grand.Domain.Directory;
using Grand.Infrastructure.Mapper;
-using Grand.Web.Admin.Extensions;
using Grand.Web.Admin.Models.Directory;
using Grand.Web.Common.Extensions;
diff --git a/src/Web/Grand.Web.Admin/Mapper/CourseProfile.cs b/src/Web/Grand.Web.Admin/Mapper/CourseProfile.cs
index bc00f38f5..56c0a1b3a 100644
--- a/src/Web/Grand.Web.Admin/Mapper/CourseProfile.cs
+++ b/src/Web/Grand.Web.Admin/Mapper/CourseProfile.cs
@@ -1,7 +1,6 @@
using AutoMapper;
using Grand.Domain.Courses;
using Grand.Infrastructure.Mapper;
-using Grand.Web.Admin.Extensions;
using Grand.Web.Admin.Models.Courses;
using Grand.Web.Common.Extensions;
diff --git a/src/Web/Grand.Web.Admin/Mapper/CurrencyProfile.cs b/src/Web/Grand.Web.Admin/Mapper/CurrencyProfile.cs
index b0971f179..c327184b3 100644
--- a/src/Web/Grand.Web.Admin/Mapper/CurrencyProfile.cs
+++ b/src/Web/Grand.Web.Admin/Mapper/CurrencyProfile.cs
@@ -1,7 +1,6 @@
using AutoMapper;
using Grand.Domain.Directory;
using Grand.Infrastructure.Mapper;
-using Grand.Web.Admin.Extensions;
using Grand.Web.Admin.Models.Directory;
using Grand.Web.Common.Extensions;
diff --git a/src/Web/Grand.Web.Admin/Mapper/CustomerAttributeProfile.cs b/src/Web/Grand.Web.Admin/Mapper/CustomerAttributeProfile.cs
index 15abd74a9..35a604487 100644
--- a/src/Web/Grand.Web.Admin/Mapper/CustomerAttributeProfile.cs
+++ b/src/Web/Grand.Web.Admin/Mapper/CustomerAttributeProfile.cs
@@ -1,7 +1,6 @@
using AutoMapper;
using Grand.Domain.Customers;
using Grand.Infrastructure.Mapper;
-using Grand.Web.Admin.Extensions;
using Grand.Web.Admin.Models.Customers;
using Grand.Web.Common.Extensions;
diff --git a/src/Web/Grand.Web.Admin/Mapper/CustomerAttributeValueProfile.cs b/src/Web/Grand.Web.Admin/Mapper/CustomerAttributeValueProfile.cs
index 8b7184d4e..fe623f226 100644
--- a/src/Web/Grand.Web.Admin/Mapper/CustomerAttributeValueProfile.cs
+++ b/src/Web/Grand.Web.Admin/Mapper/CustomerAttributeValueProfile.cs
@@ -1,7 +1,6 @@
using AutoMapper;
using Grand.Domain.Customers;
using Grand.Infrastructure.Mapper;
-using Grand.Web.Admin.Extensions;
using Grand.Web.Admin.Models.Customers;
using Grand.Web.Common.Extensions;
diff --git a/src/Web/Grand.Web.Admin/Mapper/DeliveryDateProfile.cs b/src/Web/Grand.Web.Admin/Mapper/DeliveryDateProfile.cs
index f4dae1a8d..0738bc6b1 100644
--- a/src/Web/Grand.Web.Admin/Mapper/DeliveryDateProfile.cs
+++ b/src/Web/Grand.Web.Admin/Mapper/DeliveryDateProfile.cs
@@ -1,7 +1,6 @@
using AutoMapper;
using Grand.Domain.Shipping;
using Grand.Infrastructure.Mapper;
-using Grand.Web.Admin.Extensions;
using Grand.Web.Admin.Models.Shipping;
using Grand.Web.Common.Extensions;
diff --git a/src/Web/Grand.Web.Admin/Mapper/LogProfile.cs b/src/Web/Grand.Web.Admin/Mapper/LogProfile.cs
deleted file mode 100644
index 87c51b8c6..000000000
--- a/src/Web/Grand.Web.Admin/Mapper/LogProfile.cs
+++ /dev/null
@@ -1,23 +0,0 @@
-using AutoMapper;
-using Grand.Domain.Logging;
-using Grand.Infrastructure.Mapper;
-using Grand.Web.Admin.Models.Logging;
-
-namespace Grand.Web.Admin.Mapper
-{
- public class LogProfile : Profile, IAutoMapperProfile
- {
- public LogProfile()
- {
- CreateMap<Log, LogModel>()
- .ForMember(dest => dest.CustomerEmail, mo => mo.Ignore())
- .ForMember(dest => dest.CreatedOn, mo => mo.Ignore());
-
- CreateMap<LogModel, Log>()
- .ForMember(dest => dest.Id, mo => mo.Ignore())
- .ForMember(dest => dest.CreatedOnUtc, mo => mo.Ignore());
- }
-
- public int Order => 0;
- }
-}
\ No newline at end of file
diff --git a/src/Web/Grand.Web.Admin/Mapper/MerchandiseReturnActionProfile.cs b/src/Web/Grand.Web.Admin/Mapper/MerchandiseReturnActionProfile.cs
index be3a68504..c8a4586b4 100644
--- a/src/Web/Grand.Web.Admin/Mapper/MerchandiseReturnActionProfile.cs
+++ b/src/Web/Grand.Web.Admin/Mapper/MerchandiseReturnActionProfile.cs
@@ -1,7 +1,6 @@
using AutoMapper;
using Grand.Domain.Orders;
using Grand.Infrastructure.Mapper;
-using Grand.Web.Admin.Extensions;
using Grand.Web.Admin.Models.Settings;
using Grand.Web.Common.Extensions;
diff --git a/src/Web/Grand.Web.Admin/Mapper/MerchandiseReturnReasonProfile.cs b/src/Web/Grand.Web.Admin/Mapper/MerchandiseReturnReasonProfile.cs
index e3cc368c1..754e8dc94 100644
--- a/src/Web/Grand.Web.Admin/Mapper/MerchandiseReturnReasonProfile.cs
+++ b/src/Web/Grand.Web.Admin/Mapper/MerchandiseReturnReasonProfile.cs
@@ -1,7 +1,6 @@
using AutoMapper;
using Grand.Domain.Orders;
using Grand.Infrastructure.Mapper;
-using Grand.Web.Admin.Extensions;
using Grand.Web.Admin.Models.Settings;
using Grand.Web.Common.Extensions;
diff --git a/src/Web/Grand.Web.Admin/Mapper/MessageTemplateProfile.cs b/src/Web/Grand.Web.Admin/Mapper/MessageTemplateProfile.cs
index f184b4662..d7738dfcb 100644
--- a/src/Web/Grand.Web.Admin/Mapper/MessageTemplateProfile.cs
+++ b/src/Web/Grand.Web.Admin/Mapper/MessageTemplateProfile.cs
@@ -1,7 +1,6 @@
using AutoMapper;
using Grand.Domain.Messages;
using Grand.Infrastructure.Mapper;
-using Grand.Web.Admin.Extensions;
using Grand.Web.Admin.Models.Messages;
using Grand.Web.Common.Extensions;
diff --git a/src/Web/Grand.Web.Admin/Mapper/NewsletterCategoryProfile.cs b/src/Web/Grand.Web.Admin/Mapper/NewsletterCategoryProfile.cs
index 98f0d3d44..93217a4b1 100644
--- a/src/Web/Grand.Web.Admin/Mapper/NewsletterCategoryProfile.cs
+++ b/src/Web/Grand.Web.Admin/Mapper/NewsletterCategoryProfile.cs
@@ -1,7 +1,6 @@
using AutoMapper;
using Grand.Domain.Messages;
using Grand.Infrastructure.Mapper;
-using Grand.Web.Admin.Extensions;
using Grand.Web.Admin.Models.Messages;
using Grand.Web.Common.Extensions;
diff --git a/src/Web/Grand.Web.Admin/Mapper/PredefinedProductAttributeValueProfile.cs b/src/Web/Grand.Web.Admin/Mapper/PredefinedProductAttributeValueProfile.cs
index 3a2cd659a..a993aab14 100644
--- a/src/Web/Grand.Web.Admin/Mapper/PredefinedProductAttributeValueProfile.cs
+++ b/src/Web/Grand.Web.Admin/Mapper/PredefinedProductAttributeValueProfile.cs
@@ -1,7 +1,6 @@
using AutoMapper;
using Grand.Domain.Catalog;
using Grand.Infrastructure.Mapper;
-using Grand.Web.Admin.Extensions;
using Grand.Web.Admin.Models.Catalog;
using Grand.Web.Common.Extensions;
diff --git a/src/Web/Grand.Web.Admin/Mapper/ProductAttributeProfile.cs b/src/Web/Grand.Web.Admin/Mapper/ProductAttributeProfile.cs
index d0f3257e1..5ad99ee72 100644
--- a/src/Web/Grand.Web.Admin/Mapper/ProductAttributeProfile.cs
+++ b/src/Web/Grand.Web.Admin/Mapper/ProductAttributeProfile.cs
@@ -1,7 +1,6 @@
using AutoMapper;
using Grand.Domain.Catalog;
using Grand.Infrastructure.Mapper;
-using Grand.Web.Admin.Extensions;
using Grand.Web.Admin.Models.Catalog;
using Grand.Web.Common.Extensions;
diff --git a/src/Web/Grand.Web.Admin/Mapper/ShippingMethodProfile.cs b/src/Web/Grand.Web.Admin/Mapper/ShippingMethodProfile.cs
index 96f01a832..fe08b1f46 100644
--- a/src/Web/Grand.Web.Admin/Mapper/ShippingMethodProfile.cs
+++ b/src/Web/Grand.Web.Admin/Mapper/ShippingMethodProfile.cs
@@ -1,7 +1,6 @@
using AutoMapper;
using Grand.Domain.Shipping;
using Grand.Infrastructure.Mapper;
-using Grand.Web.Admin.Extensions;
using Grand.Web.Admin.Models.Shipping;
using Grand.Web.Common.Extensions;
diff --git a/src/Web/Grand.Web.Admin/Mapper/SpecificationAttributeProfile.cs b/src/Web/Grand.Web.Admin/Mapper/SpecificationAttributeProfile.cs
index 1323d5333..a4d43c381 100644
--- a/src/Web/Grand.Web.Admin/Mapper/SpecificationAttributeProfile.cs
+++ b/src/Web/Grand.Web.Admin/Mapper/SpecificationAttributeProfile.cs
@@ -1,7 +1,6 @@
using AutoMapper;
using Grand.Domain.Catalog;
using Grand.Infrastructure.Mapper;
-using Grand.Web.Admin.Extensions;
using Grand.Web.Admin.Models.Catalog;
using Grand.Web.Common.Extensions;
diff --git a/src/Web/Grand.Web.Admin/Mapper/StateProvinceProfile.cs b/src/Web/Grand.Web.Admin/Mapper/StateProvinceProfile.cs
index 5f3cc8035..2669348fe 100644
--- a/src/Web/Grand.Web.Admin/Mapper/StateProvinceProfile.cs
+++ b/src/Web/Grand.Web.Admin/Mapper/StateProvinceProfile.cs
@@ -1,7 +1,6 @@
using AutoMapper;
using Grand.Domain.Directory;
using Grand.Infrastructure.Mapper;
-using Grand.Web.Admin.Extensions;
using Grand.Web.Admin.Models.Directory;
using Grand.Web.Common.Extensions;
diff --git a/src/Web/Grand.Web.Admin/Mapper/StoreProfile.cs b/src/Web/Grand.Web.Admin/Mapper/StoreProfile.cs
index 5c6d2d269..94fc2eb52 100644
--- a/src/Web/Grand.Web.Admin/Mapper/StoreProfile.cs
+++ b/src/Web/Grand.Web.Admin/Mapper/StoreProfile.cs
@@ -1,7 +1,6 @@
using AutoMapper;
using Grand.Domain.Stores;
using Grand.Infrastructure.Mapper;
-using Grand.Web.Admin.Extensions;
using Grand.Web.Admin.Models.Stores;
using Grand.Web.Common.Extensions;
diff --git a/src/Web/Grand.Web.Admin/Models/Logging/ActivityLogModel.cs b/src/Web/Grand.Web.Admin/Models/ActivityLog/ActivityLogModel.cs
similarity index 97%
rename from src/Web/Grand.Web.Admin/Models/Logging/ActivityLogModel.cs
rename to src/Web/Grand.Web.Admin/Models/ActivityLog/ActivityLogModel.cs
index 4a75f24b5..47d724ad2 100644
--- a/src/Web/Grand.Web.Admin/Models/Logging/ActivityLogModel.cs
+++ b/src/Web/Grand.Web.Admin/Models/ActivityLog/ActivityLogModel.cs
@@ -1,7 +1,7 @@
using Grand.Infrastructure.ModelBinding;
using Grand.Infrastructure.Models;
-namespace Grand.Web.Admin.Models.Logging
+namespace Grand.Web.Admin.Models.ActivityLog
{
public class ActivityLogModel : BaseEntityModel
{
diff --git a/src/Web/Grand.Web.Admin/Models/Logging/ActivityLogSearchModel.cs b/src/Web/Grand.Web.Admin/Models/ActivityLog/ActivityLogSearchModel.cs
similarity index 96%
rename from src/Web/Grand.Web.Admin/Models/Logging/ActivityLogSearchModel.cs
rename to src/Web/Grand.Web.Admin/Models/ActivityLog/ActivityLogSearchModel.cs
index 3783e837c..95f48388b 100644
--- a/src/Web/Grand.Web.Admin/Models/Logging/ActivityLogSearchModel.cs
+++ b/src/Web/Grand.Web.Admin/Models/ActivityLog/ActivityLogSearchModel.cs
@@ -3,7 +3,7 @@ using Grand.Infrastructure.Models;
using Microsoft.AspNetCore.Mvc.Rendering;
using System.ComponentModel.DataAnnotations;
-namespace Grand.Web.Admin.Models.Logging
+namespace Grand.Web.Admin.Models.ActivityLog
{
public class ActivityLogSearchModel : BaseModel
{
diff --git a/src/Web/Grand.Web.Admin/Models/Logging/ActivityLogTypeModel.cs b/src/Web/Grand.Web.Admin/Models/ActivityLog/ActivityLogTypeModel.cs
similarity index 90%
rename from src/Web/Grand.Web.Admin/Models/Logging/ActivityLogTypeModel.cs
rename to src/Web/Grand.Web.Admin/Models/ActivityLog/ActivityLogTypeModel.cs
index 84704e504..000021366 100644
--- a/src/Web/Grand.Web.Admin/Models/Logging/ActivityLogTypeModel.cs
+++ b/src/Web/Grand.Web.Admin/Models/ActivityLog/ActivityLogTypeModel.cs
@@ -1,7 +1,7 @@
using Grand.Infrastructure.ModelBinding;
using Grand.Infrastructure.Models;
-namespace Grand.Web.Admin.Models.Logging
+namespace Grand.Web.Admin.Models.ActivityLog
{
public class ActivityLogTypeModel : BaseEntityModel
{
diff --git a/src/Web/Grand.Web.Admin/Models/Common/MaintenanceModel.cs b/src/Web/Grand.Web.Admin/Models/Common/MaintenanceModel.cs
index b06122488..2363403b2 100644
--- a/src/Web/Grand.Web.Admin/Models/Common/MaintenanceModel.cs
+++ b/src/Web/Grand.Web.Admin/Models/Common/MaintenanceModel.cs
@@ -20,7 +20,6 @@ namespace Grand.Web.Admin.Models.Common
public ConvertPictureModel ConvertedPictureModel { get; set; }
public bool DeleteActivityLog { get; set; }
- public bool DeleteSystemLog { get; set; }
#region Nested classes
diff --git a/src/Web/Grand.Web.Admin/Models/Logging/LogListModel.cs b/src/Web/Grand.Web.Admin/Models/Logging/LogListModel.cs
deleted file mode 100644
index 29f1e24b2..000000000
--- a/src/Web/Grand.Web.Admin/Models/Logging/LogListModel.cs
+++ /dev/null
@@ -1,33 +0,0 @@
-using Grand.Infrastructure.ModelBinding;
-using Grand.Infrastructure.Models;
-using Microsoft.AspNetCore.Mvc.Rendering;
-using System.ComponentModel.DataAnnotations;
-
-namespace Grand.Web.Admin.Models.Logging
-{
- public class LogListModel : BaseModel
- {
- public LogListModel()
- {
- AvailableLogLevels = new List<SelectListItem>();
- }
-
- [GrandResourceDisplayName("Admin.System.Log.List.CreatedOnFrom")]
- [UIHint("DateNullable")]
- public DateTime? CreatedOnFrom { get; set; }
-
- [GrandResourceDisplayName("Admin.System.Log.List.CreatedOnTo")]
- [UIHint("DateNullable")]
- public DateTime? CreatedOnTo { get; set; }
-
- [GrandResourceDisplayName("Admin.System.Log.List.Message")]
-
- public string Message { get; set; }
-
- [GrandResourceDisplayName("Admin.System.Log.List.LogLevel")]
- public int LogLevelId { get; set; }
-
-
- public IList<SelectListItem> AvailableLogLevels { get; set; }
- }
-}
\ No newline at end of file
diff --git a/src/Web/Grand.Web.Admin/Models/Logging/LogModel.cs b/src/Web/Grand.Web.Admin/Models/Logging/LogModel.cs
deleted file mode 100644
index b254ebb52..000000000
--- a/src/Web/Grand.Web.Admin/Models/Logging/LogModel.cs
+++ /dev/null
@@ -1,39 +0,0 @@
-using Grand.Infrastructure.ModelBinding;
-using Grand.Infrastructure.Models;
-
-namespace Grand.Web.Admin.Models.Logging
-{
- public class LogModel : BaseEntityModel
- {
- [GrandResourceDisplayName("Admin.System.Log.Fields.LogLevel")]
- public string LogLevel { get; set; }
-
- [GrandResourceDisplayName("Admin.System.Log.Fields.ShortMessage")]
-
- public string ShortMessage { get; set; }
-
- [GrandResourceDisplayName("Admin.System.Log.Fields.FullMessage")]
-
- public string FullMessage { get; set; }
-
- [GrandResourceDisplayName("Admin.System.Log.Fields.IPAddress")]
-
- public string IpAddress { get; set; }
-
- [GrandResourceDisplayName("Admin.System.Log.Fields.Customer")]
- public string CustomerId { get; set; }
- [GrandResourceDisplayName("Admin.System.Log.Fields.Customer")]
- public string CustomerEmail { get; set; }
-
- [GrandResourceDisplayName("Admin.System.Log.Fields.PageURL")]
-
- public string PageUrl { get; set; }
-
- [GrandResourceDisplayName("Admin.System.Log.Fields.ReferrerURL")]
-
- public string ReferrerUrl { get; set; }
-
- [GrandResourceDisplayName("Admin.System.Log.Fields.CreatedOn")]
- public DateTime CreatedOn { get; set; }
- }
-}
\ No newline at end of file
diff --git a/src/Web/Grand.Web.Admin/Program.cs b/src/Web/Grand.Web.Admin/Program.cs
index 56488e919..e77dd2699 100644
--- a/src/Web/Grand.Web.Admin/Program.cs
+++ b/src/Web/Grand.Web.Admin/Program.cs
@@ -18,7 +18,9 @@ builder.Host.UseDefaultServiceProvider((_, options) =>
});
//use serilog
-builder.Host.UseSerilog();
+builder.Host.UseSerilog((context, services, configuration) => configuration
+ .ReadFrom.Configuration(context.Configuration)
+ .Enrich.FromLogContext());
//add configuration
builder.Host.ConfigureAppConfiguration((hostingContext, config) =>
@@ -38,9 +40,6 @@ builder.Host.ConfigureAppConfiguration((hostingContext, config) =>
});
-//create logger
-Log.Logger = new LoggerConfiguration().ReadFrom.Configuration(builder.Configuration).CreateLogger();
-
//add services
Grand.Infrastructure.StartupBase.ConfigureServices(builder.Services, builder.Configuration);
diff --git a/src/Web/Grand.Web.Admin/Services/ActivityLogViewModelService.cs b/src/Web/Grand.Web.Admin/Services/ActivityLogViewModelService.cs
index 3ce42d7e1..7337a889f 100644
--- a/src/Web/Grand.Web.Admin/Services/ActivityLogViewModelService.cs
+++ b/src/Web/Grand.Web.Admin/Services/ActivityLogViewModelService.cs
@@ -7,7 +7,7 @@ using Grand.Business.Core.Interfaces.Common.Logging;
using Grand.Business.Core.Interfaces.Customers;
using Grand.Web.Admin.Extensions.Mapping;
using Grand.Web.Admin.Interfaces;
-using Grand.Web.Admin.Models.Logging;
+using Grand.Web.Admin.Models.ActivityLog;
using Microsoft.AspNetCore.Mvc.Rendering;
namespace Grand.Web.Admin.Services
diff --git a/src/Web/Grand.Web.Admin/Services/CustomerGroupViewModelService.cs b/src/Web/Grand.Web.Admin/Services/CustomerGroupViewModelService.cs
index 815db1148..17ec46014 100644
--- a/src/Web/Grand.Web.Admin/Services/CustomerGroupViewModelService.cs
+++ b/src/Web/Grand.Web.Admin/Services/CustomerGroupViewModelService.cs
@@ -7,7 +7,6 @@ using Grand.Business.Core.Interfaces.Customers;
using Grand.Domain.Catalog;
using Grand.Domain.Customers;
using Grand.Infrastructure;
-using Grand.Web.Admin.Extensions;
using Grand.Web.Admin.Extensions.Mapping;
using Grand.Web.Admin.Interfaces;
using Grand.Web.Admin.Models.Catalog;
diff --git a/src/Web/Grand.Web.Admin/Services/CustomerTagViewModelService.cs b/src/Web/Grand.Web.Admin/Services/CustomerTagViewModelService.cs
index 9da5e6919..097cfe842 100644
--- a/src/Web/Grand.Web.Admin/Services/CustomerTagViewModelService.cs
+++ b/src/Web/Grand.Web.Admin/Services/CustomerTagViewModelService.cs
@@ -8,7 +8,6 @@ using Grand.Business.Core.Interfaces.Marketing.Customers;
using Grand.Domain.Catalog;
using Grand.Domain.Customers;
using Grand.Infrastructure;
-using Grand.Web.Admin.Extensions;
using Grand.Web.Admin.Extensions.Mapping;
using Grand.Web.Admin.Interfaces;
using Grand.Web.Admin.Models.Catalog;
diff --git a/src/Web/Grand.Web.Admin/Services/CustomerViewModelService.cs b/src/Web/Grand.Web.Admin/Services/CustomerViewModelService.cs
index 8540f0ac5..50f334a27 100644
--- a/src/Web/Grand.Web.Admin/Services/CustomerViewModelService.cs
+++ b/src/Web/Grand.Web.Admin/Services/CustomerViewModelService.cs
@@ -24,7 +24,6 @@ using Grand.Domain.Orders;
using Grand.Domain.Tax;
using Grand.Infrastructure;
using Grand.SharedKernel;
-using Grand.Web.Admin.Extensions;
using Grand.Web.Admin.Extensions.Mapping;
using Grand.Web.Admin.Interfaces;
using Grand.Web.Admin.Models.Catalog;
diff --git a/src/Web/Grand.Web.Admin/Services/DiscountViewModelService.cs b/src/Web/Grand.Web.Admin/Services/DiscountViewModelService.cs
index 99f338e90..23b9d0638 100644
--- a/src/Web/Grand.Web.Admin/Services/DiscountViewModelService.cs
+++ b/src/Web/Grand.Web.Admin/Services/DiscountViewModelService.cs
@@ -15,7 +15,6 @@ using Grand.Domain.Catalog;
using Grand.Domain.Discounts;
using Grand.Domain.Vendors;
using Grand.Infrastructure;
-using Grand.Web.Admin.Extensions;
using Grand.Web.Admin.Extensions.Mapping;
using Grand.Web.Admin.Interfaces;
using Grand.Web.Admin.Models.Catalog;
diff --git a/src/Web/Grand.Web.Admin/Services/LogViewModelService.cs b/src/Web/Grand.Web.Admin/Services/LogViewModelService.cs
deleted file mode 100644
index 36e0dfabb..000000000
--- a/src/Web/Grand.Web.Admin/Services/LogViewModelService.cs
+++ /dev/null
@@ -1,89 +0,0 @@
-using Grand.Infrastructure;
-using Grand.Domain.Logging;
-using Grand.Web.Common.Extensions;
-using Grand.Business.Core.Interfaces.Customers;
-using Grand.Business.Core.Interfaces.Common.Directory;
-using Grand.Business.Core.Interfaces.Common.Localization;
-using Grand.Business.Core.Interfaces.Common.Logging;
-using Grand.Web.Admin.Interfaces;
-using Grand.Web.Admin.Models.Logging;
-using Microsoft.AspNetCore.Mvc.Rendering;
-using Microsoft.Extensions.DependencyInjection;
-using Grand.Business.Core.Extensions;
-
-namespace Grand.Web.Admin.Services
-{
- public class LogViewModelService: ILogViewModelService
- {
- private readonly ILogger _logger;
- private readonly IWorkContext _workContext;
- private readonly ITranslationService _translationService;
- private readonly IDateTimeService _dateTimeService;
- private readonly IServiceProvider _serviceProvider;
-
- public LogViewModelService(ILogger logger, IWorkContext workContext,
- ITranslationService translationService, IDateTimeService dateTimeService,
- IServiceProvider serviceProvider)
- {
- _logger = logger;
- _workContext = workContext;
- _translationService = translationService;
- _dateTimeService = dateTimeService;
- _serviceProvider = serviceProvider;
- }
-
- public virtual LogListModel PrepareLogListModel()
- {
- var model = new LogListModel
- {
- AvailableLogLevels = LogLevel.Debug.ToSelectList(_translationService, _workContext, false).ToList()
- };
- model.AvailableLogLevels.Insert(0, new SelectListItem { Text = _translationService.GetResource("Admin.Common.All"), Value = " " });
- return model;
- }
- public virtual async Task<(IEnumerable<LogModel> logModels, int totalCount)> PrepareLogModel(LogListModel model, int pageIndex, int pageSize)
- {
- DateTime? createdOnFromValue = model.CreatedOnFrom == null ? null
- : _dateTimeService.ConvertToUtcTime(model.CreatedOnFrom.Value, _dateTimeService.CurrentTimeZone);
-
- DateTime? createdToFromValue = model.CreatedOnTo == null ? null
- : _dateTimeService.ConvertToUtcTime(model.CreatedOnTo.Value, _dateTimeService.CurrentTimeZone).AddDays(1);
-
- LogLevel? logLevel = model.LogLevelId > 0 ? (LogLevel?)model.LogLevelId : null;
-
-
- var logItems = await _logger.GetAllLogs(createdOnFromValue, createdToFromValue, model.Message,
- logLevel, pageIndex - 1, pageSize);
- return (logItems.Select(x => new LogModel
- {
- Id = x.Id,
- LogLevel = x.LogLevelId.GetTranslationEnum(_translationService, _workContext),
- ShortMessage = x.ShortMessage,
- FullMessage = "",
- IpAddress = x.IpAddress,
- CustomerId = x.CustomerId,
- PageUrl = x.PageUrl,
- ReferrerUrl = x.ReferrerUrl,
- CreatedOn = _dateTimeService.ConvertToUserTime(x.CreatedOnUtc, DateTimeKind.Utc)
- }), logItems.TotalCount);
-
- }
- public virtual async Task<LogModel> PrepareLogModel(Log log)
- {
- var model = new LogModel
- {
- Id = log.Id,
- LogLevel = log.LogLevelId.GetTranslationEnum(_translationService, _workContext),
- ShortMessage = log.ShortMessage,
- FullMessage = log.FullMessage,
- IpAddress = log.IpAddress,
- CustomerId = log.CustomerId,
- CustomerEmail = !string.IsNullOrEmpty(log.CustomerId) ? (await _serviceProvider.GetRequiredService<ICustomerService>().GetCustomerById(log.CustomerId))?.Email : "",
- PageUrl = log.PageUrl,
- ReferrerUrl = log.ReferrerUrl,
- CreatedOn = _dateTimeService.ConvertToUserTime(log.CreatedOnUtc, DateTimeKind.Utc)
- };
- return model;
- }
- }
-}
diff --git a/src/Web/Grand.Web.Admin/Services/PageViewModelService.cs b/src/Web/Grand.Web.Admin/Services/PageViewModelService.cs
index 51fa0b265..8cda58a13 100644
--- a/src/Web/Grand.Web.Admin/Services/PageViewModelService.cs
+++ b/src/Web/Grand.Web.Admin/Services/PageViewModelService.cs
@@ -7,7 +7,6 @@ using Grand.Business.Core.Interfaces.Common.Seo;
using Grand.Business.Core.Interfaces.Common.Stores;
using Grand.Domain.Seo;
using Grand.Domain.Pages;
-using Grand.Web.Admin.Extensions;
using Grand.Web.Admin.Interfaces;
using Grand.Web.Admin.Models.Pages;
using Microsoft.AspNetCore.Mvc.Rendering;
diff --git a/src/Web/Grand.Web.Admin/Services/PictureViewModelService.cs b/src/Web/Grand.Web.Admin/Services/PictureViewModelService.cs
index 35f1bc4c4..771811c02 100644
--- a/src/Web/Grand.Web.Admin/Services/PictureViewModelService.cs
+++ b/src/Web/Grand.Web.Admin/Services/PictureViewModelService.cs
@@ -1,7 +1,6 @@
using Grand.Business.Core.Extensions;
using Grand.Business.Core.Interfaces.Common.Localization;
using Grand.Business.Core.Interfaces.Storage;
-using Grand.Web.Admin.Extensions;
using Grand.Web.Admin.Interfaces;
using Grand.Web.Admin.Models.Common;
using Grand.Web.Common.Extensions;
diff --git a/src/Web/Grand.Web.Admin/Services/ShipmentViewModelService.cs b/src/Web/Grand.Web.Admin/Services/ShipmentViewModelService.cs
index 18b728b1c..2b321190c 100644
--- a/src/Web/Grand.Web.Admin/Services/ShipmentViewModelService.cs
+++ b/src/Web/Grand.Web.Admin/Services/ShipmentViewModelService.cs
@@ -12,7 +12,6 @@ using Grand.Domain.Directory;
using Grand.Domain.Orders;
using Grand.Domain.Shipping;
using Grand.Infrastructure;
-using Grand.Web.Admin.Extensions;
using Grand.Web.Admin.Interfaces;
using Grand.Web.Admin.Models.Orders;
using Microsoft.AspNetCore.Http;
diff --git a/src/Web/Grand.Web.Admin/Startup/StartupApplication.cs b/src/Web/Grand.Web.Admin/Startup/StartupApplication.cs
index 97d976419..180946811 100644
--- a/src/Web/Grand.Web.Admin/Startup/StartupApplication.cs
+++ b/src/Web/Grand.Web.Admin/Startup/StartupApplication.cs
@@ -45,7 +45,6 @@ namespace Grand.Web.Admin.Startup
services.AddScoped<IGiftVoucherViewModelService, GiftVoucherViewModelService>();
services.AddScoped<IKnowledgebaseViewModelService, KnowledgebaseViewModelService>();
services.AddScoped<ILanguageViewModelService, LanguageViewModelService>();
- services.AddScoped<ILogViewModelService, LogViewModelService>();
services.AddScoped<ICollectionViewModelService, CollectionViewModelService>();
services.AddScoped<INewsViewModelService, NewsViewModelService>();
services.AddScoped<IOrderViewModelService, OrderViewModelService>();
diff --git a/src/Web/Grand.Web.Common/Controllers/BaseController.cs b/src/Web/Grand.Web.Common/Controllers/BaseController.cs
index d0bb9b31b..bb3e0fc27 100644
--- a/src/Web/Grand.Web.Common/Controllers/BaseController.cs
+++ b/src/Web/Grand.Web.Common/Controllers/BaseController.cs
@@ -1,6 +1,4 @@
using Grand.Business.Core.Interfaces.Common.Localization;
-using Grand.Business.Core.Interfaces.Common.Logging;
-using Grand.Infrastructure;
using Grand.Web.Common.DataSource;
using Grand.Web.Common.Events;
using Grand.Web.Common.Extensions;
@@ -8,12 +6,12 @@ using Grand.Web.Common.Filters;
using Grand.Web.Common.Models;
using Grand.Web.Common.Page;
using MediatR;
-using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging;
namespace Grand.Web.Common.Controllers
{
@@ -92,10 +90,8 @@ namespace Grand.Web.Common.Controllers
/// <param name="exception">Exception</param>
private void LogException(Exception exception)
{
- var workContext = HttpContext.RequestServices.GetRequiredService<IWorkContext>();
- var logger = HttpContext.RequestServices.GetRequiredService<ILogger>();
- _ = logger.InsertLog(Domain.Logging.LogLevel.Error, exception?.Message, exception?.ToString(), workContext.CurrentCustomer, HttpContext.Connection.RemoteIpAddress?.ToString(),
- HttpContext.Request.GetDisplayUrl(), HttpContext.Request.GetTypedHeaders().Referer?.ToString());
+ var logger = HttpContext.RequestServices.GetRequiredService<ILoggerFactory>().CreateLogger("BaseController");
+ logger.LogError(exception, exception.Message);
}
/// <summary>
diff --git a/src/Web/Grand.Web.Common/Filters/AuthorizeMenuAttribute.cs b/src/Web/Grand.Web.Common/Filters/AuthorizeMenuAttribute.cs
index 9697982fb..a439e6ade 100644
--- a/src/Web/Grand.Web.Common/Filters/AuthorizeMenuAttribute.cs
+++ b/src/Web/Grand.Web.Common/Filters/AuthorizeMenuAttribute.cs
@@ -7,7 +7,6 @@ using Grand.Infrastructure.Configuration;
using Grand.SharedKernel.Extensions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
-using Microsoft.AspNetCore.Routing;
namespace Grand.Web.Common.Filters
{
diff --git a/src/Web/Grand.Web.Common/Infrastructure/ApplicationBuilderExtensions.cs b/src/Web/Grand.Web.Common/Infrastructure/ApplicationBuilderExtensions.cs
index d44130ca4..e36264f30 100644
--- a/src/Web/Grand.Web.Common/Infrastructure/ApplicationBuilderExtensions.cs
+++ b/src/Web/Grand.Web.Common/Infrastructure/ApplicationBuilderExtensions.cs
@@ -1,8 +1,5 @@
-using Grand.Business.Core.Extensions;
-using Grand.Business.Core.Interfaces.Common.Logging;
-using Grand.Domain.Common;
+using Grand.Domain.Common;
using Grand.Domain.Data;
-using Grand.Infrastructure;
using Grand.Infrastructure.Configuration;
using Grand.Infrastructure.Endpoints;
using Grand.Infrastructure.Plugins;
@@ -20,6 +17,7 @@ using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Hosting;
+using Microsoft.Extensions.Logging;
using Microsoft.Net.Http.Headers;
namespace Grand.Web.Common.Infrastructure
@@ -71,16 +69,9 @@ namespace Grand.Web.Common.Infrastructure
//check whether database is installed
if (DataSettingsManager.DatabaseIsInstalled())
{
- var logger = context.RequestServices.GetRequiredService<ILogger>();
- //get current customer
- var workContext = context.RequestServices.GetRequiredService<IWorkContext>();
- _ = logger.InsertLog(Domain.Logging.LogLevel.Error, exception.Message, exception.ToString(),
- customer: workContext.CurrentCustomer,
- ipAddress: context.Connection.RemoteIpAddress?.ToString(),
- pageUrl: context.Request.GetDisplayUrl(),
- referrerUrl: context.Request.GetTypedHeaders().Referer?.ToString());
+ var logger = context.RequestServices.GetRequiredService<ILoggerFactory>().CreateLogger("UseExceptionHandler");
//log error
- _ = logger.Error(exception.Message, exception, workContext.CurrentCustomer);
+ logger.LogError(exception, exception.Message);
}
}
finally
@@ -117,15 +108,8 @@ namespace Grand.Web.Common.Infrastructure
var commonSettings = context.HttpContext.RequestServices.GetRequiredService<CommonSettings>();
if (commonSettings.Log404Errors)
{
- var logger = context.HttpContext.RequestServices.GetRequiredService<ILogger>();
- //get current customer
- var workContext = context.HttpContext.RequestServices.GetRequiredService<IWorkContext>();
- _ = logger.InsertLog(Domain.Logging.LogLevel.Error,
- $"Error 404. The requested page ({context.HttpContext.Request.GetDisplayUrl()}) was not found",
- customer: workContext.CurrentCustomer,
- ipAddress: context.HttpContext.Connection.RemoteIpAddress?.ToString(),
- pageUrl: context.HttpContext.Request.GetDisplayUrl(),
- referrerUrl: context.HttpContext.Request.GetTypedHeaders().Referer?.ToString());
+ var logger = context.HttpContext.RequestServices.GetRequiredService<ILoggerFactory>().CreateLogger("UseStatusCodePages");
+ logger.LogError("Error 404. The requested page ({DisplayUrl}) was not found", context.HttpContext.Request.GetDisplayUrl());
}
}
await Task.CompletedTask;
@@ -148,12 +132,8 @@ namespace Grand.Web.Common.Infrastructure
var apiRequest = authHeader != null && authHeader.Split(' ')[0] == JwtBearerDefaults.AuthenticationScheme;
if (apiRequest) return Task.CompletedTask;
- var logger = context.HttpContext.RequestServices.GetRequiredService<ILogger>();
- var workContext = context.HttpContext.RequestServices.GetRequiredService<IWorkContext>();
- _ = logger.InsertLog(Domain.Logging.LogLevel.Error, "Error 400. Bad request", null, customer: workContext.CurrentCustomer,
- ipAddress: context.HttpContext.Connection.RemoteIpAddress?.ToString(),
- pageUrl: context.HttpContext.Request.GetDisplayUrl(),
- referrerUrl: context.HttpContext.Request.GetTypedHeaders().Referer?.ToString());
+ var logger = context.HttpContext.RequestServices.GetRequiredService<ILoggerFactory>().CreateLogger("UseBadRequestResult");
+ logger.LogError("Error 400. Bad request");
return Task.CompletedTask;
});
}
@@ -259,21 +239,6 @@ namespace Grand.Web.Common.Infrastructure
}
}
- /// <summary>
- /// Save log application started
- /// </summary>
- /// <param name="application">Builder for configuring an application's request pipeline</param>
- public static void LogApplicationStarted(this IApplicationBuilder application)
- {
- //whether database is already installed
- if (!DataSettingsManager.DatabaseIsInstalled())
- return;
-
- var serviceProvider = application.ApplicationServices;
- var logger = serviceProvider.GetRequiredService<ILogger>();
- _ = logger.Information("Application started");
- }
-
/// <summary>
/// Configure UseForwardedHeaders
/// </summary>
diff --git a/src/Web/Grand.Web.Common/Infrastructure/BackgroundServiceTask.cs b/src/Web/Grand.Web.Common/Infrastructure/BackgroundServiceTask.cs
index c6a7ea8c6..6253dcbe0 100644
--- a/src/Web/Grand.Web.Common/Infrastructure/BackgroundServiceTask.cs
+++ b/src/Web/Grand.Web.Common/Infrastructure/BackgroundServiceTask.cs
@@ -1,10 +1,9 @@
-using Grand.Business.Core.Extensions;
-using Grand.Business.Core.Interfaces.Common.Logging;
-using Grand.Business.Core.Interfaces.System.ScheduleTasks;
+using Grand.Business.Core.Interfaces.System.ScheduleTasks;
using Grand.Infrastructure;
using Grand.Domain.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
+using Microsoft.Extensions.Logging;
namespace Grand.Web.Common.Infrastructure
{
@@ -26,12 +25,12 @@ namespace Grand.Web.Common.Infrastructure
{
using var scope = _serviceProvider.CreateScope();
var serviceProvider = scope.ServiceProvider;
- var logger = serviceProvider.GetService<ILogger>();
+ var logger = serviceProvider.GetService<ILogger<BackgroundServiceTask>>();
var scheduleTaskService = serviceProvider.GetService<IScheduleTaskService>();
var task = await scheduleTaskService.GetTaskByType(_taskType);
if (task == null)
{
- _ = logger.Information($"Task {_taskType} is not exists in the database");
+ logger.LogInformation("Task {TaskType} is not exists in the database", _taskType);
break;
}
@@ -79,7 +78,7 @@ namespace Grand.Web.Common.Infrastructure
{
task.LastNonSuccessEndUtc = DateTime.UtcNow;
task.Enabled = !task.StopOnError;
- await logger.InsertLog(Domain.Logging.LogLevel.Error, $"Error while running the '{task.ScheduleTaskName}' schedule task", exc.Message);
+ logger.LogError(exc, "Error while running the \'{TaskScheduleTaskName}\' schedule task", task.ScheduleTaskName);
}
}
}
@@ -87,14 +86,14 @@ namespace Grand.Web.Common.Infrastructure
{
task.Enabled = !task.StopOnError;
task.LastNonSuccessEndUtc = DateTime.UtcNow;
- await logger.InsertLog(Domain.Logging.LogLevel.Error, $"Type {_taskType} is not registered");
+ logger.LogError("Type {TaskType} is not registered", _taskType);
}
}
else
{
task.Enabled = !task.StopOnError;
task.LastNonSuccessEndUtc = DateTime.UtcNow;
- await logger.InsertLog(Domain.Logging.LogLevel.Error, $"Type {_taskType} is null (type not exists)");
+ logger.LogError("Type {TaskType} is null (type not exists)", _taskType);
}
await scheduleTaskService.UpdateTask(task);
await Task.Delay(TimeSpan.FromMinutes(timeInterval), stoppingToken);
diff --git a/src/Web/Grand.Web.Common/Middleware/ContextLoggingMiddleware.cs b/src/Web/Grand.Web.Common/Middleware/ContextLoggingMiddleware.cs
new file mode 100644
index 000000000..5f9ebc6a6
--- /dev/null
+++ b/src/Web/Grand.Web.Common/Middleware/ContextLoggingMiddleware.cs
@@ -0,0 +1,41 @@
+using Grand.Infrastructure;
+using Microsoft.ApplicationInsights.DataContracts;
+using Microsoft.AspNetCore.Http;
+using Microsoft.Extensions.DependencyInjection;
+using Serilog.Context;
+
+namespace Grand.Web.Common.Middleware;
+
+public class ContextLoggingMiddleware
+{
+ private readonly RequestDelegate _next;
+ private const string CustomerPropertyName = "Customer";
+ private const string StorePropertyName = "Store";
+ private const string CurrencyPropertyName = "Currency";
+ private const string LanguagePropertyName = "Language";
+ public ContextLoggingMiddleware(RequestDelegate next)
+ {
+ _next = next;
+ }
+
+ public async Task InvokeAsync(HttpContext context)
+ {
+ var workContext = context.RequestServices.GetRequiredService<IWorkContext>();
+
+ LogContext.PushProperty(CustomerPropertyName, workContext?.CurrentCustomer?.Email);
+ LogContext.PushProperty(StorePropertyName, workContext?.CurrentStore?.Name);
+ LogContext.PushProperty(CurrencyPropertyName, workContext?.WorkingCurrency?.Name);
+ LogContext.PushProperty(LanguagePropertyName, workContext?.WorkingLanguage?.Name);
+
+ var requestTelemetry = context.Features.Get<RequestTelemetry>();
+ if (requestTelemetry != null)
+ {
+ requestTelemetry.Properties.TryAdd(CustomerPropertyName, workContext?.CurrentCustomer?.Email);
+ requestTelemetry.Properties.TryAdd(StorePropertyName, workContext?.CurrentStore?.Name);
+ requestTelemetry.Properties.TryAdd(CurrencyPropertyName, workContext?.WorkingCurrency?.Name);
+ requestTelemetry.Properties.TryAdd(LanguagePropertyName, workContext?.WorkingLanguage?.Name);
+ }
+
+ await _next(context);
+ }
+}
\ No newline at end of file
diff --git a/src/Web/Grand.Web.Common/Startup/GrandMvcStartup.cs b/src/Web/Grand.Web.Common/Startup/GrandMvcStartup.cs
index c11bf0b7f..2a556b733 100644
--- a/src/Web/Grand.Web.Common/Startup/GrandMvcStartup.cs
+++ b/src/Web/Grand.Web.Common/Startup/GrandMvcStartup.cs
@@ -45,9 +45,6 @@ namespace Grand.Web.Common.Startup
//endpoint routing
application.UseGrandEndpoints();
-
- //save log application started
- application.LogApplicationStarted();
}
/// <summary>
diff --git a/src/Web/Grand.Web.Common/Startup/LoggerStartup.cs b/src/Web/Grand.Web.Common/Startup/LoggerStartup.cs
new file mode 100644
index 000000000..2d2879335
--- /dev/null
+++ b/src/Web/Grand.Web.Common/Startup/LoggerStartup.cs
@@ -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;
+
+ }
+}
diff --git a/src/Web/Grand.Web.Vendor/App_Data/appsettings.json b/src/Web/Grand.Web.Vendor/App_Data/appsettings.json
index bdc313990..91fb8dd26 100644
--- a/src/Web/Grand.Web.Vendor/App_Data/appsettings.json
+++ b/src/Web/Grand.Web.Vendor/App_Data/appsettings.json
@@ -216,36 +216,25 @@
"InstalledPlugins": ""
},
+ "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",
+ "Enrich": [ "FromLogContext" ],
+ "WriteTo": [
+ {
+ "Name": "Console"
+ }
+ ]
},
-
"ApplicationInsights": {
"Enabled": false,
- "ConnectionString": ""
+ "InstrumentationKey": "",
+ "EnableAdaptiveSampling": false
}
- //https://docs.microsoft.com/en-us/azure/azure-monitor/app/asp-net-core
- //The following configuration allows ApplicationInsights to capture
- //all Information logs and more severe logs
- //"Logging": {
- // "LogLevel": {
- // "Default": "Warning"
- // },
- // "ApplicationInsights": {
- // "LogLevel": {
- // "Default": "Information"
- // }
- // }
- //}
}
\ No newline at end of file
diff --git a/src/Web/Grand.Web.Vendor/Controllers/HomeController.cs b/src/Web/Grand.Web.Vendor/Controllers/HomeController.cs
index 7f0c09749..47d4a74a5 100644
--- a/src/Web/Grand.Web.Vendor/Controllers/HomeController.cs
+++ b/src/Web/Grand.Web.Vendor/Controllers/HomeController.cs
@@ -1,11 +1,10 @@
using Grand.Business.Core.Interfaces.Authentication;
-using Grand.Business.Core.Extensions;
using Grand.Business.Core.Interfaces.Common.Directory;
using Grand.Business.Core.Interfaces.Common.Localization;
-using Grand.Business.Core.Interfaces.Common.Logging;
using Grand.Domain.Directory;
using Grand.Infrastructure;
using Microsoft.AspNetCore.Mvc;
+using Microsoft.Extensions.Logging;
namespace Grand.Web.Vendor.Controllers
{
@@ -14,7 +13,7 @@ namespace Grand.Web.Vendor.Controllers
#region Fields
private readonly IWorkContext _workContext;
- private readonly ILogger _logger;
+ private readonly ILogger<HomeController> _logger;
private readonly IGrandAuthenticationService _authenticationService;
#endregion
@@ -23,7 +22,7 @@ namespace Grand.Web.Vendor.Controllers
public HomeController(
IWorkContext workContext,
- ILogger logger,
+ ILogger<HomeController> logger,
IGrandAuthenticationService authenticationService)
{
_workContext = workContext;
@@ -47,8 +46,7 @@ namespace Grand.Web.Vendor.Controllers
public IActionResult AccessDenied(string pageUrl)
{
- _ = _logger.Information(
- $"Access denied to user #{_workContext.CurrentCustomer.Email} on {pageUrl}");
+ _logger.LogInformation("Access denied to user #{CurrentCustomerEmail} on {PageUrl}", _workContext.CurrentCustomer.Email, pageUrl);
return View();
}
diff --git a/src/Web/Grand.Web.Vendor/Program.cs b/src/Web/Grand.Web.Vendor/Program.cs
index 0c807c91d..dde13123d 100644
--- a/src/Web/Grand.Web.Vendor/Program.cs
+++ b/src/Web/Grand.Web.Vendor/Program.cs
@@ -18,7 +18,9 @@ builder.Host.UseDefaultServiceProvider((_, options) =>
});
//use serilog
-builder.Host.UseSerilog();
+builder.Host.UseSerilog((context, services, configuration) => configuration
+ .ReadFrom.Configuration(context.Configuration)
+ .Enrich.FromLogContext());
//add configuration
builder.Host.ConfigureAppConfiguration((hostingContext, config) =>
@@ -38,9 +40,6 @@ builder.Host.ConfigureAppConfiguration((hostingContext, config) =>
});
-//create logger
-Log.Logger = new LoggerConfiguration().ReadFrom.Configuration(builder.Configuration).CreateLogger();
-
//add services
Grand.Infrastructure.StartupBase.ConfigureServices(builder.Services, builder.Configuration);
diff --git a/src/Web/Grand.Web/App_Data/Resources/DefaultLanguage.xml b/src/Web/Grand.Web/App_Data/Resources/DefaultLanguage.xml
index db360d8b8..d81e686e8 100644
--- a/src/Web/Grand.Web/App_Data/Resources/DefaultLanguage.xml
+++ b/src/Web/Grand.Web/App_Data/Resources/DefaultLanguage.xml
@@ -11568,63 +11568,6 @@
<Resource Name="admin.system.developertools" Area="Admin">
<Value>Developer Tools</Value>
</Resource>
- <Resource Name="Admin.System.Log" Area="Admin">
- <Value>Log</Value>
- </Resource>
- <Resource Name="Admin.System.Log.BackToList" Area="Admin">
- <Value>back to system log</Value>
- </Resource>
- <Resource Name="Admin.System.Log.Cleared" Area="Admin">
- <Value>The log has been cleared successfully.</Value>
- </Resource>
- <Resource Name="Admin.System.Log.ClearLog" Area="Admin">
- <Value>Clear log</Value>
- </Resource>
- <Resource Name="Admin.System.Log.Deleted" Area="Admin">
- <Value>Log was successfully deleted</Value>
- </Resource>
- <Resource Name="Admin.System.Log.DeleteSelected" Area="Admin">
- <Value>Delete selected</Value>
- </Resource>
- <Resource Name="Admin.System.Log.Fields.CreatedOn" Area="Admin">
- <Value>Created on</Value>
- </Resource>
- <Resource Name="Admin.System.Log.Fields.Customer" Area="Admin">
- <Value>Customer</Value>
- </Resource>
- <Resource Name="Admin.System.Log.Fields.FullMessage" Area="Admin">
- <Value>Full message</Value>
- </Resource>
- <Resource Name="Admin.System.Log.Fields.IPAddress" Area="Admin">
- <Value>IP address</Value>
- </Resource>
- <Resource Name="Admin.System.Log.Fields.LogLevel" Area="Admin">
- <Value>Log level</Value>
- </Resource>
- <Resource Name="Admin.System.Log.Fields.PageURL" Area="Admin">
- <Value>Page URL</Value>
- </Resource>
- <Resource Name="Admin.System.Log.Fields.ReferrerURL" Area="Admin">
- <Value>Referrer URL</Value>
- </Resource>
- <Resource Name="Admin.System.Log.Fields.ShortMessage" Area="Admin">
- <Value>Short message</Value>
- </Resource>
- <Resource Name="Admin.System.Log.List.CreatedOnFrom" Area="Admin">
- <Value>Created from</Value>
- </Resource>
- <Resource Name="Admin.System.Log.List.CreatedOnTo" Area="Admin">
- <Value>Created to</Value>
- </Resource>
- <Resource Name="Admin.System.Log.List.LogLevel" Area="Admin">
- <Value>Log level</Value>
- </Resource>
- <Resource Name="Admin.System.Log.List.Message" Area="Admin">
- <Value>Message</Value>
- </Resource>
- <Resource Name="Admin.System.Log.ViewLogDetails" Area="Admin">
- <Value>View log entry details</Value>
- </Resource>
<Resource Name="Admin.System.Maintenance" Area="Admin">
<Value>Maintenance</Value>
</Resource>
@@ -11685,12 +11628,6 @@
<Resource Name="Admin.System.Maintenance.DeleteGuests.TotalDeleted" Area="Admin">
<Value>{0} customers were deleted</Value>
</Resource>
- <Resource Name="Admin.System.Maintenance.DeleteSystemLog" Area="Admin">
- <Value>Deleting system Log</Value>
- </Resource>
- <Resource Name="Admin.System.Maintenance.DeleteSystemLog.Deleted" Area="Admin">
- <Value>Deleted system Log</Value>
- </Resource>
<Resource Name="Admin.System.QueuedEmails" Area="Admin">
<Value>Message Queue</Value>
</Resource>
@@ -14688,9 +14625,6 @@
<Resource Name="Permission.ManageStores" Area="Admin">
<Value>Admin area. Manage Stores</Value>
</Resource>
- <Resource Name="Permission.ManageSystemLog" Area="Admin">
- <Value>Admin area. Manage System Log</Value>
- </Resource>
<Resource Name="Permission.ManageTaxSettings" Area="Admin">
<Value>Admin area. Manage Tax Settings</Value>
</Resource>
diff --git a/src/Web/Grand.Web/App_Data/appsettings.json b/src/Web/Grand.Web/App_Data/appsettings.json
index 528581375..1713db459 100644
--- a/src/Web/Grand.Web/App_Data/appsettings.json
+++ b/src/Web/Grand.Web/App_Data/appsettings.json
@@ -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
},
@@ -245,38 +248,26 @@
"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",
+ "Enrich": [ "FromLogContext" ],
+ "WriteTo": [
+ {
+ "Name": "Console"
+ }
+ ]
},
-
"ApplicationInsights": {
"Enabled": false,
- "ConnectionString": ""
+ "InstrumentationKey": "",
+ "EnableAdaptiveSampling": false
}
- //https://docs.microsoft.com/en-us/azure/azure-monitor/app/asp-net-core
- //The following configuration allows ApplicationInsights to capture
- //all Information logs and more severe logs
- //"Logging": {
- // "LogLevel": {
- // "Default": "Warning"
- // },
- // "ApplicationInsights": {
- // "LogLevel": {
- // "Default": "Information"
- // }
- // }
- //}
}
diff --git a/src/Web/Grand.Web/Controllers/CheckoutController.cs b/src/Web/Grand.Web/Controllers/CheckoutController.cs
index 82d4e25a1..5ed26b2fc 100644
--- a/src/Web/Grand.Web/Controllers/CheckoutController.cs
+++ b/src/Web/Grand.Web/Controllers/CheckoutController.cs
@@ -26,6 +26,7 @@ using Grand.Web.Models.Checkout;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
+using Microsoft.Extensions.Logging;
namespace Grand.Web.Controllers
{
@@ -44,7 +45,7 @@ namespace Grand.Web.Controllers
private readonly IPickupPointService _pickupPointService;
private readonly IPaymentService _paymentService;
private readonly IPaymentTransactionService _paymentTransactionService;
- private readonly ILogger _logger;
+ private readonly ILogger<CheckoutController> _logger;
private readonly IOrderService _orderService;
private readonly ICustomerActivityService _customerActivityService;
private readonly IMediator _mediator;
@@ -71,7 +72,7 @@ namespace Grand.Web.Controllers
IPickupPointService pickupPointService,
IPaymentService paymentService,
IPaymentTransactionService paymentTransactionService,
- ILogger logger,
+ ILogger<CheckoutController> logger,
IOrderService orderService,
ICustomerActivityService customerActivityService,
IMediator mediator,
@@ -516,7 +517,7 @@ namespace Grand.Web.Controllers
}
catch (Exception exc)
{
- _ = _logger.Warning(exc.Message, exc, _workContext.CurrentCustomer);
+ _logger.LogWarning(exc.Message);
return Json(new { error = 1, message = exc.Message });
}
}
@@ -687,7 +688,7 @@ namespace Grand.Web.Controllers
}
catch (Exception exc)
{
- _ = _logger.Warning(exc.Message, exc, _workContext.CurrentCustomer);
+ _logger.LogWarning(exc.Message);
return Json(new { error = 1, message = exc.Message });
}
}
@@ -772,7 +773,7 @@ namespace Grand.Web.Controllers
}
catch (Exception exc)
{
- _ = _logger.Warning(exc.Message, exc, _workContext.CurrentCustomer);
+ _logger.LogWarning(exc.Message);
return Json(new { error = 1, message = exc.Message });
}
}
@@ -855,7 +856,7 @@ namespace Grand.Web.Controllers
}
catch (Exception exc)
{
- _ = _logger.Warning(exc.Message, exc, _workContext.CurrentCustomer);
+ _logger.LogWarning(exc.Message);
return Json(new { error = 1, message = exc.Message });
}
}
@@ -915,7 +916,7 @@ namespace Grand.Web.Controllers
}
catch (Exception exc)
{
- _ = _logger.Warning(exc.Message, exc, _workContext.CurrentCustomer);
+ _logger.LogWarning(exc.Message);
return Json(new { error = 1, message = exc.Message });
}
}
@@ -1026,7 +1027,7 @@ namespace Grand.Web.Controllers
}
catch (Exception exc)
{
- _ = _logger.Warning(exc.Message, exc, _workContext.CurrentCustomer);
+ _logger.LogWarning(exc.Message);
return Json(new { error = 1, message = exc.Message });
}
}
@@ -1072,7 +1073,7 @@ namespace Grand.Web.Controllers
}
catch (Exception exc)
{
- _ = _logger.Warning(exc.Message, exc, _workContext.CurrentCustomer);
+ _logger.LogWarning(exc.Message);
return Content(exc.Message);
}
}
diff --git a/src/Web/Grand.Web/Controllers/InstallController.cs b/src/Web/Grand.Web/Controllers/InstallController.cs
index aa0c9aa95..08abd4b40 100644
--- a/src/Web/Grand.Web/Controllers/InstallController.cs
+++ b/src/Web/Grand.Web/Controllers/InstallController.cs
@@ -1,9 +1,7 @@
using Grand.Business.Core.Commands.System.Security;
-using Grand.Business.Core.Interfaces.Common.Logging;
using Grand.Business.Core.Interfaces.Common.Security;
using Grand.Business.Core.Interfaces.System.Installation;
using Grand.Domain.Data;
-using Grand.Domain.Logging;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Configuration;
using Grand.Infrastructure.Migrations;
@@ -16,6 +14,7 @@ using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
+using Microsoft.Extensions.Logging;
namespace Grand.Web.Controllers
{
@@ -243,8 +242,8 @@ namespace Grand.Web.Controllers
}
catch (Exception ex)
{
- var _logger = _serviceProvider.GetRequiredService<ILogger>();
- await _logger.InsertLog(LogLevel.Error, "Error during installing plugin " + pluginInfo.SystemName,
+ var logger = _serviceProvider.GetRequiredService<ILoggerFactory>().CreateLogger("InstallController");
+ logger.LogError(ex, "Error during installing plugin " + pluginInfo.SystemName,
ex.Message + " " + ex.InnerException?.Message);
}
}
diff --git a/src/Web/Grand.Web/Features/Models/Catalog/GetVendor.cs b/src/Web/Grand.Web/Features/Models/Catalog/GetVendor.cs
index 5761860e7..b8d543204 100644
--- a/src/Web/Grand.Web/Features/Models/Catalog/GetVendor.cs
+++ b/src/Web/Grand.Web/Features/Models/Catalog/GetVendor.cs
@@ -1,7 +1,6 @@
using Grand.Domain.Customers;
using Grand.Domain.Localization;
using Grand.Domain.Stores;
-using Grand.Domain.Vendors;
using Grand.Web.Models.Catalog;
using MediatR;
diff --git a/src/Web/Grand.Web/Features/Models/Customers/GetNavigation.cs b/src/Web/Grand.Web/Features/Models/Customers/GetNavigation.cs
index 24952c302..14fe41b69 100644
--- a/src/Web/Grand.Web/Features/Models/Customers/GetNavigation.cs
+++ b/src/Web/Grand.Web/Features/Models/Customers/GetNavigation.cs
@@ -1,7 +1,6 @@
using Grand.Domain.Customers;
using Grand.Domain.Localization;
using Grand.Domain.Stores;
-using Grand.Domain.Vendors;
using Grand.Web.Models.Customer;
using MediatR;
diff --git a/src/Web/Grand.Web/Features/Models/Vendors/GetVendorReviews.cs b/src/Web/Grand.Web/Features/Models/Vendors/GetVendorReviews.cs
index e0f99ba56..cb67f4fe0 100644
--- a/src/Web/Grand.Web/Features/Models/Vendors/GetVendorReviews.cs
+++ b/src/Web/Grand.Web/Features/Models/Vendors/GetVendorReviews.cs
@@ -1,5 +1,4 @@
-using Grand.Domain.Vendors;
-using Grand.Web.Models.Vendors;
+using Grand.Web.Models.Vendors;
using MediatR;
namespace Grand.Web.Features.Models.Vendors
diff --git a/src/Web/Grand.Web/Program.cs b/src/Web/Grand.Web/Program.cs
index 3a9386087..82c3a26cc 100644
--- a/src/Web/Grand.Web/Program.cs
+++ b/src/Web/Grand.Web/Program.cs
@@ -17,8 +17,12 @@ builder.Host.UseDefaultServiceProvider((_, options) =>
options.ValidateOnBuild = false;
});
+builder.Services.AddLogging();
+
//use serilog
-builder.Host.UseSerilog();
+builder.Host.UseSerilog((context, services, configuration) => configuration
+ .ReadFrom.Configuration(context.Configuration)
+ .Enrich.FromLogContext());
//add configuration
builder.Host.ConfigureAppConfiguration((hostingContext, config) =>
@@ -38,9 +42,6 @@ builder.Host.ConfigureAppConfiguration((hostingContext, config) =>
});
-//create logger
-Log.Logger = new LoggerConfiguration().ReadFrom.Configuration(builder.Configuration).CreateLogger();
-
//add services
StartupBase.ConfigureServices(builder.Services, builder.Configuration);