Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

perf(CA1848): Use the LoggerMessage delegates #104

Merged
merged 1 commit into from
Feb 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions src/MockHttp.Server/Server/Log.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;

namespace MockHttp.Server;

internal static partial class Log
{
internal const string LogRequestMessageTemplate = "Connection id \"{ConnectionId}\", Request id \"{RequestId}\": {Message}";

#if NET6_0_OR_GREATER
[LoggerMessage(
EventId = 0,
Level = LogLevel.Debug,
Message = LogRequestMessageTemplate)]
private static partial void LogDebugRequestMessage(ILogger logger, string connectionId, string requestId, string message, Exception? exception);
#else
private static readonly Action<ILogger, string, string, string, Exception?> LogDebugRequestMessage = LoggerMessage.Define<string, string, string>(LogLevel.Debug, new EventId(0), LogRequestMessageTemplate);
#endif

public static void LogRequestMessage(this ILogger logger, HttpContext httpContext, string message, Exception? exception = null)
{
LogDebugRequestMessage(logger, httpContext.Connection.Id, httpContext.TraceIdentifier, message, exception);
}
}
14 changes: 3 additions & 11 deletions src/MockHttp.Server/Server/ServerRequestHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public async Task HandleAsync(HttpContext httpContext, Func<Task> _)
throw new ArgumentNullException(nameof(httpContext));
}

LogRequestMessage(httpContext, Resources.Debug_HandlingRequest);
_logger.LogRequestMessage(httpContext, Resources.Debug_HandlingRequest);

CancellationToken cancellationToken = httpContext.RequestAborted;
HttpResponse response = httpContext.Response;
Expand All @@ -40,7 +40,7 @@ public async Task HandleAsync(HttpContext httpContext, Func<Task> _)
}
catch (Exception ex)
{
LogRequestMessage(httpContext, Resources.Error_VerifyMockSetup);
_logger.LogRequestMessage(httpContext, Resources.Error_VerifyMockSetup);

#pragma warning disable CA2000 // Dispose objects before losing scope
httpResponseMessage = new HttpResponseMessage(HttpStatusCode.InternalServerError)
Expand All @@ -52,7 +52,7 @@ public async Task HandleAsync(HttpContext httpContext, Func<Task> _)
}
finally
{
LogRequestMessage(httpContext, Resources.Debug_RequestHandled);
_logger.LogRequestMessage(httpContext, Resources.Debug_RequestHandled);
}

// Dispose message when response is done.
Expand All @@ -67,12 +67,4 @@ public async Task HandleAsync(HttpContext httpContext, Func<Task> _)
}
await httpResponseMessage.MapToFeatureAsync(responseFeature, responseBodyFeature, cancellationToken).ConfigureAwait(false);
}

private void LogRequestMessage(HttpContext httpContext, string message, LogLevel logLevel = LogLevel.Debug, Exception? ex = null)
{
string formattedMessage = Resources.RequestLogMessage + message;
#pragma warning disable CA2254 // Template should be a static expression
_logger.Log(logLevel, ex, formattedMessage, httpContext.Connection.Id, httpContext.TraceIdentifier);
#pragma warning restore CA2254 // Template should be a static expression
}
}
43 changes: 43 additions & 0 deletions test/MockHttp.Server.Tests/Server/LogTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;

namespace MockHttp.Server;

public sealed class LogTests
{
[Fact]
public void Log_should_produce_expected_output()
{
ILogger? logger = Substitute.For<ILogger>();
logger.IsEnabled(Arg.Any<LogLevel>()).Returns(true);

string traceId = Guid.NewGuid().ToString("D");
string connId = Guid.NewGuid().ToString("D");
var httpContext = new DefaultHttpContext { TraceIdentifier = traceId, Connection = { Id = connId } };

const string customMessage = "hello world";
var ex = new InvalidOperationException();

Func<IReadOnlyList<KeyValuePair<string, object>>, bool> assertState = state =>
{
state.Should().ContainKey("{OriginalFormat}").WhoseValue.Should().Be(Log.LogRequestMessageTemplate);
state.Should().ContainKey("RequestId").WhoseValue.Should().Be(traceId);
state.Should().ContainKey("ConnectionId").WhoseValue.Should().Be(connId);
state.Should().ContainKey("Message").WhoseValue.Should().Be(customMessage);
return true;
};

// Act
logger.LogRequestMessage(httpContext, customMessage, ex);

// Assert
logger.Received(1)
.Log(
LogLevel.Debug,
Arg.Is<EventId>(e => e.Id == 0),
Arg.Is<IReadOnlyList<KeyValuePair<string, object>>>(state => assertState(state)),
ex,
Arg.Any<Func<IReadOnlyList<KeyValuePair<string, object>>, Exception?, string>>()
);
}
}
Loading