Guards structured logging with IsEnabled checks

This commit is contained in:
BinaryAlley committed 2026-11-26 12:35:30 +02:00
1 parent ccbd653ee5
commit 2e53449ada
44 files changed
+448 -136

No files matched your search

@@ -14,6 +14,7 @@ using Microsoft.Extensions.Logging;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
@@ -154,6 +155,7 @@ public class EventualConsistencyMiddlewareTests
httpContext.Request.Path = "/api/v1/probe";
httpContext.Response.StatusCode = StatusCodes.Status200OK;
ILogger<EventualConsistencyMiddleware> mockLogger = Substitute.For<ILogger<EventualConsistencyMiddleware>>();
mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(true);
EventualConsistencyMiddleware sut = new(_ => Task.CompletedTask, mockLogger);
IUnitOfWork mockUnitOfWork = Substitute.For<IUnitOfWork>();
mockUnitOfWork
@@ -170,6 +172,12 @@ public class EventualConsistencyMiddlewareTests
// The completion callback must never leave a transaction open after a failed commit, and it must never publish events that belong to a transaction that did not commit.
await mockUnitOfWork.Received(1).RollbackTransactionAsync(Arg.Any<CancellationToken>());
await mockPublisher.DidNotReceive().PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>());
mockLogger.Received(1).Log(
LogLevel.Error,
Arg.Any<EventId>(),
Arg.Any<object>(),
Arg.Is<Exception>(exception => exception is InvalidOperationException && exception.Message == "commit failed"),
Arg.Any<Func<object, Exception?, string>>());
}
/// <summary>
@@ -33,6 +33,7 @@ public class ExceptionHandlingMiddlewareTests
public ExceptionHandlingMiddlewareTests()
{
_mockLogger = Substitute.For<ILogger<ExceptionHandlingMiddleware>>();
_mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(true);
_sut = new ExceptionHandlingMiddleware(context => _nextDelegate(context), _mockLogger);
}
@@ -87,6 +88,30 @@ public class ExceptionHandlingMiddlewareTests
Arg.Any<Func<object, Exception?, string>>());
}
[Fact]
public async Task InvokeAsync_WhenLoggingIsDisabledAndNextThrowsException_ShouldNotLogTheException()
{
// Arrange
_mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(false);
DefaultHttpContext context = new()
{
Response = { Body = new MemoryStream() }
};
_nextDelegate = _ => throw new InvalidOperationException("sensitive internal details");
// Act
await _sut.InvokeAsync(context);
// Assert
Assert.Equal(StatusCodes.Status500InternalServerError, context.Response.StatusCode);
_mockLogger.DidNotReceive().Log(
LogLevel.Error,
Arg.Any<EventId>(),
Arg.Any<object>(),
Arg.Any<Exception?>(),
Arg.Any<Func<object, Exception?, string>>());
}
[Fact]
public async Task InvokeAsync_WhenNextThrowsExceptionAndActivityIsCurrent_ShouldUseTheActivityIdAsTraceId()
{