Skip to content

Commit

Permalink
Logger Service - remove IHttpContextAccessor
Browse files Browse the repository at this point in the history
  • Loading branch information
KrzysztofPajak committed Oct 21, 2021
1 parent e41480a commit 97216fb
Show file tree
Hide file tree
Showing 19 changed files with 92 additions and 68 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,7 @@ public async Task<PlaceOrderResult> Handle(PlaceOrderCommand command, Cancellati
}
catch (Exception exc)
{
_logger.Error(exc.Message, exc);
_ = _logger.Error(exc.Message, exc);
result.AddError(exc.Message);
}

Expand All @@ -240,7 +240,7 @@ public async Task<PlaceOrderResult> Handle(PlaceOrderCommand command, Cancellati
{
//log it
string logError = string.Format("Error while placing order. {0}", error);
_logger.Error(logError);
_ = _logger.Error(logError);
}

#endregion
Expand Down Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,7 @@ public virtual IList<IShippingRateCalculationProvider> 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<ShippingOption>();
Expand Down
24 changes: 13 additions & 11 deletions src/Business/Grand.Business.Common/Extensions/LoggingExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,15 @@ public partial interface ILogger
/// <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<Log> 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);

/// <summary>
/// Determines whether a log level is enabled
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ public partial class DefaultLogger : ILogger
#region Fields

private readonly IRepository<Log> _logRepository;
private readonly IHttpContextAccessor _httpContextAccessor;

#endregion

Expand All @@ -31,12 +30,9 @@ public partial class DefaultLogger : ILogger
/// Ctor
/// </summary>
/// <param name="logRepository">Log repository</param>
/// <param name="webHelper">Web helper</param>
public DefaultLogger(IRepository<Log> logRepository,
IHttpContextAccessor httpContextAccessor)
public DefaultLogger(IRepository<Log> logRepository)
{
_logRepository = logRepository;
_httpContextAccessor = httpContextAccessor;
}

#endregion
Expand Down Expand Up @@ -121,24 +117,28 @@ where logIds.Contains(l.Id)
/// <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 async Task<Log> 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;
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ public async Task<IActionResult> 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);
Expand Down Expand Up @@ -145,7 +145,7 @@ public async Task<IActionResult> 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 {
Expand Down Expand Up @@ -296,7 +296,7 @@ public async Task<IActionResult> 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,
Expand Down Expand Up @@ -326,7 +326,7 @@ public async Task<IActionResult> 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,
Expand Down Expand Up @@ -372,7 +372,7 @@ public async Task<IActionResult> 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
Expand All @@ -383,7 +383,7 @@ public async Task<IActionResult> IPNHandler()
}
else
{
_logger.Error("PayPal IPN failed.", new GrandException(strRequest));
_ = _logger.Error("PayPal IPN failed.", new GrandException(strRequest));
}

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

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

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

_loggerMock.Verify(c => c.InsertLog(Domain.Logging.LogLevel.Error, It.IsAny<string>(), It.IsAny<string>(), It.IsAny<Customer>()), Times.Never);
_loggerMock.Verify(c => c.InsertLog(Domain.Logging.LogLevel.Error, It.IsAny<string>(), It.IsAny<string>(), It.IsAny<Customer>(), null, null, null), Times.Never);
_auctionMock.Verify(c => c.UpdateBid(It.IsAny<Bid>()), Times.Once);
_auctionMock.Verify(c => c.UpdateAuctionEnded(It.IsAny<Product>(), It.IsAny<bool>(), It.IsAny<bool>()), Times.Once);
_messageProviderMock.Verify(c => c.SendAuctionEndedStoreOwnerMessage(It.IsAny<Product>(), It.IsAny<string>(), It.IsAny<Bid>()), Times.Once);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ public async Task Execute_ThrowExecption_InovekExpectedMethodsAndInsertLog()
It.IsAny<string>(), It.IsAny<string>(), It.IsAny<IEnumerable<string>>())).ThrowsAsync(new Exception());
_loggerMock.Setup(c => c.IsEnabled(It.IsAny<LogLevel>())).Returns(true);
await _task.Execute();
_loggerMock.Verify(c => c.InsertLog(Domain.Logging.LogLevel.Error, It.IsAny<string>(), It.IsAny<string>(), It.IsAny<Customer>()), Times.Once);
_loggerMock.Verify(c => c.InsertLog(Domain.Logging.LogLevel.Error, It.IsAny<string>(), It.IsAny<string>(), It.IsAny<Customer>(), null, null, null), Times.Once);
_queuedEmailServiceMock.Verify(c => c.UpdateQueuedEmail(It.IsAny<QueuedEmail>()), Times.Once);
}
}
Expand Down
7 changes: 5 additions & 2 deletions src/Web/Grand.Web.Admin/Controllers/CommonController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -357,7 +357,10 @@ public async Task<IActionResult> MaintenanceDeleteActivitylog(MaintenanceModel m
}

[HttpPost]
public async Task<IActionResult> MaintenanceConvertPicture([FromServices] IPictureService pictureService, [FromServices] MediaSettings mediaSettings, [FromServices] ILogger logger)
public async Task<IActionResult> MaintenanceConvertPicture(
[FromServices] IPictureService pictureService,
[FromServices] MediaSettings mediaSettings,
[FromServices] ILogger logger)
{
var numberOfConvertItems = 0;
if (mediaSettings.StoreInDb)
Expand All @@ -374,7 +377,7 @@ public async Task<IActionResult> 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);
}

}
Expand Down
4 changes: 2 additions & 2 deletions src/Web/Grand.Web.Admin/Controllers/HomeController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -222,11 +222,11 @@ public async Task<IActionResult> 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();
Expand Down
2 changes: 1 addition & 1 deletion src/Web/Grand.Web.Admin/Controllers/PluginController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -447,7 +447,7 @@ private void Upload(string archivePath)
}
catch (Exception ex)
{
_logger.Error(ex.Message);
_ = _logger.Error(ex.Message);
};
}
}
Expand Down

0 comments on commit 97216fb

Please sign in to comment.