From 97216fb00157ff3b4f54974dca24d516b7534b5b Mon Sep 17 00:00:00 2001 From: KrzysztofPajak Date: Thu, 21 Oct 2021 09:03:44 +0200 Subject: [PATCH] Logger Service - remove IHttpContextAccessor --- .../Services/Tax/TaxService.cs | 2 +- .../Orders/PlaceOrderCommandHandler.cs | 6 ++--- .../Services/Shipping/ShippingService.cs | 2 +- .../Extensions/LoggingExtensions.cs | 24 +++++++++-------- .../Interfaces/Logging/ILogger.cs | 9 ++++++- .../Services/Directory/GeoLookupService.cs | 2 +- .../Services/Logging/DefaultLogger.cs | 22 ++++++++-------- .../Services/PictureService.cs | 4 +-- .../BackgroundServiceTask.cs | 2 +- .../QueuedMessagesSendScheduleTask.cs | 2 +- .../PaymentPayPalStandardController.cs | 12 ++++----- .../BackgroundService/EndAuctionsTaskTests.cs | 4 +-- .../QueuedMessagesSendScheduleTaskTests.cs | 2 +- .../Controllers/CommonController.cs | 7 +++-- .../Controllers/HomeController.cs | 4 +-- .../Controllers/PluginController.cs | 2 +- .../Controllers/BaseController.cs | 14 +++++----- .../ApplicationBuilderExtensions.cs | 26 ++++++++++++++----- .../Controllers/CheckoutController.cs | 14 +++++----- 19 files changed, 92 insertions(+), 68 deletions(-) diff --git a/src/Business/Grand.Business.Catalog/Services/Tax/TaxService.cs b/src/Business/Grand.Business.Catalog/Services/Tax/TaxService.cs index e299a82f3..813353350 100644 --- a/src/Business/Grand.Business.Catalog/Services/Tax/TaxService.cs +++ b/src/Business/Grand.Business.Catalog/Services/Tax/TaxService.cs @@ -261,7 +261,7 @@ await IsVatExempt(calculateTaxRequest.Address, calculateTaxRequest.Customer)) { foreach (var error in calculateTaxResult.Errors) { - _logger.Error(string.Format("{0} - {1}", activeTaxProvider.FriendlyName, error), null, customer); + _ = _logger.Error(string.Format("{0} - {1}", activeTaxProvider.FriendlyName, error), null, customer); } } return (taxRate, isTaxable); 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 4b3bcda60..f173a7cc3 100644 --- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PlaceOrderCommandHandler.cs +++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PlaceOrderCommandHandler.cs @@ -223,7 +223,7 @@ public async Task Handle(PlaceOrderCommand command, Cancellati } catch (Exception exc) { - _logger.Error(exc.Message, exc); + _ = _logger.Error(exc.Message, exc); result.AddError(exc.Message); } @@ -240,7 +240,7 @@ public async Task Handle(PlaceOrderCommand command, Cancellati { //log it string logError = string.Format("Error while placing order. {0}", error); - _logger.Error(logError); + _ = _logger.Error(logError); } #endregion @@ -1162,7 +1162,7 @@ protected virtual async Task SendNotification(IServiceScopeFactory scopeFactory, } catch (Exception ex) { - _logger.Error($"Error - order placed attachment file {order.OrderNumber}", ex); + _ = _logger.Error($"Error - order placed attachment file {order.OrderNumber}", ex); } await messageProviderService diff --git a/src/Business/Grand.Business.Checkout/Services/Shipping/ShippingService.cs b/src/Business/Grand.Business.Checkout/Services/Shipping/ShippingService.cs index 71d09f4cf..d3f6d5bf4 100644 --- a/src/Business/Grand.Business.Checkout/Services/Shipping/ShippingService.cs +++ b/src/Business/Grand.Business.Checkout/Services/Shipping/ShippingService.cs @@ -227,7 +227,7 @@ public virtual IList LoadAllShippingRateCalcul foreach (string error in getShippingOptionResponse.Errors) { result.AddError(error); - _logger.Warning(string.Format("Shipping ({0}). {1}", srcm.FriendlyName, error)); + _ = _logger.Warning(string.Format("Shipping ({0}). {1}", srcm.FriendlyName, error)); } //clear the shipping options in this case srcmShippingOptions = new List(); diff --git a/src/Business/Grand.Business.Common/Extensions/LoggingExtensions.cs b/src/Business/Grand.Business.Common/Extensions/LoggingExtensions.cs index 4e6428860..e864f8ee7 100644 --- a/src/Business/Grand.Business.Common/Extensions/LoggingExtensions.cs +++ b/src/Business/Grand.Business.Common/Extensions/LoggingExtensions.cs @@ -2,35 +2,37 @@ using Grand.Domain.Logging; using System; using Grand.Business.Common.Interfaces.Logging; +using System.Threading.Tasks; namespace Grand.Business.Common.Extensions { public static class LoggingExtensions { - public static void Information(this ILogger logger, string message, Exception exception = null, Customer customer = null) + public static Task Information(this ILogger logger, string message, Exception exception = null, Customer customer = null) { - FilteredLog(logger, LogLevel.Information, message, exception, customer); + return FilteredLog(logger, LogLevel.Information, message, exception, customer); } - public static void Warning(this ILogger logger, string message, Exception exception = null, Customer customer = null) + public static Task Warning(this ILogger logger, string message, Exception exception = null, Customer customer = null) { - FilteredLog(logger, LogLevel.Warning, message, exception, customer); + return FilteredLog(logger, LogLevel.Warning, message, exception, customer); } - public static void Error(this ILogger logger, string message, Exception exception = null, Customer customer = null) + public static Task Error(this ILogger logger, string message, Exception exception = null, Customer customer = null) { - FilteredLog(logger, LogLevel.Error, message, exception, customer); + return FilteredLog(logger, LogLevel.Error, message, exception, customer); } - public static void Fatal(this ILogger logger, string message, Exception exception = null, Customer customer = null) + public static Task Fatal(this ILogger logger, string message, Exception exception = null, Customer customer = null) { - FilteredLog(logger, LogLevel.Fatal, message, exception, customer); + return FilteredLog(logger, LogLevel.Fatal, message, exception, customer); } - private static void FilteredLog(ILogger logger, LogLevel level, string message, Exception exception = null, Customer customer = null) + private static Task FilteredLog(ILogger logger, LogLevel level, string message, Exception exception = null, Customer customer = null) { if (logger.IsEnabled(level)) { - string fullMessage = exception == null ? string.Empty : exception.ToString(); - logger.InsertLog(level, message, fullMessage, customer); + var fullMessage = exception == null ? string.Empty : exception.ToString(); + return logger.InsertLog(level, message, fullMessage, customer); } + return Task.CompletedTask; } } } diff --git a/src/Business/Grand.Business.Common/Interfaces/Logging/ILogger.cs b/src/Business/Grand.Business.Common/Interfaces/Logging/ILogger.cs index 96e274391..3f8f7334a 100644 --- a/src/Business/Grand.Business.Common/Interfaces/Logging/ILogger.cs +++ b/src/Business/Grand.Business.Common/Interfaces/Logging/ILogger.cs @@ -47,8 +47,15 @@ public partial interface ILogger /// The short message /// The full message /// The customer to associate log record with + /// Ip address + /// Page url + /// Referrer url /// A log item - Task InsertLog(LogLevel logLevel, string shortMessage, string fullMessage = "", Customer customer = null); + Task InsertLog(LogLevel logLevel, string shortMessage, string fullMessage = "", Customer customer = null, + string ipAddress = default, + string pageurl = default, + string referrerUrl = default); + /// /// Determines whether a log level is enabled /// diff --git a/src/Business/Grand.Business.Common/Services/Directory/GeoLookupService.cs b/src/Business/Grand.Business.Common/Services/Directory/GeoLookupService.cs index a74937f0d..0e462182f 100644 --- a/src/Business/Grand.Business.Common/Services/Directory/GeoLookupService.cs +++ b/src/Business/Grand.Business.Common/Services/Directory/GeoLookupService.cs @@ -54,7 +54,7 @@ protected virtual CountryResponse GetInformation(string ipAddress) } catch (Exception exc) { - _logger.Warning("Cannot load MaxMind record", exc); + _ = _logger.Warning("Cannot load MaxMind record", exc); return null; } } diff --git a/src/Business/Grand.Business.Common/Services/Logging/DefaultLogger.cs b/src/Business/Grand.Business.Common/Services/Logging/DefaultLogger.cs index 5a23a374f..5d33d3ffc 100644 --- a/src/Business/Grand.Business.Common/Services/Logging/DefaultLogger.cs +++ b/src/Business/Grand.Business.Common/Services/Logging/DefaultLogger.cs @@ -21,7 +21,6 @@ public partial class DefaultLogger : ILogger #region Fields private readonly IRepository _logRepository; - private readonly IHttpContextAccessor _httpContextAccessor; #endregion @@ -31,12 +30,9 @@ public partial class DefaultLogger : ILogger /// Ctor /// /// Log repository - /// Web helper - public DefaultLogger(IRepository logRepository, - IHttpContextAccessor httpContextAccessor) + public DefaultLogger(IRepository logRepository) { _logRepository = logRepository; - _httpContextAccessor = httpContextAccessor; } #endregion @@ -121,24 +117,28 @@ where logIds.Contains(l.Id) /// The short message /// The full message /// The customer to associate log record with + /// Ip address + /// Page url + /// Referrer url /// A log item - public virtual async Task InsertLog(LogLevel logLevel, string shortMessage, string fullMessage = "", Customer customer = null) + 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 = _httpContextAccessor.HttpContext?.Connection?.RemoteIpAddress?.ToString(), + IpAddress = ipAddress, CustomerId = customer != null ? customer.Id : "", - PageUrl = _httpContextAccessor.HttpContext?.Request?.GetDisplayUrl(), - ReferrerUrl = _httpContextAccessor.HttpContext?.Request?.Headers[HeaderNames.Referer], + PageUrl = pageurl, + ReferrerUrl = referrerUrl, CreatedOnUtc = DateTime.UtcNow }; - await _logRepository.InsertAsync(log); + _logRepository.InsertAsync(log); - return log; + return Task.CompletedTask; } /// diff --git a/src/Business/Grand.Business.Storage/Services/PictureService.cs b/src/Business/Grand.Business.Storage/Services/PictureService.cs index 9e3326c8b..279bd0354 100644 --- a/src/Business/Grand.Business.Storage/Services/PictureService.cs +++ b/src/Business/Grand.Business.Storage/Services/PictureService.cs @@ -557,7 +557,7 @@ public virtual async Task ClearThumbs() } catch (Exception ex) { - _logger.Error(ex.Message, ex); + _ = _logger.Error(ex.Message, ex); } } await Task.CompletedTask; @@ -735,7 +735,7 @@ public virtual Task SavePictureInFile(string pictureId, byte[] pictureBinary, st File.WriteAllBytes(filepath, pictureBinary); } else - _logger.Error("Drirectory path not exist."); + _ = _logger.Error("Drirectory path not exist."); return Task.CompletedTask; } diff --git a/src/Business/Grand.Business.System/Services/BackgroundServices/BackgroundServiceTask.cs b/src/Business/Grand.Business.System/Services/BackgroundServices/BackgroundServiceTask.cs index 09d3c0daf..c87b878b4 100644 --- a/src/Business/Grand.Business.System/Services/BackgroundServices/BackgroundServiceTask.cs +++ b/src/Business/Grand.Business.System/Services/BackgroundServices/BackgroundServiceTask.cs @@ -45,7 +45,7 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken) var task = await scheduleTaskService.GetTaskByType(_taskType); if (task == null) { - logger.Information($"Task {_taskType} is not exists in the database"); + _ = logger.Information($"Task {_taskType} is not exists in the database"); break; } 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 363edf2d7..1a3084df0 100644 --- a/src/Business/Grand.Business.System/Services/BackgroundServices/ScheduleTasks/QueuedMessagesSendScheduleTask.cs +++ b/src/Business/Grand.Business.System/Services/BackgroundServices/ScheduleTasks/QueuedMessagesSendScheduleTask.cs @@ -65,7 +65,7 @@ public async Task Execute() } catch (Exception exc) { - _logger.Error(string.Format("Error sending e-mail. {0}", exc.Message), exc); + _ = _logger.Error(string.Format("Error sending e-mail. {0}", exc.Message), exc); } finally { diff --git a/src/Plugins/Payments.PayPalStandard/Controllers/PaymentPayPalStandardController.cs b/src/Plugins/Payments.PayPalStandard/Controllers/PaymentPayPalStandardController.cs index 489bec0a4..90c265789 100644 --- a/src/Plugins/Payments.PayPalStandard/Controllers/PaymentPayPalStandardController.cs +++ b/src/Plugins/Payments.PayPalStandard/Controllers/PaymentPayPalStandardController.cs @@ -101,7 +101,7 @@ public async Task PDTHandler() } catch (Exception exc) { - _logger.Error("PayPal PDT. Error getting mc_gross", exc); + _ = _logger.Error("PayPal PDT. Error getting mc_gross", exc); } values.TryGetValue("payer_status", out var payer_status); @@ -145,7 +145,7 @@ public async Task PDTHandler() if (_payPalStandardPaymentSettings.PdtValidateOrderTotal && !Math.Round(mc_gross, 2).Equals(Math.Round(order.OrderTotal * order.CurrencyRate, 2))) { string errorStr = string.Format("PayPal PDT. Returned order total {0} doesn't equal order total {1}. Order# {2}.", mc_gross, order.OrderTotal * order.CurrencyRate, order.OrderNumber); - _logger.Error(errorStr); + _ = _logger.Error(errorStr); //order note await _orderService.InsertOrderNote(new OrderNote { @@ -296,7 +296,7 @@ public async Task IPNHandler() //not valid string errorStr = string.Format("PayPal IPN. Returned order total {0} doesn't equal order total {1}. Order# {2}.", mc_gross, order.OrderTotal * order.CurrencyRate, order.Id); //log - _logger.Error(errorStr); + _ = _logger.Error(errorStr); //order note await _orderService.InsertOrderNote(new OrderNote { Note = errorStr, @@ -326,7 +326,7 @@ public async Task IPNHandler() //not valid string errorStr = string.Format("PayPal IPN. Returned order total {0} doesn't equal order total {1}. Order# {2}.", mc_gross, order.OrderTotal * order.CurrencyRate, order.Id); //log - _logger.Error(errorStr); + _ = _logger.Error(errorStr); //order note await _orderService.InsertOrderNote(new OrderNote { Note = errorStr, @@ -372,7 +372,7 @@ public async Task IPNHandler() } else { - _logger.Error("PayPal IPN. Order is not found", new GrandException(sb.ToString())); + _ = _logger.Error("PayPal IPN. Order is not found", new GrandException(sb.ToString())); } } #endregion @@ -383,7 +383,7 @@ public async Task IPNHandler() } else { - _logger.Error("PayPal IPN failed.", new GrandException(strRequest)); + _ = _logger.Error("PayPal IPN failed.", new GrandException(strRequest)); } return BadRequest(); 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 5180af3c9..36a4af130 100644 --- a/src/Tests/Grand.Business.System.Tests/Services/BackgroundService/EndAuctionsTaskTests.cs +++ b/src/Tests/Grand.Business.System.Tests/Services/BackgroundService/EndAuctionsTaskTests.cs @@ -66,7 +66,7 @@ public async Task Execute_HasWarnings_InvokeExpectedMethos() .ReturnsAsync((new List() { "warning" }, null)); await _task.Execute(); - _loggerMock.Verify(c => c.InsertLog(Domain.Logging.LogLevel.Error, It.IsAny(), It.IsAny(), It.IsAny()), Times.Once); + _loggerMock.Verify(c => c.InsertLog(Domain.Logging.LogLevel.Error, It.IsAny(), It.IsAny(), It.IsAny(), null, null, null), Times.Once); } [TestMethod] @@ -80,7 +80,7 @@ public async Task Execute_Valid_InvokeExpectedMethos() .ReturnsAsync((new List(), null)); await _task.Execute(); - _loggerMock.Verify(c => c.InsertLog(Domain.Logging.LogLevel.Error, It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); + _loggerMock.Verify(c => c.InsertLog(Domain.Logging.LogLevel.Error, It.IsAny(), It.IsAny(), It.IsAny(), null, null, null), Times.Never); _auctionMock.Verify(c => c.UpdateBid(It.IsAny()), Times.Once); _auctionMock.Verify(c => c.UpdateAuctionEnded(It.IsAny(), It.IsAny(), It.IsAny()), Times.Once); _messageProviderMock.Verify(c => c.SendAuctionEndedStoreOwnerMessage(It.IsAny(), It.IsAny(), It.IsAny()), 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 1409da2b3..b9d7d54f0 100644 --- a/src/Tests/Grand.Business.System.Tests/Services/BackgroundService/QueuedMessagesSendScheduleTaskTests.cs +++ b/src/Tests/Grand.Business.System.Tests/Services/BackgroundService/QueuedMessagesSendScheduleTaskTests.cs @@ -62,7 +62,7 @@ public async Task Execute_ThrowExecption_InovekExpectedMethodsAndInsertLog() It.IsAny(), It.IsAny(), It.IsAny>())).ThrowsAsync(new Exception()); _loggerMock.Setup(c => c.IsEnabled(It.IsAny())).Returns(true); await _task.Execute(); - _loggerMock.Verify(c => c.InsertLog(Domain.Logging.LogLevel.Error, It.IsAny(), It.IsAny(), It.IsAny()), Times.Once); + _loggerMock.Verify(c => c.InsertLog(Domain.Logging.LogLevel.Error, It.IsAny(), It.IsAny(), It.IsAny(), null, null, null), Times.Once); _queuedEmailServiceMock.Verify(c => c.UpdateQueuedEmail(It.IsAny()), Times.Once); } } diff --git a/src/Web/Grand.Web.Admin/Controllers/CommonController.cs b/src/Web/Grand.Web.Admin/Controllers/CommonController.cs index 36ef7db14..6852682fe 100644 --- a/src/Web/Grand.Web.Admin/Controllers/CommonController.cs +++ b/src/Web/Grand.Web.Admin/Controllers/CommonController.cs @@ -357,7 +357,10 @@ public async Task MaintenanceDeleteActivitylog(MaintenanceModel m } [HttpPost] - public async Task MaintenanceConvertPicture([FromServices] IPictureService pictureService, [FromServices] MediaSettings mediaSettings, [FromServices] ILogger logger) + public async Task MaintenanceConvertPicture( + [FromServices] IPictureService pictureService, + [FromServices] MediaSettings mediaSettings, + [FromServices] ILogger logger) { var numberOfConvertItems = 0; if (mediaSettings.StoreInDb) @@ -374,7 +377,7 @@ public async Task MaintenanceConvertPicture([FromServices] IPictu } catch (Exception ex) { - logger.Error($"Error on converting picture with id {picture.Id} to webp format", ex); + _ = logger.Error($"Error on converting picture with id {picture.Id} to webp format", ex); } } diff --git a/src/Web/Grand.Web.Admin/Controllers/HomeController.cs b/src/Web/Grand.Web.Admin/Controllers/HomeController.cs index 54d2dd652..d0b656062 100644 --- a/src/Web/Grand.Web.Admin/Controllers/HomeController.cs +++ b/src/Web/Grand.Web.Admin/Controllers/HomeController.cs @@ -222,11 +222,11 @@ public async Task AccessDenied(string pageUrl) var currentCustomer = _workContext.CurrentCustomer; if (currentCustomer == null || await _groupService.IsGuest(currentCustomer)) { - _logger.Information(string.Format("Access denied to anonymous request on {0}", pageUrl)); + _ = _logger.Information(string.Format("Access denied to anonymous request on {0}", pageUrl)); return View(); } - _logger.Information(string.Format("Access denied to user #{0} '{1}' on {2}", currentCustomer.Email, currentCustomer.Email, pageUrl)); + _ = _logger.Information(string.Format("Access denied to user #{0} '{1}' on {2}", currentCustomer.Email, currentCustomer.Email, pageUrl)); return View(); diff --git a/src/Web/Grand.Web.Admin/Controllers/PluginController.cs b/src/Web/Grand.Web.Admin/Controllers/PluginController.cs index f57ab1b21..4825a0b4a 100644 --- a/src/Web/Grand.Web.Admin/Controllers/PluginController.cs +++ b/src/Web/Grand.Web.Admin/Controllers/PluginController.cs @@ -447,7 +447,7 @@ private void Upload(string archivePath) } catch (Exception ex) { - _logger.Error(ex.Message); + _ = _logger.Error(ex.Message); }; } } diff --git a/src/Web/Grand.Web.Common/Controllers/BaseController.cs b/src/Web/Grand.Web.Common/Controllers/BaseController.cs index 181f4693f..a994bd190 100644 --- a/src/Web/Grand.Web.Common/Controllers/BaseController.cs +++ b/src/Web/Grand.Web.Common/Controllers/BaseController.cs @@ -1,5 +1,4 @@ -using Grand.Business.Common.Extensions; -using Grand.Business.Common.Interfaces.Localization; +using Grand.Business.Common.Interfaces.Localization; using Grand.Business.Common.Interfaces.Logging; using Grand.Infrastructure; using Grand.Web.Common.DataSource; @@ -14,6 +13,7 @@ using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Net.Http.Headers; using System; using System.Collections.Generic; using System.Threading.Tasks; @@ -99,8 +99,8 @@ protected void LogException(Exception exception) { var workContext = HttpContext.RequestServices.GetRequiredService(); var logger = HttpContext.RequestServices.GetRequiredService(); - var customer = workContext.CurrentCustomer; - logger.Error(exception.Message, exception, customer); + _ = logger.InsertLog(Domain.Logging.LogLevel.Error, exception?.Message, exception?.ToString(), workContext.CurrentCustomer, HttpContext.Connection?.RemoteIpAddress?.ToString(), + HttpContext.Request?.GetDisplayUrl(), HttpContext.Request?.Headers[HeaderNames.Referer]); } /// @@ -136,8 +136,7 @@ protected virtual void Notification(NotifyType type, string message, bool persis /// Error's json data protected JsonResult ErrorForKendoGridJson(string errorMessage) { - var gridModel = new DataSourceResult - { + var gridModel = new DataSourceResult { Errors = errorMessage }; @@ -150,8 +149,7 @@ protected JsonResult ErrorForKendoGridJson(string errorMessage) /// Error's json data protected JsonResult ErrorForKendoGridJson(ModelStateDictionary modelState) { - var gridModel = new DataSourceResult - { + var gridModel = new DataSourceResult { Errors = modelState.SerializeErrors() }; return Json(gridModel); diff --git a/src/Web/Grand.Web.Common/Infrastructure/ApplicationBuilderExtensions.cs b/src/Web/Grand.Web.Common/Infrastructure/ApplicationBuilderExtensions.cs index 437216997..77451b4c4 100644 --- a/src/Web/Grand.Web.Common/Infrastructure/ApplicationBuilderExtensions.cs +++ b/src/Web/Grand.Web.Common/Infrastructure/ApplicationBuilderExtensions.cs @@ -14,6 +14,7 @@ using Microsoft.AspNetCore.Diagnostics; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Extensions; using Microsoft.AspNetCore.HttpOverrides; using Microsoft.AspNetCore.StaticFiles; using Microsoft.Extensions.DependencyInjection; @@ -77,8 +78,13 @@ public static void UseGrandExceptionHandler(this IApplicationBuilder application var logger = context.RequestServices.GetRequiredService(); //get current customer var workContext = context.RequestServices.GetRequiredService(); + _ = 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?.Headers[HeaderNames.Referer]); //log error - logger.Error(exception.Message, exception, workContext.CurrentCustomer); + _ = logger.Error(exception.Message, exception, workContext.CurrentCustomer); } } finally @@ -118,8 +124,13 @@ public static void UsePageNotFound(this IApplicationBuilder application) var logger = context.HttpContext.RequestServices.GetRequiredService(); //get current customer var workContext = context.HttpContext.RequestServices.GetRequiredService(); - logger.Error($"Error 404. The requested page ({context.HttpContext.Request.Scheme}://{context.HttpContext.Request.Host}{context.HttpContext.Request.Path}) was not found", - customer: workContext.CurrentCustomer); + _ = logger.InsertLog(Domain.Logging.LogLevel.Error, + $"Error 404. The requested page ({context.HttpContext.Request.Scheme}://{context.HttpContext.Request.Host}{context.HttpContext.Request.Path})" + + $" was not found", + customer: workContext.CurrentCustomer, + ipAddress: context.HttpContext?.Connection?.RemoteIpAddress?.ToString(), + pageurl: context.HttpContext?.Request?.GetDisplayUrl(), + referrerUrl: context.HttpContext?.Request?.Headers[HeaderNames.Referer]); } } await Task.CompletedTask; @@ -144,7 +155,10 @@ public static void UseBadRequestResult(this IApplicationBuilder application) { var logger = context.HttpContext.RequestServices.GetRequiredService(); var workContext = context.HttpContext.RequestServices.GetRequiredService(); - logger.Error("Error 400. Bad request", null, customer: workContext.CurrentCustomer); + _ = 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?.Headers[HeaderNames.Referer]); } } return Task.CompletedTask; @@ -223,7 +237,7 @@ public static void UseGrandStaticFiles(this IApplicationBuilder application, App RequestPath = new PathString("/Plugins"), OnPrepareResponse = ctx => { - if (!String.IsNullOrEmpty(appConfig.StaticFilesCacheControl)) + if (!string.IsNullOrEmpty(appConfig.StaticFilesCacheControl)) ctx.Context.Response.Headers.Append(HeaderNames.CacheControl, appConfig.StaticFilesCacheControl); } }); @@ -260,7 +274,7 @@ public static void LogApplicationStarted(this IApplicationBuilder application) var serviceProvider = application.ApplicationServices; var logger = serviceProvider.GetRequiredService(); - logger.Information("Application started", null, null); + _ = logger.Information("Application started", null, null); } /// diff --git a/src/Web/Grand.Web/Controllers/CheckoutController.cs b/src/Web/Grand.Web/Controllers/CheckoutController.cs index 6414fbb61..01c56a99e 100644 --- a/src/Web/Grand.Web/Controllers/CheckoutController.cs +++ b/src/Web/Grand.Web/Controllers/CheckoutController.cs @@ -586,7 +586,7 @@ public virtual async Task SaveBilling(IFormCollection form) } catch (Exception exc) { - _logger.Warning(exc.Message, exc, _workContext.CurrentCustomer); + _ = _logger.Warning(exc.Message, exc, _workContext.CurrentCustomer); return Json(new { error = 1, message = exc.Message }); } } @@ -768,7 +768,7 @@ public virtual async Task SaveShipping(CheckoutShippingAddressMod } catch (Exception exc) { - _logger.Warning(exc.Message, exc, _workContext.CurrentCustomer); + _ = _logger.Warning(exc.Message, exc, _workContext.CurrentCustomer); return Json(new { error = 1, message = exc.Message }); } } @@ -841,7 +841,7 @@ public virtual async Task SaveShippingMethod(IFormCollection form } catch (Exception exc) { - _logger.Warning(exc.Message, exc, _workContext.CurrentCustomer); + _ = _logger.Warning(exc.Message, exc, _workContext.CurrentCustomer); return Json(new { error = 1, message = exc.Message }); } } @@ -915,7 +915,7 @@ public virtual async Task SavePaymentMethod(IFormCollection form) } catch (Exception exc) { - _logger.Warning(exc.Message, exc, _workContext.CurrentCustomer); + _ = _logger.Warning(exc.Message, exc, _workContext.CurrentCustomer); return Json(new { error = 1, message = exc.Message }); } } @@ -974,7 +974,7 @@ public virtual async Task SavePaymentInfo(IFormCollection form) } catch (Exception exc) { - _logger.Warning(exc.Message, exc, _workContext.CurrentCustomer); + _ = _logger.Warning(exc.Message, exc, _workContext.CurrentCustomer); return Json(new { error = 1, message = exc.Message }); } } @@ -1042,7 +1042,7 @@ public virtual async Task ConfirmOrder() } catch (Exception exc) { - _logger.Warning(exc.Message, exc, _workContext.CurrentCustomer); + _ = _logger.Warning(exc.Message, exc, _workContext.CurrentCustomer); return Json(new { error = 1, message = exc.Message }); } } @@ -1086,7 +1086,7 @@ public virtual async Task CompleteRedirectionPayment(string payme } catch (Exception exc) { - _logger.Warning(exc.Message, exc, _workContext.CurrentCustomer); + _ = _logger.Warning(exc.Message, exc, _workContext.CurrentCustomer); return Content(exc.Message); } }