Skip to content

Commit

Permalink
Added BuildLoggerFactory extension methods (#225)
Browse files Browse the repository at this point in the history
* Added BuildLoggerFactory extension methods
* Updated readme
* Updated logging packages to target v7.0.0

+semver: feature
  • Loading branch information
roryprimrose authored Nov 21, 2023
1 parent d491e84 commit 52307d2
Show file tree
Hide file tree
Showing 14 changed files with 183 additions and 135 deletions.
17 changes: 6 additions & 11 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,37 +19,32 @@ jobs:
steps:

- name: Checkout
uses: actions/checkout@v3.0.2
uses: actions/checkout@v4.1.1
with:
fetch-depth: 0

- name: Install GitVersion
uses: gittools/actions/gitversion/setup@v0.9.13
uses: gittools/actions/gitversion/setup@v0.10.2
with:
versionSpec: '5.x'

- name: Use GitVersion
id: gitversion # step id used as reference for output values
uses: gittools/actions/gitversion/execute@v0.9.13
uses: gittools/actions/gitversion/execute@v0.10.2
with:
useConfigFile: true
configFilePath: ./GitVersion.yml

- name: Update project version
uses: roryprimrose/[email protected].5
uses: roryprimrose/[email protected].6
with:
version: ${{ steps.gitversion.outputs.NuGetVersionV2 }}
assemblyVersion: ${{ steps.gitversion.outputs.AssemblySemVer }}
fileVersion: ${{ steps.gitversion.outputs.MajorMinorPatch }}
informationalVersion: ${{ steps.gitversion.outputs.InformationalVersion }}

- name: Setup dotnet v3.1
uses: actions/[email protected]
with:
dotnet-version: '3.1.x' # SDK Version to use.

- name: Setup dotnet v6.0
uses: actions/setup-dotnet@v2.1.0
uses: actions/setup-dotnet@v3.2.0
with:
dotnet-version: '6.0.x' # SDK Version to use.

Expand All @@ -64,7 +59,7 @@ jobs:

- name: Generate coverage report
# run: reportgenerator -reports:**/coverage.cobertura.xml -targetdir:Report -reporttypes:HtmlInline_AzurePipelines;Cobertura
uses: danielpalme/ReportGenerator-GitHub-Action@5.1.9
uses: danielpalme/ReportGenerator-GitHub-Action@5.2.0
with:
reports: "**/coverage*cobertura.xml"
targetdir: "Report"
Expand Down
8 changes: 4 additions & 4 deletions Divergic.Logging.Xunit.UnitTests/CacheLoggerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -235,13 +235,13 @@ public void LogCachesLogMessageTest(LogLevel logLevel)
[InlineData(null)]
[InlineData("")]
[InlineData(" ")]
public void LogDoesLogsRecordWhenFormatterReturnsEmptyMessageAndExceptionIsNotNullTest(string data)
public void LogDoesLogsRecordWhenFormatterReturnsEmptyMessageAndExceptionIsNotNullTest(string? data)
{
const LogLevel logLevel = LogLevel.Error;
var eventId = Model.Create<EventId>();
var state = Guid.NewGuid().ToString();
var exception = new ArgumentNullException(Guid.NewGuid().ToString(), Guid.NewGuid().ToString());
string Formatter(string message, Exception? error) => data;
string Formatter(string message, Exception? error) => data!;

var source = Substitute.For<ILogger>();

Expand Down Expand Up @@ -282,12 +282,12 @@ public void LogDoesLogsRecordWhenFormatterReturnsMessageAndExceptionIsNull()
[InlineData(null)]
[InlineData("")]
[InlineData(" ")]
public void LogDoesNotLogRecordWhenFormatterReturnsEmptyMessageAndExceptionIsNullTest(string data)
public void LogDoesNotLogRecordWhenFormatterReturnsEmptyMessageAndExceptionIsNullTest(string? data)
{
const LogLevel logLevel = LogLevel.Error;
var eventId = Model.Create<EventId>();
var state = Guid.NewGuid().ToString();
string Formatter(string message, Exception? error) => data;
string Formatter(string message, Exception? error) => data!;

var source = Substitute.For<ILogger>();

Expand Down
8 changes: 4 additions & 4 deletions Divergic.Logging.Xunit.UnitTests/DefaultFormatterTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ public void FormatHidesSensitiveDataInMessage(string? sensitiveValue, string mes
[InlineData("", true)]
[InlineData(" ", true)]
[InlineData("stuff", true)]
public void FormatIncludesNewLineBetweenMessageAndException(string message, bool exceptionExists)
public void FormatIncludesNewLineBetweenMessageAndException(string? message, bool exceptionExists)
{
var config = new LoggingConfig();
var scopeLevel = 1;
Expand All @@ -93,7 +93,7 @@ public void FormatIncludesNewLineBetweenMessageAndException(string message, bool

var sut = new DefaultFormatter(config);

var actual = sut.Format(scopeLevel, categoryName, logLevel, eventId, message, exception);
var actual = sut.Format(scopeLevel, categoryName, logLevel, eventId, message!, exception);

actual.Should().NotStartWith(Environment.NewLine);
actual.Should().NotEndWith(Environment.NewLine);
Expand Down Expand Up @@ -125,7 +125,7 @@ public void FormatIncludesNewLineBetweenMessageAndException(string message, bool
[InlineData(null)]
[InlineData("")]
[InlineData(" ")]
public void FormatReturnsEmptyWhenMessageIsNullEmptyOrWhiteSpace(string message)
public void FormatReturnsEmptyWhenMessageIsNullEmptyOrWhiteSpace(string? message)
{
var config = new LoggingConfig().Set(x => x.ScopePaddingSpaces = 2);
var scopeLevel = 1;
Expand All @@ -135,7 +135,7 @@ public void FormatReturnsEmptyWhenMessageIsNullEmptyOrWhiteSpace(string message)

var sut = new DefaultFormatter(config);

var actual = sut.Format(scopeLevel, categoryName, logLevel, eventId, message, null);
var actual = sut.Format(scopeLevel, categoryName, logLevel, eventId, message!, null);

actual.Should().BeEmpty();
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,28 +1,28 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFrameworks>netcoreapp3.1;net6.0</TargetFrameworks>
<TargetFrameworks>net6.0</TargetFrameworks>
<IsPackable>False</IsPackable>
<CodeAnalysisRuleSet>..\Solution Items\UnitTest.ruleset</CodeAnalysisRuleSet>
<LangVersion>latest</LangVersion>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.NetAnalyzers" Version="6.0.0">
<PackageReference Include="Microsoft.CodeAnalysis.NetAnalyzers" Version="8.0.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.2.0" />
<PackageReference Include="xunit" Version="2.4.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.5">
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
<PackageReference Include="xunit" Version="2.6.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.5.4">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="ModelBuilder" Version="8.3.0" />
<PackageReference Include="NSubstitute" Version="4.4.0" />
<PackageReference Include="FluentAssertions" Version="6.7.0" />
<PackageReference Include="coverlet.msbuild" Version="3.1.2">
<PackageReference Include="ModelBuilder" Version="8.4.0" />
<PackageReference Include="NSubstitute" Version="5.1.0" />
<PackageReference Include="FluentAssertions" Version="6.12.0" />
<PackageReference Include="coverlet.msbuild" Version="6.0.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
Expand Down
8 changes: 4 additions & 4 deletions Divergic.Logging.Xunit.UnitTests/ScopeScenarioTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ public void TestOutputWritesMessagesInContextOfScopesWithSensitiveData()
[InlineData(null)]
[InlineData("")]
[InlineData(" ")]
public void TestOutputWritesMessagesUsingScopesWithoutState(string scopeState)
public void TestOutputWritesMessagesUsingScopesWithoutState(string? scopeState)
{
Logger.LogCritical("Writing critical message");
Logger.LogDebug("Writing debug message");
Expand All @@ -80,11 +80,11 @@ public void TestOutputWritesMessagesUsingScopesWithoutState(string scopeState)
Logger.LogTrace("Writing trace message");
Logger.LogWarning("Writing warning message");

using (Logger.BeginScope((object) scopeState))
using (Logger.BeginScope((object) scopeState!))
{
Logger.LogInformation("Inside first scope");

using (Logger.BeginScope((object) scopeState))
using (Logger.BeginScope((object) scopeState!))
{
Logger.LogInformation("Inside second scope");
}
Expand Down Expand Up @@ -195,7 +195,7 @@ public async Task UsingParallelTasks()
return Task.CompletedTask;
})).ToList();

await Task.WhenAll(tasks).ConfigureAwait(false);
await Task.WhenAll(tasks);

Task StartOnDefaultScheduler(Func<Task> asyncFunc)
{
Expand Down
56 changes: 45 additions & 11 deletions Divergic.Logging.Xunit.UnitTests/TestOutputHelperExtensionsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,40 @@ public TestOutputHelperExtensionsTests(ITestOutputHelper output)
_output = output;
}

[Fact]
public void BuildLoggerFactoryReturnsILoggerFactory()
{
var factory = _output.BuildLoggerFactory();

factory.Should().BeAssignableTo<ILoggerFactory>();
}

[Fact]
public void BuildLoggerFactoryThrowsExceptionWithNullOutputT()
{
Action action = () => TestOutputHelperExtensions.BuildLoggerFactory(null!);

action.Should().Throw<ArgumentNullException>();
}

[Fact]
public void BuildLoggerFactoryWithConfigReturnsILoggerFactory()
{
var config = new LoggingConfig();

var factory = _output.BuildLoggerFactory(config);

factory.Should().BeAssignableTo<ILoggerFactory>();
}

[Fact]
public void BuildLoggerFactoryWithLogLevelReturnsILoggerFactory()
{
var factory = _output.BuildLoggerFactory(LogLevel.Error);

factory.Should().BeAssignableTo<ILoggerFactory>();
}

[Theory]
[ClassData(typeof(LogLevelDataSet))]
public void BuildLoggerForTLogsAccordingToLogLevel(LogLevel configuredLevel, LogLevel logLevel, bool isEnabled)
Expand Down Expand Up @@ -98,15 +132,7 @@ public void BuildLoggerLogsAccordingToLogLevel(LogLevel configuredLevel, LogLeve
}

[Fact]
public void BuildLoggerThrowsExceptionWithNullOutputT()
{
Action action = () => TestOutputHelperExtensions.BuildLogger(null!);

action.Should().Throw<ArgumentNullException>();
}

[Fact]
public void BuildReturnsILogger()
public void BuildLoggerReturnsILogger()
{
var logger = _output.BuildLogger();

Expand All @@ -118,7 +144,7 @@ public void BuildReturnsILogger()
}

[Fact]
public void BuildReturnsUsableLogger()
public void BuildLoggerReturnsUsableLogger()
{
var logger = _output.BuildLogger();

Expand All @@ -128,7 +154,15 @@ public void BuildReturnsUsableLogger()
}

[Fact]
public void BuildWithLoggingConfigReturnsUsableLogger()
public void BuildLoggerThrowsExceptionWithNullOutputT()
{
Action action = () => TestOutputHelperExtensions.BuildLogger(null!);

action.Should().Throw<ArgumentNullException>();
}

[Fact]
public void BuildLoggerWithLoggingConfigReturnsUsableLogger()
{
var config = new LoggingConfig();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,14 @@ public void CanDisposeMultipleTimes()
[InlineData(null)]
[InlineData("")]
[InlineData(" ")]
public void CreateLoggerThrowsExceptionWithInvalidCategoryNameTest(string categoryName)
public void CreateLoggerThrowsExceptionWithInvalidCategoryNameTest(string? categoryName)
{
var output = Substitute.For<ITestOutputHelper>();

using var sut = new TestOutputLoggerProvider(output);

// ReSharper disable once AccessToDisposedClosure
Action action = () => sut.CreateLogger(categoryName);
Action action = () => sut.CreateLogger(categoryName!);

action.Should().Throw<ArgumentException>();
}
Expand Down
6 changes: 3 additions & 3 deletions Divergic.Logging.Xunit.UnitTests/TestOutputLoggerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ public void LogIgnoresTestBoundaryFailure()

var task = new Task(async () =>
{
await Task.Delay(0).ConfigureAwait(false);
await Task.Delay(0);

sut.LogCritical("message2");
});
Expand Down Expand Up @@ -198,12 +198,12 @@ public void LogWritesMessageUsingSpecifiedLineFormatter()
[InlineData(null)]
[InlineData("")]
[InlineData(" ")]
public void ThrowsExceptionWhenCreatedWithInvalidCategoryNameTest(string categoryName)
public void ThrowsExceptionWhenCreatedWithInvalidCategoryNameTest(string? categoryName)
{
var output = Substitute.For<ITestOutputHelper>();

// ReSharper disable once ObjectCreationAsStatement
Action action = () => new TestOutputLogger(categoryName, output);
Action action = () => new TestOutputLogger(categoryName!, output);

action.Should().Throw<ArgumentException>();
}
Expand Down
2 changes: 1 addition & 1 deletion Divergic.Logging.Xunit/CacheLogger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ internal CacheLogger(ILogger logger, ILoggerFactory factory)
}

/// <inheritdoc />
public override IDisposable BeginScope<TState>(TState state)
public override IDisposable? BeginScope<TState>(TState state)
{
var scope = _logger?.BeginScope(state) ?? NoopDisposable.Instance;

Expand Down
Loading

0 comments on commit 52307d2

Please sign in to comment.