Skip to content

Commit

Permalink
add extension methods for ILogger to be able to push properties like …
Browse files Browse the repository at this point in the history
…serilog does without serilog; add more unit tests
  • Loading branch information
cYCL157 committed Feb 4, 2025
1 parent fef9747 commit cc4d26c
Show file tree
Hide file tree
Showing 10 changed files with 158 additions and 11 deletions.
10 changes: 10 additions & 0 deletions src/Cortside.Common.Logging/Cortside.Common.Logging.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
</ItemGroup>
</Project>
15 changes: 15 additions & 0 deletions src/Cortside.Common.Logging/LoggingExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;

namespace Cortside.Common.Logging {
public static class LoggerExtensions {
public static IDisposable PushProperty(this ILogger logger, string name, object value) {
return logger.BeginScope(new Dictionary<string, object> { { name, value } });
}

public static IDisposable PushProperties(this ILogger logger, Dictionary<string, object> properties) {
return logger.BeginScope(properties);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Cortside.Common.Logging\Cortside.Common.Logging.csproj" />
<ProjectReference Include="..\Cortside.Common.Testing\Cortside.Common.Testing.csproj" />
</ItemGroup>
</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Cortside.Common.Logging;
using Cortside.Common.Testing.Logging.LogEvent;
using Microsoft.Extensions.Logging;
using Xunit;
using Xunit.Abstractions;

namespace Cortside.Common.Testing.Tests.Logging.Xunit {
public class LogEventLoggerTest {
private readonly ILoggerFactory loggerFactory;

public LogEventLoggerTest(ITestOutputHelper output) {
// Create a logger factory with a debug provider
loggerFactory = LoggerFactory.Create(builder => {
builder
.SetMinimumLevel(LogLevel.Trace)
.AddFilter("Microsoft", LogLevel.Warning)
.AddFilter("System", LogLevel.Warning)
.AddFilter("Cortside.Common", LogLevel.Trace)
.AddLogEvent();
});
}

[Fact]
public void TestLogger() {
// Create a logger with the category name of the current class
var logger = loggerFactory.CreateLogger<LogEventLoggerTest>();

Assert.NotNull(logger);

// Log some messages with different log levels and message templates
logger.LogTrace("This is a trace message.");
logger.LogDebug("This is a debug message.");
logger.LogInformation("Hello {Name}!", "World");
logger.LogWarning("This is a warning message.");
logger.LogError("This is an error message.");
logger.LogCritical("This is a critical message.");

// Use structured logging to capture complex data
var person = new Person { Name = "Alice", Age = 25 };
logger.LogInformation("Created a new person: {@Person}", person);

// Use exception logging to capture the details of an exception
try {
throw new Exception("Something went wrong.");
} catch (Exception ex) {
logger.LogError(ex, "An exception occurred.");
}

// Use the logger to capture a log event
Assert.Equal(8, LogEventLogger.LogEvents.Count);

using (logger.PushProperties(new Dictionary<string, object>() {
["UserId"] = "xxx",
["ExtraProperty"] = "yyy",
})) {
logger.LogDebug("logged messaged that should have 2 properties with it");
}

// 10, adding 1 for the actual log and 1 for the being scope
Assert.Equal(10, LogEventLogger.LogEvents.Count);
Assert.Equal("UserId=xxxExtraProperty=yyy", LogEventLogger.LogEvents.First(x => x.LogLevel == LogLevel.None).Message);
}
}
}
2 changes: 1 addition & 1 deletion src/Cortside.Common.Testing/Extensions/RandomExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
using System;

namespace Cortside.Common.Testing.Extensions {
static class RandomExtensions {
public static class RandomExtensions {
/// <summary>
/// Returns a random long from min (inclusive) to max (exclusive)
/// </summary>
Expand Down
19 changes: 15 additions & 4 deletions src/Cortside.Common.Testing/Logging/LogEvent/LogEventLogger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,12 @@
using Microsoft.Extensions.Logging;

namespace Cortside.Common.Testing.Logging.LogEvent {
public class LogEventLogger<T> : ILogger<T> {
public List<LogEvent> LogEvents { get; }
public class LogEventLogger : ILogger {
private readonly string name;
public static List<LogEvent> LogEvents { get; } = new List<LogEvent>();

public LogEventLogger() {
LogEvents = new List<LogEvent>();
public LogEventLogger(string name) {
this.name = name;
}

public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter) {
Expand All @@ -24,6 +25,16 @@ public bool IsEnabled(LogLevel logLevel) {
}

public IDisposable BeginScope<TState>(TState state) {
var s = string.Empty;
if (state is IEnumerable<KeyValuePair<string, object>>) {
var context = state as IEnumerable<KeyValuePair<string, object>>;
foreach (var kp in context) {
s += kp.Key + "=" + kp.Value.ToString();
}

LogEvents.Add(new LogEvent() { LogLevel = LogLevel.None, Message = s });
}

return NullScope.Instance;
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Logging;

namespace Cortside.Common.Testing.Logging.LogEvent {
/// <summary>
/// Extension methods for the <see cref="ILoggerFactory"/> class.
/// </summary>
public static class LogEventLoggerFactoryExtensions {
/// <summary>
/// Adds a debug logger named 'Debug' to the factory.
/// </summary>
/// <param name="builder">The extension method argument.</param>
public static ILoggingBuilder AddLogEvent(this ILoggingBuilder builder) {
builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton<ILoggerProvider>(new LogEventLoggerProvider()));

return builder;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
using Cortside.Common.Testing.Logging.Xunit;
using Microsoft.Extensions.Logging;
using Xunit.Abstractions;

namespace Cortside.Common.Testing.Logging.LogEvent {
/// <summary>
/// The provider for the <see cref="XunitLogger"/>.
/// </summary>
[ProviderAlias("LogEvent")]
public class LogEventLoggerProvider : ILoggerProvider {
private readonly ITestOutputHelper output;

/// <inheritdoc />
public ILogger CreateLogger(string name) {
return new LogEventLogger(name);
}

/// <inheritdoc />
public void Dispose() {
}
}
}
Original file line number Diff line number Diff line change
@@ -1,9 +1,4 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Logging;
using Xunit.Abstractions;

namespace Cortside.Common.Testing.Logging.Xunit {
namespace Cortside.Common.Testing.Logging.Xunit {
/// <summary>
/// Extension methods for the <see cref="ILoggerFactory"/> class.
/// </summary>
Expand Down
6 changes: 6 additions & 0 deletions src/Cortside.Common.sln
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Cortside.Common.Correlation
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Cortside.Common.Correlation.Tests", "Cortside.Common.Correlation.Tests\Cortside.Common.Correlation.Tests.csproj", "{58003B10-A4C3-4EF7-A5B8-5A7C927406FB}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Cortside.Common.Logging", "Cortside.Common.Logging\Cortside.Common.Logging.csproj", "{ECE6C743-FCA4-47CA-97A2-645BAB61E1BA}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -167,6 +169,10 @@ Global
{58003B10-A4C3-4EF7-A5B8-5A7C927406FB}.Debug|Any CPU.Build.0 = Debug|Any CPU
{58003B10-A4C3-4EF7-A5B8-5A7C927406FB}.Release|Any CPU.ActiveCfg = Release|Any CPU
{58003B10-A4C3-4EF7-A5B8-5A7C927406FB}.Release|Any CPU.Build.0 = Release|Any CPU
{ECE6C743-FCA4-47CA-97A2-645BAB61E1BA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{ECE6C743-FCA4-47CA-97A2-645BAB61E1BA}.Debug|Any CPU.Build.0 = Debug|Any CPU
{ECE6C743-FCA4-47CA-97A2-645BAB61E1BA}.Release|Any CPU.ActiveCfg = Release|Any CPU
{ECE6C743-FCA4-47CA-97A2-645BAB61E1BA}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down

0 comments on commit cc4d26c

Please sign in to comment.