Skip to content

Commit

Permalink
add ilogger
Browse files Browse the repository at this point in the history
  • Loading branch information
tinohager committed Feb 13, 2024
1 parent 4a5bfd7 commit 7f2cbf1
Show file tree
Hide file tree
Showing 7 changed files with 69 additions and 10 deletions.
37 changes: 37 additions & 0 deletions src/Nager.PublicSuffix.UnitTest/Helpers/LoggerHelper.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
using Microsoft.Extensions.Logging;
using Moq;
using System;
using System.Diagnostics;

namespace Nager.PublicSuffix.UnitTest.Helpers
{
public static class LoggerHelper
{
public static Mock<ILogger<T>> GetLogger<T>()
{
var logger = new Mock<ILogger<T>>();

logger.Setup(x => x.Log(
It.IsAny<LogLevel>(),
It.IsAny<EventId>(),
It.IsAny<It.IsAnyType>(),
It.IsAny<Exception>(),
(Func<It.IsAnyType, Exception?, string>)It.IsAny<object>()))
.Callback(new InvocationAction(invocation =>
{
var logLevel = (LogLevel)invocation.Arguments[0]; // The first two will always be whatever is specified in the setup above
var eventId = (EventId)invocation.Arguments[1]; // so I'm not sure you would ever want to actually use them
var state = invocation.Arguments[2];
var exception = (Exception)invocation.Arguments[3];
var formatter = invocation.Arguments[4];
var invokeMethod = formatter.GetType().GetMethod("Invoke");
var logMessage = (string?)invokeMethod?.Invoke(formatter, new[] { state, exception });
Trace.WriteLine($"{logLevel} - {logMessage}");
}));

return logger;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.9.0" />
<PackageReference Include="Moq" Version="4.20.70" />
<PackageReference Include="MSTest.TestAdapter" Version="3.2.0" />
<PackageReference Include="MSTest.TestFramework" Version="3.2.0" />
</ItemGroup>
Expand Down
5 changes: 4 additions & 1 deletion src/Nager.PublicSuffix.UnitTest/RuleProviderTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Nager.PublicSuffix.CacheProviders;
using Nager.PublicSuffix.RuleProviders;
using Nager.PublicSuffix.UnitTest.Helpers;
using System.Net.Http;
using System.Threading.Tasks;

Expand All @@ -13,13 +14,15 @@ public class RuleProviderTest
[TestMethod]
public async Task WebTldRuleProviderTest()
{
var loggerMock = LoggerHelper.GetLogger<WebRuleProvider>();

var builder = new ConfigurationBuilder();
using var httpClient = new HttpClient();

var configuration = builder.Build();

var cacheProvider = new LocalFileSystemCacheProvider();
var webRuleProvider = new WebRuleProvider(configuration, cacheProvider, httpClient);
var webRuleProvider = new WebRuleProvider(loggerMock.Object, configuration, cacheProvider, httpClient);
var domainDataStructure = await webRuleProvider.BuildAsync();
Assert.IsNotNull(domainDataStructure);
}
Expand Down
4 changes: 2 additions & 2 deletions src/Nager.PublicSuffix/CacheProviders/ICacheProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,13 @@ namespace Nager.PublicSuffix.CacheProviders
public interface ICacheProvider
{
/// <summary>
/// Get the data of the cache file
/// Get the data from the cache
/// </summary>
/// <returns>Returns null if the cache has expired</returns>
Task<string> GetAsync();

/// <summary>
/// Create or update the cache file
/// Store data in the cache
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ public LocalFileSystemCacheProvider(
this._cacheFilePath = Path.Combine(tempPath, cacheFileName);
}

///<inheritdoc/>
/// <inheritdoc/>
public bool IsCacheValid()
{
var cacheInvalid = true;
Expand All @@ -53,7 +53,7 @@ public bool IsCacheValid()
return !cacheInvalid;
}

///<inheritdoc/>
/// <inheritdoc/>
public async Task<string> GetAsync()
{
if (!this.IsCacheValid())
Expand All @@ -65,7 +65,7 @@ public async Task<string> GetAsync()
return await reader.ReadToEndAsync().ConfigureAwait(false);
}

///<inheritdoc/>
/// <inheritdoc/>
public async Task SetAsync(string data)
{
using var streamWriter = File.CreateText(this._cacheFilePath);
Expand Down
1 change: 1 addition & 0 deletions src/Nager.PublicSuffix/Nager.PublicSuffix.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.0" />
</ItemGroup>

</Project>
25 changes: 21 additions & 4 deletions src/Nager.PublicSuffix/RuleProviders/WebRuleProvider.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Nager.PublicSuffix.CacheProviders;
using Nager.PublicSuffix.Exceptions;
using Nager.PublicSuffix.Extensions;
using Nager.PublicSuffix.Models;
using Nager.PublicSuffix.RuleParsers;
using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
Expand All @@ -16,6 +18,7 @@ namespace Nager.PublicSuffix.RuleProviders
public class WebRuleProvider : IRuleProvider
{
private readonly string _dataFileUrl;
private readonly ILogger<WebRuleProvider> _logger;
private readonly ICacheProvider _cacheProvider;
private readonly HttpClient _httpClient;
private DomainDataStructure _domainDataStructure;
Expand All @@ -30,15 +33,18 @@ public class WebRuleProvider : IRuleProvider
/// Loads the public suffix definition file from the official website
/// </summary>
/// <remarks>It is possible to overwrite the url via configuration parameters <c>Nager:PublicSuffix:DataUrl</c></remarks>
/// <param name="logger"></param>
/// <param name="configuration"></param>
/// <param name="cacheProvider"></param>
/// <param name="httpClient"></param>
public WebRuleProvider(
ILogger<WebRuleProvider> logger,
IConfiguration configuration,
ICacheProvider cacheProvider,
HttpClient httpClient
)
{
this._logger = logger;
this._cacheProvider = cacheProvider;
this._httpClient = httpClient;

Expand All @@ -60,12 +66,24 @@ public async Task<bool> BuildAsync(
string ruleData;
if (this._cacheProvider.IsCacheValid())
{
this._logger.LogInformation($"{nameof(BuildAsync)} - Use data from cache");
ruleData = await this._cacheProvider.GetAsync().ConfigureAwait(false);
}
else
{
ruleData = await this.LoadFromUrlAsync(this._dataFileUrl, cancellationToken).ConfigureAwait(false);
await this._cacheProvider.SetAsync(ruleData).ConfigureAwait(false);
this._logger.LogInformation($"{nameof(BuildAsync)} - Start downloading data from url");

try
{
ruleData = await this.LoadFromUrlAsync(this._dataFileUrl, cancellationToken).ConfigureAwait(false);
await this._cacheProvider.SetAsync(ruleData).ConfigureAwait(false);
}
catch (Exception exception)
{
this._logger.LogError(exception, $"{nameof(BuildAsync)} - Failure on download");

return false;
}
}

var rules = ruleParser.ParseRules(ruleData);
Expand All @@ -79,7 +97,7 @@ public async Task<bool> BuildAsync(
}

/// <inheritdoc/>
public DomainDataStructure GetDomainDataStructure()
public DomainDataStructure? GetDomainDataStructure()

Check warning on line 100 in src/Nager.PublicSuffix/RuleProviders/WebRuleProvider.cs

View workflow job for this annotation

GitHub Actions / build

The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.

Check warning on line 100 in src/Nager.PublicSuffix/RuleProviders/WebRuleProvider.cs

View workflow job for this annotation

GitHub Actions / build

The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.
{
return this._domainDataStructure;
}
Expand All @@ -95,7 +113,6 @@ public async Task<string> LoadFromUrlAsync(
CancellationToken cancellationToken)
{
using var response = await this._httpClient.GetAsync(url, cancellationToken).ConfigureAwait(false);

if (!response.IsSuccessStatusCode)
{
throw new RuleLoadException($"Cannot load from {url} {response.StatusCode}");
Expand Down

0 comments on commit 7f2cbf1

Please sign in to comment.