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

@@ -49,7 +49,8 @@ internal static class ApplicationHandlerTelemetry
{
activity?.SetStatus(ActivityStatusCode.Ok);
RecordOutcome(activity, handlerName, handlerType, duration, isSuccess: true);
logger.LogDebug("Completed handling {HandlerType} {HandlerName} in {DurationMs}ms", handlerType, handlerName, duration.TotalMilliseconds);
if (logger.IsEnabled(LogLevel.Debug))
logger.LogDebug("Completed handling {HandlerType} {HandlerName} in {DurationMs}ms", handlerType, handlerName, duration.TotalMilliseconds);
}
/// <summary>
@@ -66,7 +67,8 @@ internal static class ApplicationHandlerTelemetry
activity?.SetStatus(ActivityStatusCode.Error, error);
RecordOutcome(activity, handlerName, handlerType, duration, isSuccess: false);
// Business-rule failures are routine outcomes (e.g. failed logins), so log at Debug to avoid noise from high-frequency handlers.
logger.LogDebug("Failed handling {HandlerType} {HandlerName} in {DurationMs}ms: {Error}", handlerType, handlerName, duration.TotalMilliseconds, error);
if (logger.IsEnabled(LogLevel.Debug))
logger.LogDebug("Failed handling {HandlerType} {HandlerName} in {DurationMs}ms: {Error}", handlerType, handlerName, duration.TotalMilliseconds, error);
}
/// <summary>
@@ -82,7 +84,8 @@ internal static class ApplicationHandlerTelemetry
{
activity?.SetStatus(ActivityStatusCode.Error, exception.Message);
RecordOutcome(activity, handlerName, handlerType, duration, isSuccess: false);
logger.LogError(exception, "Failed handling {HandlerType} {HandlerName} in {DurationMs}ms", handlerType, handlerName, duration.TotalMilliseconds);
if (logger.IsEnabled(LogLevel.Error))
logger.LogError(exception, "Failed handling {HandlerType} {HandlerName} in {DurationMs}ms", handlerType, handlerName, duration.TotalMilliseconds);
}
/// <summary>
@@ -72,7 +72,8 @@ internal sealed class BooksMediaLibraryItemDeletionStrategy : IMediaLibraryItemD
Result<Deleted> deleteArtworkResult = _bookArtworkService.DeleteBookArtwork(libraryId, book.Id, library.Title, authorName, book.Title);
if (deleteArtworkResult.IsFailure)
_logger.LogWarning("Failed to delete the stored artwork of the book with Id '{BookId}' at path '{BookPath}', the artwork might remain orphaned.", book.Id, book.Path);
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("Failed to delete the stored artwork of the book with Id '{BookId}' at path '{BookPath}', the artwork might remain orphaned.", book.Id, book.Path);
// Delete the book, whose stored artwork and participations are removed by the database cascade.
Result<Deleted> deleteBookResult = await _unitOfWork.BookRepository.DeleteByIdAsync(book.Id, cancellationToken).ConfigureAwait(false);
@@ -142,7 +142,8 @@ internal sealed class MusicMediaLibraryItemDeletionStrategy : IMediaLibraryItemD
Result<Deleted> deleteStoredArtworkResult = _musicArtworkService.DeleteStoredArtwork(artwork.FileName);
if (deleteStoredArtworkResult.IsFailure)
_logger.LogWarning("Failed to delete the stored {OwnerType} artwork at '{ArtworkPath}' of the music library item with Id '{OwnerId}', the file might remain orphaned.", ownerType, artwork.FileName, ownerId);
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("Failed to delete the stored {OwnerType} artwork at '{ArtworkPath}' of the music library item with Id '{OwnerId}', the file might remain orphaned.", ownerType, artwork.FileName, ownerId);
}
return await _unitOfWork.MusicArtworkRepository.DeleteByOwnerAsync(ownerType, ownerId, cancellationToken).ConfigureAwait(false);
@@ -61,7 +61,8 @@ public class LibraryMediaItemDeletedDomainEventHandler : IDomainEventHandler<Lib
IMediaLibraryItemDeletionStrategy? deletionStrategy = _mediaLibraryItemDeletionStrategies.FirstOrDefault(strategy => strategy.SupportedLibraryType == libraryType);
if (deletionStrategy is null)
{
_logger.LogWarning("No deletion strategy exists for media library type '{LibraryType}', the item at path '{ItemPath}' was not deleted.", libraryType, domainEvent.Path);
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("No deletion strategy exists for media library type '{LibraryType}', the item at path '{ItemPath}' was not deleted.", libraryType, domainEvent.Path);
return;
}
@@ -133,7 +133,8 @@ public class GetThemeTemplateQueryHandler : IQueryHandler<GetThemeTemplateQuery,
{
// The restore is best effort: an unexpected failure must not fail the request, so the caller falls back to
// the application view instead of returning an error to the browser.
_logger.LogWarning(exception, "Failed to restore the files of bundled theme '{ThemeId}'.", theme.ThemeId);
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning(exception, "Failed to restore the files of bundled theme '{ThemeId}'.", theme.ThemeId);
return false;
}
}
@@ -79,13 +79,15 @@ internal static class PublicHostConnectionGuard
catch (PublicHostRejectedException exception)
{
// The address policy refused the target. This is deterministic, so it is logged as a rejection rather than as a transport failure.
logger.LogWarning("Rejected the outbound connection to the host '{Host}' because {RejectionReason}. The connection was not made.", host, exception.RejectionReason);
if (logger.IsEnabled(LogLevel.Warning))
logger.LogWarning("Rejected the outbound connection to the host '{Host}' because {RejectionReason}. The connection was not made.", host, exception.RejectionReason);
throw;
}
catch (PublicHostResolutionException)
{
// The host name could not be resolved. This is reported separately from a policy rejection because it can be transient.
logger.LogWarning("Could not resolve the outbound host '{Host}'. The connection was not made.", host);
if (logger.IsEnabled(LogLevel.Warning))
logger.LogWarning("Could not resolve the outbound host '{Host}'. The connection was not made.", host);
throw;
}
}
@@ -116,7 +116,8 @@ internal sealed class PublicHostRedirectHandler : DelegatingHandler
{
if (result.RejectionReason == OutboundRequestRejectionReason.HostCouldNotBeResolved)
{
_logger.LogWarning("Could not resolve the outbound redirect host '{Host}'. The request was not sent.", redirectUri.IdnHost);
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("Could not resolve the outbound redirect host '{Host}'. The request was not sent.", redirectUri.IdnHost);
throw new PublicHostResolutionException(redirectUri.IdnHost);
}
throw Reject(redirectUri.IdnHost, result.RejectionReason);
@@ -142,7 +143,8 @@ internal sealed class PublicHostRedirectHandler : DelegatingHandler
/// <returns>The exception that reports the rejection.</returns>
private PublicHostRejectedException Reject(string host, OutboundRequestRejectionReason rejectionReason)
{
_logger.LogWarning("Rejected the outbound redirect to the host '{Host}' because {RejectionReason}. The request was not sent.", host, rejectionReason);
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("Rejected the outbound redirect to the host '{Host}' because {RejectionReason}. The request was not sent.", host, rejectionReason);
return new PublicHostRejectedException(host, rejectionReason);
}
@@ -55,11 +55,13 @@ internal sealed class PublicHostValidationHandler : DelegatingHandler
if (result.RejectionReason == OutboundRequestRejectionReason.HostCouldNotBeResolved)
{
_logger.LogWarning("Could not resolve the outbound host '{Host}'. The request was not sent.", requestUri.IdnHost);
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("Could not resolve the outbound host '{Host}'. The request was not sent.", requestUri.IdnHost);
throw new PublicHostResolutionException(requestUri.IdnHost);
}
_logger.LogWarning("Rejected the outbound request to the host '{Host}' because {RejectionReason}. The request was not sent.", requestUri.IdnHost, result.RejectionReason);
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("Rejected the outbound request to the host '{Host}' because {RejectionReason}. The request was not sent.", requestUri.IdnHost, result.RejectionReason);
throw new PublicHostRejectedException(requestUri.IdnHost, result.RejectionReason);
}
@@ -545,7 +545,8 @@ internal sealed class TrackNormalizationService : ITrackNormalizationService, ID
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException)
{
_logger.LogError(exception, "The normalized audio cache directory '{CacheDirectory}' is not available for track {TrackId} in cache entry {CacheId}.", _cacheRoot, request.TrackId, cacheId);
if (_logger.IsEnabled(LogLevel.Error))
_logger.LogError(exception, "The normalized audio cache directory '{CacheDirectory}' is not available for track {TrackId} in cache entry {CacheId}.", _cacheRoot, request.TrackId, cacheId);
return Errors.Playback.NormalizationUnavailable;
}
@@ -588,7 +589,8 @@ internal sealed class TrackNormalizationService : ITrackNormalizationService, ID
catch (Exception exception)
{
// The production is shared by requests that are no longer necessarily waiting, so every failure is turned into a result and observed here.
_logger.LogError(exception, "The normalized audio of track {TrackId} in cache entry {CacheId} could not be produced.", request.TrackId, cacheId);
if (_logger.IsEnabled(LogLevel.Error))
_logger.LogError(exception, "The normalized audio of track {TrackId} in cache entry {CacheId} could not be produced.", request.TrackId, cacheId);
return Errors.Playback.NormalizationFailed;
}
}
@@ -678,7 +680,8 @@ internal sealed class TrackNormalizationService : ITrackNormalizationService, ID
return Errors.Playback.NormalizationFailed;
}
if (isKeptOverCapacity)
_logger.LogWarning("The normalized audio of track {TrackId} in cache entry {CacheId} was produced successfully but exceeds the configured normalized audio cache limit. It is kept readable and will be evicted when it is no longer in use.", request.TrackId, cacheId);
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("The normalized audio of track {TrackId} in cache entry {CacheId} was produced successfully but exceeds the configured normalized audio cache limit. It is kept readable and will be evicted when it is no longer in use.", request.TrackId, cacheId);
return GetOrCreateTrackProjection(cacheId, index);
}
@@ -688,7 +691,8 @@ internal sealed class TrackNormalizationService : ITrackNormalizationService, ID
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or JsonException or NotSupportedException)
{
_logger.LogWarning(exception, "The normalized audio of track {TrackId} in cache entry {CacheId} could not be cached.", request.TrackId, cacheId);
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning(exception, "The normalized audio of track {TrackId} in cache entry {CacheId} could not be cached.", request.TrackId, cacheId);
return Errors.Playback.NormalizationFailed;
}
finally
@@ -748,7 +752,8 @@ internal sealed class TrackNormalizationService : ITrackNormalizationService, ID
}
catch (Exception exception) when (exception is Win32Exception or InvalidOperationException or IOException)
{
_logger.LogError(exception, "The audio transcoder for track {TrackId} in cache entry {CacheId} could not be started.", request.TrackId, cacheId);
if (_logger.IsEnabled(LogLevel.Error))
_logger.LogError(exception, "The audio transcoder for track {TrackId} in cache entry {CacheId} could not be started.", request.TrackId, cacheId);
return Errors.Playback.NormalizationUnavailable;
}
@@ -801,12 +806,16 @@ internal sealed class TrackNormalizationService : ITrackNormalizationService, ID
return Errors.Playback.NormalizationTimedOut;
if (process.ExitCode != 0)
{
_logger.LogWarning("The audio transcoder for track {TrackId} in cache entry {CacheId} exited with code {ExitCode}.", request.TrackId, cacheId, process.ExitCode);
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("The audio transcoder for track {TrackId} in cache entry {CacheId} exited with code {ExitCode}.", request.TrackId, cacheId, process.ExitCode);
if (!string.IsNullOrWhiteSpace(standardError))
{
// The bounded stderr can contain the source path and media metadata. It is only written at Debug and never returned to a client.
string diagnostic = RedactPath(RedactPath(standardError, inputPath), request.SourcePath);
_logger.LogDebug("The audio transcoder for track {TrackId} in cache entry {CacheId} reported: {StandardError}", request.TrackId, cacheId, diagnostic);
if (_logger.IsEnabled(LogLevel.Debug))
{
string diagnostic = RedactPath(RedactPath(standardError, inputPath), request.SourcePath);
_logger.LogDebug("The audio transcoder for track {TrackId} in cache entry {CacheId} reported: {StandardError}", request.TrackId, cacheId, diagnostic);
}
}
return Errors.Playback.NormalizationFailed;
}
@@ -1013,7 +1022,8 @@ internal sealed class TrackNormalizationService : ITrackNormalizationService, ID
if (previousEndSeconds < expectedDurationSeconds - durationToleranceSeconds)
return Errors.Playback.NormalizationFailed;
if (previousEndSeconds > expectedDurationSeconds + durationToleranceSeconds)
_logger.LogInformation("The normalized audio of track {TrackId} in cache entry {CacheId} is longer than the probed duration: produced {ProducedSeconds} seconds, probed {ExpectedSeconds} seconds. The production is kept because only a shortfall is treated as truncation.", request.TrackId, cacheId, previousEndSeconds, expectedDurationSeconds);
if (_logger.IsEnabled(LogLevel.Information))
_logger.LogInformation("The normalized audio of track {TrackId} in cache entry {CacheId} is longer than the probed duration: produced {ProducedSeconds} seconds, probed {ExpectedSeconds} seconds. The production is kept because only a shortfall is treated as truncation.", request.TrackId, cacheId, previousEndSeconds, expectedDurationSeconds);
// The index advertises the produced end, rounded up to the next second, instead of the probed duration. A probe can underestimate a variable
// bitrate file, and a seek map that is shorter than the audio would hide the tail of every segment after the underestimated end.
@@ -1311,7 +1321,8 @@ internal sealed class TrackNormalizationService : ITrackNormalizationService, ID
long actualBytes = outputSizeTracker.GetCurrentSize();
if (!reservation.TryUpdate(actualBytes, _settings.MaxCacheBytes, _evictionGracePeriod))
{
_logger.LogWarning("A normalization job for track {TrackId} in cache entry {CacheId} could not reserve enough space in the normalized audio cache and was stopped.", trackId, cacheId);
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("A normalization job for track {TrackId} in cache entry {CacheId} could not reserve enough space in the normalized audio cache and was stopped.", trackId, cacheId);
KillProcess(process);
return true;
}
@@ -1462,7 +1473,8 @@ internal sealed class TrackNormalizationService : ITrackNormalizationService, ID
OnApplicationStopping(this, EventArgs.Empty);
if (!_productionsDrained.Wait(TimeSpan.FromSeconds(PRODUCTION_DRAIN_TIMEOUT_SECONDS)))
{
_logger.LogWarning("The normalized audio productions did not drain within {DrainTimeoutSeconds} seconds during shutdown. The process lifetime resources are left undisposed.", PRODUCTION_DRAIN_TIMEOUT_SECONDS);
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("The normalized audio productions did not drain within {DrainTimeoutSeconds} seconds during shutdown. The process lifetime resources are left undisposed.", PRODUCTION_DRAIN_TIMEOUT_SECONDS);
return;
}
_cache.Release();
@@ -78,7 +78,8 @@ internal sealed class TranscodingStartupInitializer : IHostedService
catch (OperationCanceledException)
{
if (!cancellationToken.IsCancellationRequested)
_logger.LogWarning("The normalized audio cache cleanup did not finish within {CleanupTimeoutSeconds} seconds. Whatever remains is accounted for by the coordinator and is removed by the next cleanup.", CACHE_CLEANUP_TIMEOUT_SECONDS);
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("The normalized audio cache cleanup did not finish within {CleanupTimeoutSeconds} seconds. Whatever remains is accounted for by the coordinator and is removed by the next cleanup.", CACHE_CLEANUP_TIMEOUT_SECONDS);
}
}
}
@@ -90,13 +91,15 @@ internal sealed class TranscodingStartupInitializer : IHostedService
}
else
TranscodingCachePaths.EnsureDirectoryExists(cacheDirectory);
_logger.LogInformation("The normalized audio cache uses the directory '{CacheDirectory}'.", cacheDirectory);
if (_logger.IsEnabled(LogLevel.Information))
_logger.LogInformation("The normalized audio cache uses the directory '{CacheDirectory}'.", cacheDirectory);
}
catch (Exception exception)
{
// A locked file, a read-only volume or a directory owned by another account must not stop the whole application; the coordinator accounts
// for whatever remains and the service reports normalized playback as unavailable when the directory still cannot be used.
_logger.LogError(exception, "The normalized audio cache could not be initialized (configured directory: '{CacheDirectory}'). Normalized playback may be unavailable.", _settings.CacheDirectory ?? "(default)");
if (_logger.IsEnabled(LogLevel.Error))
_logger.LogError(exception, "The normalized audio cache could not be initialized (configured directory: '{CacheDirectory}'). Normalized playback may be unavailable.", _settings.CacheDirectory ?? "(default)");
}
try
@@ -145,7 +148,8 @@ internal sealed class TranscodingStartupInitializer : IHostedService
if (!process.Start())
{
_toolchainStatus.RecordUnavailable();
_logger.LogWarning("The ffmpeg binary '{FfmpegPath}' could not be started. Normalized playback will be unavailable.", _settings.FfmpegPath);
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("The ffmpeg binary '{FfmpegPath}' could not be started. Normalized playback will be unavailable.", _settings.FfmpegPath);
return;
}
@@ -173,7 +177,8 @@ internal sealed class TranscodingStartupInitializer : IHostedService
_logger.LogDebug(killException, "The ffmpeg startup probe process could not be stopped.");
}
if (!cancellationToken.IsCancellationRequested)
_logger.LogWarning("The ffmpeg binary '{FfmpegPath}' did not respond to the startup probe.", _settings.FfmpegPath);
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("The ffmpeg binary '{FfmpegPath}' did not respond to the startup probe.", _settings.FfmpegPath);
_toolchainStatus.RecordUnavailable();
return;
}
@@ -183,7 +188,8 @@ internal sealed class TranscodingStartupInitializer : IHostedService
if (process.ExitCode != 0)
{
_toolchainStatus.RecordUnavailable();
_logger.LogWarning("The ffmpeg binary '{FfmpegPath}' exited with code {ExitCode} during the startup probe. Normalized playback may be unavailable.", _settings.FfmpegPath, process.ExitCode);
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("The ffmpeg binary '{FfmpegPath}' exited with code {ExitCode} during the startup probe. Normalized playback may be unavailable.", _settings.FfmpegPath, process.ExitCode);
return;
}
@@ -195,16 +201,19 @@ internal sealed class TranscodingStartupInitializer : IHostedService
{
// An unpinned distribution package can change the encoder set without changing the application build, so this is reported at startup instead of surfacing as a per track playback failure.
_toolchainStatus.RecordMissingEncoders(missingEncoders);
_logger.LogError("The ffmpeg binary '{FfmpegPath}' is missing the encoders {MissingEncoders}. Normalized playback for those formats will be unavailable.", _settings.FfmpegPath, string.Join(", ", missingEncoders));
if (_logger.IsEnabled(LogLevel.Error))
_logger.LogError("The ffmpeg binary '{FfmpegPath}' is missing the encoders {MissingEncoders}. Normalized playback for those formats will be unavailable.", _settings.FfmpegPath, string.Join(", ", missingEncoders));
return;
}
_toolchainStatus.RecordAvailable();
_logger.LogInformation("The ffmpeg binary '{FfmpegPath}' provides every encoder the normalized audio pipeline uses.", _settings.FfmpegPath);
if (_logger.IsEnabled(LogLevel.Information))
_logger.LogInformation("The ffmpeg binary '{FfmpegPath}' provides every encoder the normalized audio pipeline uses.", _settings.FfmpegPath);
}
catch (Exception exception) when (exception is Win32Exception or InvalidOperationException or IOException or UnauthorizedAccessException or NotSupportedException)
{
_toolchainStatus.RecordUnavailable();
_logger.LogWarning(exception, "The ffmpeg binary '{FfmpegPath}' could not be probed. Normalized playback will be unavailable.", _settings.FfmpegPath);
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning(exception, "The ffmpeg binary '{FfmpegPath}' could not be probed. Normalized playback will be unavailable.", _settings.FfmpegPath);
}
}
@@ -121,7 +121,8 @@ internal sealed class MusicFileSystemDiscoveryJob : MediaLibraryScanJob, IMusicF
// When the library content is stored on a solid state drive, the file system reads of the scan run in parallel.
bool shouldParallelizeReads = domainLibraryResult.Value.IsContentOnSsd;
if (shouldParallelizeReads)
_logger.LogDebug("The content of the media library with Id '{LibraryId}' is stored on a solid state drive, so its file system reads will run in parallel.", LibraryId.Value);
if (_logger.IsEnabled(LogLevel.Debug))
_logger.LogDebug("The content of the media library with Id '{LibraryId}' is stored on a solid state drive, so its file system reads will run in parallel.", LibraryId.Value);
// Get the files for each of the media library content locations.
foreach (FileSystemPathId contentLocation in domainLibraryResult.Value.ContentLocations)
@@ -336,7 +337,8 @@ internal sealed class MusicFileSystemDiscoveryJob : MediaLibraryScanJob, IMusicF
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
// A file might become inaccessible between enumeration and processing, so it is skipped.
_logger.LogWarning(ex, "Failed to read the metadata of the music file '{Path}', so it is skipped for this scan.", filesToProcess[index].Path);
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning(ex, "Failed to read the metadata of the music file '{Path}', so it is skipped for this scan.", filesToProcess[index].Path);
}
});
}
@@ -120,7 +120,8 @@ internal sealed class MusicMediaLibraryScanArtworkEnricher : IMediaLibraryScanAr
.Where(provider => provider.SupportedLibraryTypes.Contains(LibraryType.Music)
&& (canDownloadMetadataFromWeb || !provider.RequiresWebAccess))];
if (configuredProviders.Count == 0)
_logger.LogWarning("No artwork provider was found for the configured plugin with Id '{PluginId}' and the {LibraryType} library type.", configuration.PluginId, LibraryType.Music);
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("No artwork provider was found for the configured plugin with Id '{PluginId}' and the {LibraryType} library type.", configuration.PluginId, LibraryType.Music);
artworkProviders.AddRange(configuredProviders);
}
}
@@ -129,7 +130,8 @@ internal sealed class MusicMediaLibraryScanArtworkEnricher : IMediaLibraryScanAr
// When no artwork provider is available, the items must not be marked as failed to resolve, so the enrichment is skipped entirely.
if (artworkProviders.Count == 0)
{
_logger.LogWarning("No artwork provider is configured for the media library with Id '{LibraryId}', the artwork enrichment will be skipped.", libraryId.Value);
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("No artwork provider is configured for the media library with Id '{LibraryId}', the artwork enrichment will be skipped.", libraryId.Value);
return;
}
@@ -414,18 +416,19 @@ internal sealed class MusicMediaLibraryScanArtworkEnricher : IMediaLibraryScanAr
Result<Deleted> deleteStoredArtworkResult = deleteStoredArtwork();
if (deleteStoredArtworkResult.IsFailure)
{
_logger.LogWarning("Failed to clear the stored artwork files of the {OwnerType} '{OwnerDescription}'.", ownerType, ownerDescription);
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("Failed to clear the stored artwork files of the {OwnerType} '{OwnerDescription}'.", ownerType, ownerDescription);
// Some files may have been deleted before the failure, so the stored records are dropped and the owner is marked as failed,
// keeping it eligible for a retry without serving the paths of the files that no longer exist.
Result<Deleted> deleteFailedEntitiesResult = await unitOfWork.MusicArtworkRepository.DeleteByOwnerAsync(ownerType, ownerId, cancellationToken).ConfigureAwait(false);
if (deleteFailedEntitiesResult.IsFailure)
_logger.LogWarning("Failed to clear the stored artwork records of the {OwnerType} '{OwnerDescription}'.", ownerType, ownerDescription);
else
if (deleteFailedEntitiesResult.IsSuccess)
{
List<MusicArtworkEntity> failedArtworkEntities = [CreateArtworkEntity(ownerId, ownerType, ArtworkType.Cover, 0, null, 0, ArtworkStatus.Failed, null)];
await PersistArtworkAsync(unitOfWork, failedArtworkEntities, cancellationToken).ConfigureAwait(false);
}
else if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("Failed to clear the stored artwork records of the {OwnerType} '{OwnerDescription}'.", ownerType, ownerDescription);
DeleteTemporaryArtworks(resolution.Artworks.Select(resolvedArtwork => resolvedArtwork.Artwork));
return false;
@@ -433,7 +436,8 @@ internal sealed class MusicMediaLibraryScanArtworkEnricher : IMediaLibraryScanAr
Result<Deleted> deleteEntitiesResult = await unitOfWork.MusicArtworkRepository.DeleteByOwnerAsync(ownerType, ownerId, cancellationToken).ConfigureAwait(false);
if (deleteEntitiesResult.IsFailure)
{
_logger.LogWarning("Failed to clear the stored artwork records of the {OwnerType} '{OwnerDescription}'.", ownerType, ownerDescription);
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("Failed to clear the stored artwork records of the {OwnerType} '{OwnerDescription}'.", ownerType, ownerDescription);
DeleteTemporaryArtworks(resolution.Artworks.Select(resolvedArtwork => resolvedArtwork.Artwork));
return false;
}
@@ -448,7 +452,8 @@ internal sealed class MusicMediaLibraryScanArtworkEnricher : IMediaLibraryScanAr
Result<string> saveArtworkResult = await saveArtworkAsync(artwork, cancellationToken).ConfigureAwait(false);
if (saveArtworkResult.IsFailure)
{
_logger.LogWarning("Failed to store the {ArtworkType} artwork of the {OwnerType} '{OwnerDescription}'.", artwork.Type, ownerType, ownerDescription);
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("Failed to store the {ArtworkType} artwork of the {OwnerType} '{OwnerDescription}'.", artwork.Type, ownerType, ownerDescription);
continue;
}
@@ -558,7 +563,8 @@ internal sealed class MusicMediaLibraryScanArtworkEnricher : IMediaLibraryScanAr
{
// A failing artwork provider must not prevent the other providers from being tried, but the failure must be surfaced for diagnostics.
hasFailed = true;
_logger.LogWarning(exception, "The artwork provider '{ProviderName}' failed while resolving the artwork of '{OwnerDescription}'.", provider.Name, ownerDescription);
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning(exception, "The artwork provider '{ProviderName}' failed while resolving the artwork of '{OwnerDescription}'.", provider.Name, ownerDescription);
continue;
}
@@ -601,7 +607,8 @@ internal sealed class MusicMediaLibraryScanArtworkEnricher : IMediaLibraryScanAr
{
// A failing artwork provider must not prevent the other providers from being tried, but the failure must be surfaced for diagnostics.
hasFailed = true;
_logger.LogWarning(exception, "The artwork provider '{ProviderName}' failed while resolving the artwork of '{OwnerDescription}'.", provider.Name, ownerDescription);
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning(exception, "The artwork provider '{ProviderName}' failed while resolving the artwork of '{OwnerDescription}'.", provider.Name, ownerDescription);
continue;
}
@@ -105,7 +105,8 @@ internal sealed class MusicMediaLibraryScanMetadataEnricher : IMediaLibraryScanM
.Where(provider => provider.SupportedLibraryTypes.Contains(LibraryType.Music)
&& (canDownloadMetadataFromWeb || !provider.RequiresWebAccess))];
if (configuredProviders.Count == 0)
_logger.LogWarning("No metadata provider was found for the configured plugin with Id '{PluginId}' and the {LibraryType} library type.", configuration.PluginId, LibraryType.Music);
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("No metadata provider was found for the configured plugin with Id '{PluginId}' and the {LibraryType} library type.", configuration.PluginId, LibraryType.Music);
providers.AddRange(configuredProviders);
}
@@ -193,7 +194,10 @@ internal sealed class MusicMediaLibraryScanMetadataEnricher : IMediaLibraryScanM
// A unique constraint conflict on a shared lookup such as a media contributor can happen when two scans enrich concurrently;
// it must not abort the whole scan, so the artist is left unenriched and retried on the next scan, while the rest proceeds.
if (saveChangesResult.FirstError == Errors.Persistence.UniqueConstraintViolation)
_logger.LogWarning("The enriched metadata of the artist '{ArtistName}' could not be persisted because of a unique constraint conflict; it will be retried on the next scan.", artistEntity.Name);
{
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("The enriched metadata of the artist '{ArtistName}' could not be persisted because of a unique constraint conflict; it will be retried on the next scan.", artistEntity.Name);
}
else
throw new InvalidOperationException(saveChangesResult.FirstError.Description);
}
@@ -209,7 +213,7 @@ internal sealed class MusicMediaLibraryScanMetadataEnricher : IMediaLibraryScanM
if (publishFinalProgressResult.IsFailure)
throw new InvalidOperationException(publishFinalProgressResult.FirstError.Description);
}
else
else if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("No metadata provider is configured for the media library with Id '{LibraryId}', the metadata enrichment will be skipped.", libraryId.Value);
}
@@ -414,7 +418,8 @@ internal sealed class MusicMediaLibraryScanMetadataEnricher : IMediaLibraryScanM
catch (Exception exception)
{
// A failing metadata provider must not prevent the other providers from being tried, but the failure must be surfaced for diagnostics.
logger.LogWarning(exception, "The metadata provider '{ProviderName}' failed while resolving a {LookupType} lookup for '{Lookup}'.", metadataProvider.Name, typeof(TLookup).Name, lookup);
if (logger.IsEnabled(LogLevel.Warning))
logger.LogWarning(exception, "The metadata provider '{ProviderName}' failed while resolving a {LookupType} lookup for '{Lookup}'.", metadataProvider.Name, typeof(TLookup).Name, lookup);
}
}
return null;
@@ -456,7 +461,8 @@ internal sealed class MusicMediaLibraryScanMetadataEnricher : IMediaLibraryScanM
catch (Exception exception)
{
// A failing metadata provider must not prevent the other providers from being tried, but the failure must be surfaced for diagnostics.
logger.LogWarning(exception, "The metadata provider '{ProviderName}' failed while resolving a {LookupType} lookup for '{Lookup}'.", metadataProvider.Name, typeof(TLookup).Name, lookup);
if (logger.IsEnabled(LogLevel.Warning))
logger.LogWarning(exception, "The metadata provider '{ProviderName}' failed while resolving a {LookupType} lookup for '{Lookup}'.", metadataProvider.Name, typeof(TLookup).Name, lookup);
}
}
@@ -311,7 +311,8 @@ internal sealed class MusicMetadataExtractionJob : MediaLibraryScanJob, IMusicMe
{
// A music file whose tags cannot be read still contributes the metadata derived from its path, but the failure is logged, so that a
// systematic tagging failure of a whole library does not silently degrade every file to path only metadata.
_logger.LogWarning(exception, "Failed to read the embedded tags of the music file '{Path}'. Its metadata will be derived from the path only.", path);
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning(exception, "Failed to read the embedded tags of the music file '{Path}'. Its metadata will be derived from the path only.", path);
}
if (string.IsNullOrWhiteSpace(trackTitle))
@@ -124,7 +124,8 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF
// When the library content is stored on a solid state drive, the file system reads of the scan run in parallel.
bool shouldParallelizeReads = domainLibraryResult.Value.IsContentOnSsd;
if (shouldParallelizeReads)
_logger.LogDebug("The content of the media library with Id '{LibraryId}' is stored on a solid state drive, so its file system reads will run in parallel.", LibraryId.Value);
if (_logger.IsEnabled(LogLevel.Debug))
_logger.LogDebug("The content of the media library with Id '{LibraryId}' is stored on a solid state drive, so its file system reads will run in parallel.", LibraryId.Value);
// Get the files for each of the media library content locations.
foreach (FileSystemPathId contentLocation in domainLibraryResult.Value.ContentLocations)
@@ -261,7 +262,8 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
_logger.LogWarning(ex, "Failed to enumerate the files of the directory '{DirectoryPath}', so its files are skipped for this scan.", currentDirectory.FullName);
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning(ex, "Failed to enumerate the files of the directory '{DirectoryPath}', so its files are skipped for this scan.", currentDirectory.FullName);
}
if (files is not null)
@@ -289,7 +291,8 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
// A file might become inaccessible between enumeration and processing, so the remaining files of the directory are skipped.
_logger.LogWarning(ex, "Failed to read the metadata of the files of the directory '{DirectoryPath}', so the remaining files of the directory are skipped for this scan.", currentDirectory.FullName);
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning(ex, "Failed to read the metadata of the files of the directory '{DirectoryPath}', so the remaining files of the directory are skipped for this scan.", currentDirectory.FullName);
}
}
@@ -301,7 +304,8 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
_logger.LogWarning(ex, "Failed to enumerate the subdirectories of the directory '{DirectoryPath}', so its subtree is skipped for this scan.", currentDirectory.FullName);
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning(ex, "Failed to enumerate the subdirectories of the directory '{DirectoryPath}', so its subtree is skipped for this scan.", currentDirectory.FullName);
}
if (subdirectories is not null)
@@ -316,7 +320,8 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
_logger.LogWarning(ex, "Failed to process the subdirectories of the directory '{DirectoryPath}', so the remaining subdirectories are skipped for this scan.", currentDirectory.FullName);
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning(ex, "Failed to process the subdirectories of the directory '{DirectoryPath}', so the remaining subdirectories are skipped for this scan.", currentDirectory.FullName);
}
}
}
@@ -350,7 +355,8 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
// A file might become inaccessible between enumeration and processing, so it is skipped.
_logger.LogWarning(ex, "Failed to read the metadata of the book file '{Path}', so it is skipped for this scan.", filesToProcess[index].FullName);
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning(ex, "Failed to read the metadata of the book file '{Path}', so it is skipped for this scan.", filesToProcess[index].FullName);
}
});
}
@@ -105,7 +105,8 @@ internal sealed class BooksMediaLibraryScanArtworkEnricher : IMediaLibraryScanAr
.Where(provider => provider.SupportedLibraryTypes.Contains(LibraryType.Book)
&& (canDownloadMetadataFromWeb || !provider.RequiresWebAccess))];
if (configuredProviders.Count == 0)
_logger.LogWarning("No artwork provider was found for the configured plugin with Id '{PluginId}' and the {LibraryType} library type.", configuration.PluginId, LibraryType.Book);
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("No artwork provider was found for the configured plugin with Id '{PluginId}' and the {LibraryType} library type.", configuration.PluginId, LibraryType.Book);
artworkProviders.AddRange(configuredProviders);
}
}
@@ -176,7 +177,7 @@ internal sealed class BooksMediaLibraryScanArtworkEnricher : IMediaLibraryScanAr
lastPath = booksPage[^1].Path;
}
}
else
else if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("No artwork provider is configured for the media library with Id '{LibraryId}', the artwork enrichment will be skipped.", libraryId.Value);
}
@@ -103,7 +103,8 @@ internal sealed class BooksMediaLibraryScanMetadataEnricher : IMediaLibraryScanM
&& provider.SupportedLibraryTypes.Contains(LibraryType.Book)
&& (canDownloadMetadataFromWeb || !provider.RequiresWebAccess))];
if (configuredProviders.Count == 0)
_logger.LogWarning("No metadata provider was found for the configured plugin with Id '{PluginId}' and the {LibraryType} library type.", configuration.PluginId, LibraryType.Book);
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("No metadata provider was found for the configured plugin with Id '{PluginId}' and the {LibraryType} library type.", configuration.PluginId, LibraryType.Book);
providers.AddRange(configuredProviders);
}
@@ -180,7 +181,7 @@ internal sealed class BooksMediaLibraryScanMetadataEnricher : IMediaLibraryScanM
lastPath = booksPage[^1].Path;
}
}
else
else if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("No metadata provider is configured for the media library with Id '{LibraryId}', the metadata enrichment will be skipped.", libraryId.Value);
}
@@ -68,7 +68,8 @@ internal sealed class MediaLibraryScanProcessorJob : BackgroundService
catch (Exception exception)
{
// A scan that fails must never stop the scans that are queued behind it, so its failure is logged and the queue keeps draining.
_logger.LogError(exception, "Failed to process the media library scan '{ScanId}'.", compositeId.ScanId.Value);
if (_logger.IsEnabled(LogLevel.Error))
_logger.LogError(exception, "Failed to process the media library scan '{ScanId}'.", compositeId.ScanId.Value);
}
}
}
@@ -105,7 +106,8 @@ internal sealed class MediaLibraryScanProcessorJob : BackgroundService
compositeId.ScanId.Value, shouldTrackEntities: false, cancellationToken: linkedSource.Token).ConfigureAwait(false);
if (getLibraryScanResult.IsFailure)
{
_logger.LogError("Failed to read the media library scan '{ScanId}': {Error}", compositeId.ScanId.Value, getLibraryScanResult.FirstError.Description);
if (_logger.IsEnabled(LogLevel.Error))
_logger.LogError("Failed to read the media library scan '{ScanId}': {Error}", compositeId.ScanId.Value, getLibraryScanResult.FirstError.Description);
return;
}
@@ -142,13 +144,15 @@ internal sealed class MediaLibraryScanProcessorJob : BackgroundService
rootJob = startScanResult.Value;
}
_logger.LogInformation("Started the media library scan '{ScanId}' of the media library '{LibraryId}'.", compositeId.ScanId.Value, libraryScan.LibraryId.Value);
if (_logger.IsEnabled(LogLevel.Information))
_logger.LogInformation("Started the media library scan '{ScanId}' of the media library '{LibraryId}'.", compositeId.ScanId.Value, libraryScan.LibraryId.Value);
// The file system discovery job is the only top level job of the scan job graph, and every job awaits its children, so awaiting it
// completes the entire scan. The next queued scan is only dequeued once this call returns.
await rootJob.ExecuteAsync(Guid.CreateVersion7(), new { }, linkedSource.Token).ConfigureAwait(false);
_logger.LogInformation("Completed the media library scan '{ScanId}' of the media library '{LibraryId}'.", compositeId.ScanId.Value, libraryScan.LibraryId.Value);
if (_logger.IsEnabled(LogLevel.Information))
_logger.LogInformation("Completed the media library scan '{ScanId}' of the media library '{LibraryId}'.", compositeId.ScanId.Value, libraryScan.LibraryId.Value);
}
catch (OperationCanceledException)
{
@@ -158,10 +162,10 @@ internal sealed class MediaLibraryScanProcessorJob : BackgroundService
{
// An unexpected preparation failure must still leave the scan failed instead of pending forever, and must not affect the scans queued behind it.
// The failure is reported without a cancellation token, because the scan token may already be cancelled and the report must still be published.
if (libraryId is null)
_logger.LogError(exception, "Failed to process the media library scan '{ScanId}'.", compositeId.ScanId.Value);
else
if (libraryId is not null)
await ReportScanFailureAsync(compositeId, libraryId, exception, CancellationToken.None).ConfigureAwait(false);
else if (_logger.IsEnabled(LogLevel.Error))
_logger.LogError(exception, "Failed to process the media library scan '{ScanId}'.", compositeId.ScanId.Value);
}
}
@@ -175,7 +179,8 @@ internal sealed class MediaLibraryScanProcessorJob : BackgroundService
/// <returns>A task that represents the asynchronous operation.</returns>
private async Task ReportScanFailureAsync(MediaLibraryScanCompositeId compositeId, LibraryId libraryId, Exception exception, CancellationToken cancellationToken)
{
_logger.LogError(exception, "Failed to start the media library scan '{ScanId}'.", compositeId.ScanId.Value);
if (_logger.IsEnabled(LogLevel.Error))
_logger.LogError(exception, "Failed to start the media library scan '{ScanId}'.", compositeId.ScanId.Value);
await ScanFailurePublisher.PublishAsync(_serviceScopeFactory, libraryId, compositeId, exception, cancellationToken).ConfigureAwait(false);
}
}
@@ -186,7 +186,8 @@ internal sealed class BookReadingService : IBookReadingService
}
catch (Exception exception)
{
_logger.LogError(exception, "Failed to produce the resource '{ResourceKey}' of the book '{BookId}'.", resourceKey, bookId);
if (_logger.IsEnabled(LogLevel.Error))
_logger.LogError(exception, "Failed to produce the resource '{ResourceKey}' of the book '{BookId}'.", resourceKey, bookId);
return Error.Failure(code: "Reading.ResourceProductionFailed", description: "The resource of the book could not be produced.");
}
@@ -335,7 +336,8 @@ internal sealed class BookReadingService : IBookReadingService
}
catch (Exception exception)
{
_logger.LogError(exception, "Failed to open the book '{BookId}' for reading.", bookId);
if (_logger.IsEnabled(LogLevel.Error))
_logger.LogError(exception, "Failed to open the book '{BookId}' for reading.", bookId);
return Error.Failure(code: "Reading.ExtractionFailed", description: "The book could not be opened for reading.");
}
}
@@ -56,7 +56,8 @@ internal sealed class PluginDetectionSyncJob : BackgroundService
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
foreach (PluginLoadErrorDto loadError in _loadErrors)
_logger.LogWarning("Plugin load failure: {LoadError}", loadError.ErrorMessage);
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("Plugin load failure: {LoadError}", loadError.ErrorMessage);
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetRequiredService<IUnitOfWork>();
@@ -78,7 +79,8 @@ internal sealed class PluginDetectionSyncJob : BackgroundService
};
Result<Updated> upsertResult = await unitOfWork.PluginRepository.UpsertAsync(pluginEntity, stoppingToken).ConfigureAwait(false);
if (upsertResult.IsFailure)
_logger.LogError("Failed to persist the detection of plugin '{PluginName}': {Error}", plugin.Name, upsertResult.FirstError.Description);
if (_logger.IsEnabled(LogLevel.Error))
_logger.LogError("Failed to persist the detection of plugin '{PluginName}': {Error}", plugin.Name, upsertResult.FirstError.Description);
}
foreach (PluginLoadErrorDto loadError in _loadErrors)
@@ -99,7 +101,8 @@ internal sealed class PluginDetectionSyncJob : BackgroundService
};
Result<Updated> upsertResult = await unitOfWork.PluginRepository.UpsertAsync(pluginEntity, stoppingToken).ConfigureAwait(false);
if (upsertResult.IsFailure)
_logger.LogError("Failed to persist the detection of plugin '{PluginName}': {Error}", loadError.AssemblyName, upsertResult.FirstError.Description);
if (_logger.IsEnabled(LogLevel.Error))
_logger.LogError("Failed to persist the detection of plugin '{PluginName}': {Error}", loadError.AssemblyName, upsertResult.FirstError.Description);
}
// Remove the rows of the plugins that are no longer detected, so that each plugin assembly has exactly one row regardless of its load status,
@@ -116,10 +119,12 @@ internal sealed class PluginDetectionSyncJob : BackgroundService
continue;
Result<Deleted> deleteResult = await unitOfWork.PluginRepository.DeleteByIdAsync(plugin.Id, stoppingToken).ConfigureAwait(false);
if (deleteResult.IsFailure)
_logger.LogError("Failed to remove the stale detection of plugin '{PluginName}': {Error}", plugin.Name, deleteResult.FirstError.Description);
if (_logger.IsEnabled(LogLevel.Error))
_logger.LogError("Failed to remove the stale detection of plugin '{PluginName}': {Error}", plugin.Name, deleteResult.FirstError.Description);
Result<Deleted> removeConfigurationsResult = await providerConfigurationStore.RemoveProviderConfigurationsAsync(plugin.Id, stoppingToken).ConfigureAwait(false);
if (removeConfigurationsResult.IsFailure)
_logger.LogError("Failed to remove the provider configurations of the removed plugin '{PluginName}': {Error}", plugin.Name, removeConfigurationsResult.FirstError.Description);
if (_logger.IsEnabled(LogLevel.Error))
_logger.LogError("Failed to remove the provider configurations of the removed plugin '{PluginName}': {Error}", plugin.Name, removeConfigurationsResult.FirstError.Description);
}
}
@@ -135,7 +140,8 @@ internal sealed class PluginDetectionSyncJob : BackgroundService
{
Result<Success> ensureResult = await providerConfigurationStore.EnsureProviderConfigurationsAsync(library.Id, library.LibraryType, stoppingToken).ConfigureAwait(false);
if (ensureResult.IsFailure)
_logger.LogError("Failed to seed the provider configurations of the media library '{LibraryTitle}': {Error}", library.Title, ensureResult.FirstError.Description);
if (_logger.IsEnabled(LogLevel.Error))
_logger.LogError("Failed to seed the provider configurations of the media library '{LibraryTitle}': {Error}", library.Title, ensureResult.FirstError.Description);
}
}
@@ -44,7 +44,8 @@ internal sealed class PluginSettingsStore : IPluginSettingsStore
Result<PluginEntity?> getPluginResult = await _unitOfWork.PluginRepository.GetByIdAsync(pluginId, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getPluginResult.IsFailure)
{
_logger.LogWarning("Failed to read the settings of the plugin with Id '{PluginId}': {Error}", pluginId, getPluginResult.FirstError.Description);
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("Failed to read the settings of the plugin with Id '{PluginId}': {Error}", pluginId, getPluginResult.FirstError.Description);
return null;
}
@@ -133,7 +133,8 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS
Result<IEnumerable<ScheduledJobEntity>> getScheduledJobsResult = await unitOfWork.ScheduledJobRepository.GetActiveOrRunningAsync(cancellationToken).ConfigureAwait(false);
if (getScheduledJobsResult.IsFailure)
{
_logger.LogWarning("Failed to read the scheduled jobs to decide whether the themes must be synchronized: {Error}", getScheduledJobsResult.FirstError.Description);
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("Failed to read the scheduled jobs to decide whether the themes must be synchronized: {Error}", getScheduledJobsResult.FirstError.Description);
return;
}
// When an active "Repair themes at startup" job exists, its cycle is resumed below and it runs the synchronization.
@@ -170,7 +171,8 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS
.GetAllAsync<BaseFilterDto>(cancellationToken: cancellationToken).ConfigureAwait(false);
if (getScheduledJobsResult.IsFailure)
{
_logger.LogWarning("Failed to read the scheduled jobs to ensure the technical data cleanup job: {Error}", getScheduledJobsResult.FirstError.Description);
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("Failed to read the scheduled jobs to ensure the technical data cleanup job: {Error}", getScheduledJobsResult.FirstError.Description);
return;
}
@@ -196,13 +198,15 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS
Result<Created> insertScheduledJobResult = await unitOfWork.ScheduledJobRepository.InsertAsync(technicalDataCleanupJob, cancellationToken).ConfigureAwait(false);
if (insertScheduledJobResult.IsFailure)
{
_logger.LogWarning("Failed to insert the technical data cleanup scheduled job: {Error}", insertScheduledJobResult.FirstError.Description);
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("Failed to insert the technical data cleanup scheduled job: {Error}", insertScheduledJobResult.FirstError.Description);
return;
}
Result<Success> saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
if (saveChangesResult.IsFailure)
{
_logger.LogWarning("Failed to save the technical data cleanup scheduled job: {Error}", saveChangesResult.FirstError.Description);
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("Failed to save the technical data cleanup scheduled job: {Error}", saveChangesResult.FirstError.Description);
return;
}
_logger.LogInformation("Created the default 'Technical data cleanup at startup' scheduled job.");
@@ -226,7 +230,8 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS
Result<IEnumerable<ScheduledJobEntity>> getScheduledJobsResult = await unitOfWork.ScheduledJobRepository.GetActiveOrRunningAsync(cancellationToken).ConfigureAwait(false);
if (getScheduledJobsResult.IsFailure)
{
_logger.LogWarning("Failed to read the scheduled jobs to resume: {Error}", getScheduledJobsResult.FirstError.Description);
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("Failed to read the scheduled jobs to resume: {Error}", getScheduledJobsResult.FirstError.Description);
return;
}
foreach (ScheduledJobEntity scheduledJob in getScheduledJobsResult.Value)
@@ -311,7 +316,8 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS
catch (Exception exception)
{
// Failures of a single run are handled inside RunScheduledJobAsync, so an exception reaching this point is unexpected and ends the cycle.
_logger.LogError(exception, "The execution cycle of the scheduled job '{ScheduledJobId}' failed.", scheduledJobId.Value);
if (_logger.IsEnabled(LogLevel.Error))
_logger.LogError(exception, "The execution cycle of the scheduled job '{ScheduledJobId}' failed.", scheduledJobId.Value);
}
finally
{
@@ -335,7 +341,8 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS
catch (OperationCanceledException) { }
catch (Exception exception)
{
_logger.LogError(exception, "The one time execution of the scheduled job '{ScheduledJobId}' failed.", scheduledJobId.Value);
if (_logger.IsEnabled(LogLevel.Error))
_logger.LogError(exception, "The one time execution of the scheduled job '{ScheduledJobId}' failed.", scheduledJobId.Value);
}
}
@@ -360,7 +367,8 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS
}
catch (Exception exception)
{
_logger.LogError(exception, "The execution of the scheduled job '{ScheduledJobId}' failed unexpectedly.", scheduledJobId.Value);
if (_logger.IsEnabled(LogLevel.Error))
_logger.LogError(exception, "The execution of the scheduled job '{ScheduledJobId}' failed unexpectedly.", scheduledJobId.Value);
await ReconcileInterruptedRunAsync(scheduledJobId, CancellationToken.None).ConfigureAwait(false);
}
finally
@@ -410,7 +418,8 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS
IScheduledTaskExecutor taskExecutor = taskExecutorFactory.CreateExecutor(scheduledJob.TaskType);
Result<Success> executePayloadResult = await taskExecutor.ExecutePayloadAsync(scheduledJob, cancellationToken).ConfigureAwait(false);
if (executePayloadResult.IsFailure)
_logger.LogWarning("The task of the scheduled job '{ScheduledJobName}' failed: {Error}", scheduledJob.Name, executePayloadResult.FirstError.Description);
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("The task of the scheduled job '{ScheduledJobName}' failed: {Error}", scheduledJob.Name, executePayloadResult.FirstError.Description);
}
catch (OperationCanceledException)
{
@@ -418,7 +427,8 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS
}
catch (Exception exception)
{
_logger.LogError(exception, "The task of the scheduled job '{ScheduledJobName}' threw an exception.", scheduledJob.Name);
if (_logger.IsEnabled(LogLevel.Error))
_logger.LogError(exception, "The task of the scheduled job '{ScheduledJobName}' threw an exception.", scheduledJob.Name);
}
if (cancellationToken.IsCancellationRequested)
@@ -461,7 +471,8 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS
catch (Exception exception)
{
// The completion failed after the execution was persisted as running, so the interrupted run is reconciled directly.
_logger.LogError(exception, "Failed to complete the execution of the scheduled job '{ScheduledJobId}'.", scheduledJob.Id.Value);
if (_logger.IsEnabled(LogLevel.Error))
_logger.LogError(exception, "Failed to complete the execution of the scheduled job '{ScheduledJobId}'.", scheduledJob.Id.Value);
await ReconcileInterruptedRunAsync(scheduledJob.Id, CancellationToken.None).ConfigureAwait(false);
}
}
@@ -513,7 +524,8 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS
Result<Success> saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
if (saveChangesResult.IsFailure)
throw new InvalidOperationException(saveChangesResult.FirstError.Description);
_logger.LogInformation("The interrupted execution of the scheduled job '{ScheduledJobName}' was closed.", scheduledJob.Name);
if (_logger.IsEnabled(LogLevel.Information))
_logger.LogInformation("The interrupted execution of the scheduled job '{ScheduledJobName}' was closed.", scheduledJob.Name);
return reconciledStatus;
}
catch (OperationCanceledException)
@@ -522,7 +534,8 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS
}
catch (Exception exception)
{
_logger.LogWarning(exception, "Failed to reconcile the interrupted execution of the scheduled job '{ScheduledJobId}'.", scheduledJobId.Value);
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning(exception, "Failed to reconcile the interrupted execution of the scheduled job '{ScheduledJobId}'.", scheduledJobId.Value);
return ScheduledJobStatus.Added;
}
}
@@ -46,7 +46,8 @@ public class CleanScheduledJobExecutionHistoryTaskExecutor : IScheduledTaskExecu
if (deleteResult.IsFailure)
return deleteResult.Errors;
_logger.LogInformation("Cleaned the execution history of the scheduled jobs on behalf of the scheduled job '{ScheduledJobName}'.", scheduledJob.Name);
if (_logger.IsEnabled(LogLevel.Information))
_logger.LogInformation("Cleaned the execution history of the scheduled jobs on behalf of the scheduled job '{ScheduledJobName}'.", scheduledJob.Name);
return Result.Success;
}
}
@@ -106,7 +106,8 @@ public class MediaLibraryScanTaskExecutor : IScheduledTaskExecutor
foreach (IDomainEvent domainEvent in domainEvents)
await _domainEventPublisher.PublishAsync(domainEvent, cancellationToken).ConfigureAwait(false);
_logger.LogInformation("Scanned all enabled media libraries on behalf of the scheduled job '{ScheduledJobName}'.", scheduledJob.Name);
if (_logger.IsEnabled(LogLevel.Information))
_logger.LogInformation("Scanned all enabled media libraries on behalf of the scheduled job '{ScheduledJobName}'.", scheduledJob.Name);
return Result.Success;
}
}
@@ -46,7 +46,8 @@ public class RepairThemesTaskExecutor : IScheduledTaskExecutor
try
{
await ThemeSynchronizer.SynchronizeAsync(_themeService, _unitOfWork, _logger, cancellationToken).ConfigureAwait(false);
_logger.LogInformation("Repaired the themes on behalf of the scheduled job '{ScheduledJobName}'.", scheduledJob.Name);
if (_logger.IsEnabled(LogLevel.Information))
_logger.LogInformation("Repaired the themes on behalf of the scheduled job '{ScheduledJobName}'.", scheduledJob.Name);
return Result.Success;
}
catch (OperationCanceledException)
@@ -55,7 +56,8 @@ public class RepairThemesTaskExecutor : IScheduledTaskExecutor
}
catch (Exception exception)
{
_logger.LogWarning(exception, "The themes could not be repaired on behalf of the scheduled job '{ScheduledJobName}'.", scheduledJob.Name);
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning(exception, "The themes could not be repaired on behalf of the scheduled job '{ScheduledJobName}'.", scheduledJob.Name);
return Error.Failure(description: nameof(RepairThemesTaskExecutor));
}
}
@@ -40,7 +40,8 @@ public class TechnicalDataCleanupTaskExecutor : IScheduledTaskExecutor
if (failInterruptedScansResult.IsFailure)
return failInterruptedScansResult.Errors;
_logger.LogInformation("Cleaned the technical data on behalf of the scheduled job '{ScheduledJobName}'.", scheduledJob.Name);
if (_logger.IsEnabled(LogLevel.Information))
_logger.LogInformation("Cleaned the technical data on behalf of the scheduled job '{ScheduledJobName}'.", scheduledJob.Name);
return Result.Success;
}
}
@@ -45,7 +45,8 @@ public class TemporaryFilesCleanupTaskExecutor : IScheduledTaskExecutor
!temporaryDirectoryRoot.StartsWith(applicationBaseDirectory, comparison) ||
string.Equals(temporaryDirectoryRoot, applicationBaseDirectory, comparison))
{
_logger.LogWarning("The temporary directory to clean could not be resolved safely, so the scheduled job '{ScheduledJobName}' was skipped.", scheduledJob.Name);
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("The temporary directory to clean could not be resolved safely, so the scheduled job '{ScheduledJobName}' was skipped.", scheduledJob.Name);
return Result.Success;
}
@@ -54,12 +55,14 @@ public class TemporaryFilesCleanupTaskExecutor : IScheduledTaskExecutor
if (Directory.Exists(temporaryDirectoryRoot))
Directory.Delete(temporaryDirectoryRoot, recursive: true);
Directory.CreateDirectory(temporaryDirectoryRoot);
_logger.LogInformation("Emptied the temporary directory '{TemporaryDirectory}'.", temporaryDirectoryRoot);
if (_logger.IsEnabled(LogLevel.Information))
_logger.LogInformation("Emptied the temporary directory '{TemporaryDirectory}'.", temporaryDirectoryRoot);
return Result.Success;
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException)
{
_logger.LogWarning(exception, "The temporary directory '{TemporaryDirectory}' could not be emptied.", temporaryDirectoryRoot);
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning(exception, "The temporary directory '{TemporaryDirectory}' could not be emptied.", temporaryDirectoryRoot);
return await Task.FromResult(Error.Failure(description: nameof(TemporaryFilesCleanupTaskExecutor)));
}
}
@@ -832,7 +832,8 @@ public sealed class ThemeService : IThemeService
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException)
{
_logger.LogDebug(exception, "Could not remove stale theme staging path {StagingPath}.", path);
if (_logger.IsEnabled(LogLevel.Debug))
_logger.LogDebug(exception, "Could not remove stale theme staging path {StagingPath}.", path);
}
}
}
@@ -35,7 +35,8 @@ internal static class ThemeSynchronizer
Result<PaginatedResultDto<ThemeEntity>> getThemesResult = await unitOfWork.ThemeRepository.GetAllAsync<BaseFilterDto>(cancellationToken: cancellationToken).ConfigureAwait(false);
if (getThemesResult.IsFailure)
{
logger.LogWarning("Failed to read the installed themes: {Error}", getThemesResult.FirstError.Description);
if (logger.IsEnabled(LogLevel.Warning))
logger.LogWarning("Failed to read the installed themes: {Error}", getThemesResult.FirstError.Description);
return;
}
@@ -47,7 +48,8 @@ internal static class ThemeSynchronizer
Result<ThemeManifestDto> manifestResult = await themeService.ReadManifestFromArchiveAsync(archivePath, cancellationToken).ConfigureAwait(false);
if (manifestResult.IsFailure)
{
logger.LogWarning("Skipping bundled theme archive {ArchivePath}: {Error}", archivePath, manifestResult.FirstError.Description);
if (logger.IsEnabled(LogLevel.Warning))
logger.LogWarning("Skipping bundled theme archive {ArchivePath}: {Error}", archivePath, manifestResult.FirstError.Description);
continue;
}
@@ -74,7 +76,8 @@ internal static class ThemeSynchronizer
Result<ThemeManifestDto> installResult = await themeService.InstallAsync(archive, cancellationToken).ConfigureAwait(false);
if (installResult.IsFailure)
{
logger.LogWarning("Failed to install bundled theme '{ThemeId}': {Error}", manifestResult.Value.Id, installResult.FirstError.Description);
if (logger.IsEnabled(LogLevel.Warning))
logger.LogWarning("Failed to install bundled theme '{ThemeId}': {Error}", manifestResult.Value.Id, installResult.FirstError.Description);
continue;
}
@@ -86,7 +89,8 @@ internal static class ThemeSynchronizer
existingTheme.Version = manifestResult.Value.Version;
Result<Updated> updateResult = await unitOfWork.ThemeRepository.UpdateAsync(existingTheme, cancellationToken).ConfigureAwait(false);
if (updateResult.IsFailure)
logger.LogWarning("Failed to update the version of theme '{ThemeId}': {Error}", existingTheme.ThemeId, updateResult.FirstError.Description);
if (logger.IsEnabled(LogLevel.Warning))
logger.LogWarning("Failed to update the version of theme '{ThemeId}': {Error}", existingTheme.ThemeId, updateResult.FirstError.Description);
}
continue;
}
@@ -105,18 +109,20 @@ internal static class ThemeSynchronizer
};
Result<Created> insertResult = await unitOfWork.ThemeRepository.InsertAsync(themeEntity, cancellationToken).ConfigureAwait(false);
if (insertResult.IsFailure)
logger.LogWarning("Failed to persist the detection of theme '{ThemeId}': {Error}", manifestResult.Value.Id, insertResult.FirstError.Description);
else
if (insertResult.IsSuccess)
themes.Add(themeEntity);
else if (logger.IsEnabled(LogLevel.Warning))
logger.LogWarning("Failed to persist the detection of theme '{ThemeId}': {Error}", manifestResult.Value.Id, insertResult.FirstError.Description);
}
catch (IOException exception)
{
logger.LogWarning(exception, "Failed to install bundled theme '{ThemeId}': the theme files could not be written.", manifestResult.Value.Id);
if (logger.IsEnabled(LogLevel.Warning))
logger.LogWarning(exception, "Failed to install bundled theme '{ThemeId}': the theme files could not be written.", manifestResult.Value.Id);
}
catch (UnauthorizedAccessException exception)
{
logger.LogWarning(exception, "Failed to install bundled theme '{ThemeId}': access to the theme files was denied.", manifestResult.Value.Id);
if (logger.IsEnabled(LogLevel.Warning))
logger.LogWarning(exception, "Failed to install bundled theme '{ThemeId}': access to the theme files was denied.", manifestResult.Value.Id);
}
}
@@ -155,14 +161,16 @@ internal static class ThemeSynchronizer
if (restoreResult.IsSuccess)
continue;
logger.LogWarning("Failed to restore the files of bundled theme '{ThemeId}': {Error}", brokenTheme.ThemeId, restoreResult.FirstError.Description);
if (logger.IsEnabled(LogLevel.Warning))
logger.LogWarning("Failed to restore the files of bundled theme '{ThemeId}': {Error}", brokenTheme.ThemeId, restoreResult.FirstError.Description);
// At least one bundled theme must always remain available, so the application never ends up without any theme;
// the last remaining bundled theme is kept even when its files cannot be recovered.
int availableBundledThemes = themes.Count(availableTheme => !availableTheme.IsDeleted && availableTheme.InstallSource == ThemeInstallSource.Bundled);
if (availableBundledThemes <= 1)
{
logger.LogWarning("Bundled theme '{ThemeId}' is the last remaining bundled theme and its files could not be restored, so it is kept.", brokenTheme.ThemeId);
if (logger.IsEnabled(LogLevel.Warning))
logger.LogWarning("Bundled theme '{ThemeId}' is the last remaining bundled theme and its files could not be restored, so it is kept.", brokenTheme.ThemeId);
continue;
}
@@ -171,16 +179,19 @@ internal static class ThemeSynchronizer
brokenTheme.IsCurrent = null;
Result<Updated> updateResult = await unitOfWork.ThemeRepository.UpdateAsync(brokenTheme, cancellationToken).ConfigureAwait(false);
if (updateResult.IsFailure)
logger.LogWarning("Failed to delete theme '{ThemeId}': {Error}", brokenTheme.ThemeId, updateResult.FirstError.Description);
if (logger.IsEnabled(LogLevel.Warning))
logger.LogWarning("Failed to delete theme '{ThemeId}': {Error}", brokenTheme.ThemeId, updateResult.FirstError.Description);
}
else
{
// A user theme has no shipped archive to restore from, so damage is permanent and the theme is removed entirely.
logger.LogWarning("The stored files of user theme '{ThemeId}' are missing, so the theme is deleted.", brokenTheme.ThemeId);
if (logger.IsEnabled(LogLevel.Warning))
logger.LogWarning("The stored files of user theme '{ThemeId}' are missing, so the theme is deleted.", brokenTheme.ThemeId);
brokenTheme.IsCurrent = null;
Result<Deleted> deleteResult = await unitOfWork.ThemeRepository.DeleteByIdAsync(brokenTheme.Id, cancellationToken).ConfigureAwait(false);
if (deleteResult.IsFailure)
logger.LogWarning("Failed to delete theme '{ThemeId}': {Error}", brokenTheme.ThemeId, deleteResult.FirstError.Description);
if (logger.IsEnabled(LogLevel.Warning))
logger.LogWarning("Failed to delete theme '{ThemeId}': {Error}", brokenTheme.ThemeId, deleteResult.FirstError.Description);
}
}
catch (OperationCanceledException)
@@ -190,7 +201,8 @@ internal static class ThemeSynchronizer
catch (Exception exception)
{
// Repairing a broken theme is best effort: an unexpected failure on one theme must not crash the host, so it is logged and the remaining broken themes are still processed.
logger.LogWarning(exception, "Failed to repair the broken theme '{ThemeId}'.", brokenTheme.ThemeId);
if (logger.IsEnabled(LogLevel.Warning))
logger.LogWarning(exception, "Failed to repair the broken theme '{ThemeId}'.", brokenTheme.ThemeId);
}
}
}
@@ -222,6 +234,7 @@ internal static class ThemeSynchronizer
defaultTheme.IsCurrent = true;
Result<Updated> updateResult = await unitOfWork.ThemeRepository.UpdateAsync(defaultTheme, cancellationToken).ConfigureAwait(false);
if (updateResult.IsFailure)
logger.LogWarning("Failed to activate theme '{ThemeId}': {Error}", defaultTheme.ThemeId, updateResult.FirstError.Description);
if (logger.IsEnabled(LogLevel.Warning))
logger.LogWarning("Failed to activate theme '{ThemeId}': {Error}", defaultTheme.ThemeId, updateResult.FirstError.Description);
}
}
@@ -76,11 +76,12 @@ public static class PresentationApiLayerServices
.FirstOrDefault()?.Split(',')[0].Trim()
?? onRejectedContext.HttpContext.Connection.RemoteIpAddress?.ToString()
?? "unknown";
logger.LogWarning(
"Rate limit exceeded. IP: {IpAddress}, Route: {Route}, Lease Acquired: {IsAcquired}",
clientIp,
onRejectedContext.HttpContext.Request.Path,
onRejectedContext.Lease.IsAcquired); // When False, the request was rejected because it exceeded rate limits.
if (logger.IsEnabled(LogLevel.Warning))
logger.LogWarning(
"Rate limit exceeded. IP: {IpAddress}, Route: {Route}, Lease Acquired: {IsAcquired}",
clientIp,
onRejectedContext.HttpContext.Request.Path,
onRejectedContext.Lease.IsAcquired); // When False, the request was rejected because it exceeded rate limits.
onRejectedContext.HttpContext.Response.StatusCode = StatusCodes.Status429TooManyRequests;
onRejectedContext.HttpContext.Response.ContentType = "application/problem+json";
@@ -80,7 +80,8 @@ public class EventualConsistencyMiddleware
}
catch (Exception ex) // The response is already complete, so this failure cannot reach the client. It is logged, and the transaction is still closed by the rollback below.
{
_logger.LogError(ex, "Failed to complete the request transaction for {Path}", context.Request.Path);
if (_logger.IsEnabled(LogLevel.Error))
_logger.LogError(ex, "Failed to complete the request transaction for {Path}", context.Request.Path);
}
finally
{
@@ -93,7 +94,8 @@ public class EventualConsistencyMiddleware
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to roll back the request transaction for {Path}", context.Request.Path);
if (_logger.IsEnabled(LogLevel.Error))
_logger.LogError(ex, "Failed to roll back the request transaction for {Path}", context.Request.Path);
}
}
});
@@ -53,7 +53,8 @@ public class ExceptionHandlingMiddleware
// Once the response has started, it is no longer possible to replace it with a ProblemDetails response.
if (context.Response.HasStarted)
throw;
_logger.LogError(ex, "Unhandled exception occurred while processing request {Method} {Path}", context.Request.Method, context.Request.Path);
if (_logger.IsEnabled(LogLevel.Error))
_logger.LogError(ex, "Unhandled exception occurred while processing request {Method} {Path}", context.Request.Method, context.Request.Path);
await WriteProblemDetailsResponseAsync(context).ConfigureAwait(false);
}
}
@@ -63,7 +63,8 @@ public class ExceptionHandlingMiddleware
}
catch (Exception ex) // Other cases.
{
_logger.LogError(ex, "Unexpected exception occurred: {Message}", ex.Message);
if (_logger.IsEnabled(LogLevel.Error))
_logger.LogError(ex, "Unexpected exception occurred: {Message}", ex.Message);
// Once the response has started, its status and headers are already on the wire, so they can no longer be replaced: the connection
// is aborted instead, so that the client sees a failed transfer rather than a success response it cannot trust.
if (context.Response.HasStarted)
@@ -105,13 +106,14 @@ public class ExceptionHandlingMiddleware
private async Task HandleApiExceptionAsync(HttpContext context, ApiException apiException)
{
// Log all available details for debugging/monitoring.
_logger.LogError(
apiException,
"API Exception occurred. Status: {StatusCode}, Title: {Title}, Detail: {Detail}, Extensions: {Extensions}",
apiException.HttpStatusCode,
apiException.ProblemDetails?.Title,
apiException.ProblemDetails?.Detail,
apiException.ProblemDetails?.Extensions);
if (_logger.IsEnabled(LogLevel.Error))
_logger.LogError(
apiException,
"API Exception occurred. Status: {StatusCode}, Title: {Title}, Detail: {Detail}, Extensions: {Extensions}",
apiException.HttpStatusCode,
apiException.ProblemDetails?.Title,
apiException.ProblemDetails?.Detail,
apiException.ProblemDetails?.Extensions);
// Once the response has started, its status and headers are already on the wire, so they can no longer be replaced: the connection
// is aborted instead, so that the client sees a failed transfer rather than a redirect it could not follow or a body it would misread.
@@ -284,7 +286,8 @@ public class ExceptionHandlingMiddleware
string culture = context.Request.RouteValues["culture"]?.ToString()?.ToLower() ?? "en-us";
string returnUrl = $"{context.Request.Path}{context.Request.QueryString}";
string loginUrl = $"/{culture}/auth/login?returnUrl={Uri.EscapeDataString(returnUrl)}";
_logger.LogInformation("Redirecting unauthorized user to {Url}", loginUrl);
if (_logger.IsEnabled(LogLevel.Information))
_logger.LogInformation("Redirecting unauthorized user to {Url}", loginUrl);
context.Response.Redirect(loginUrl); // Force an entire refresh of the current location, so that header and footer are re-rendered too.
}
else
@@ -310,7 +313,8 @@ public class ExceptionHandlingMiddleware
if (errorsObj.ValueKind == JsonValueKind.Object)
foreach (JsonProperty error in errorsObj.EnumerateObject())
{
_logger.LogError("Validation error {Field}: {@ErrorValues}", error.Name, error.Value.EnumerateArray().Select(jsonElement => jsonElement.ToString()));
if (_logger.IsEnabled(LogLevel.Error))
_logger.LogError("Validation error {Field}: {@ErrorValues}", error.Name, error.Value.EnumerateArray().Select(jsonElement => jsonElement.ToString()));
if (error.Value.ValueKind == JsonValueKind.Array)
foreach (JsonElement errorValue in error.Value.EnumerateArray())
errorMessage.AppendLine($"{_stringLocalizer[errorValue.ToString()]}<br>");
@@ -43,6 +43,7 @@ public class TranscodingStartupInitializerTests : IDisposable
_settings = _transcodingSettingsDtoFixture.Create(ffmpegPath: missingFfmpegPath, cacheDirectory: _cacheDirectory);
_toolchainStatus = new TranscodingToolchainStatus();
_mockLogger = Substitute.For<ILogger<TranscodingStartupInitializer>>();
_mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(true);
_sut = new TranscodingStartupInitializer(Options.Create(_settings), _toolchainStatus, _mockLogger);
}
@@ -102,6 +103,28 @@ public class TranscodingStartupInitializerTests : IDisposable
Arg.Any<Func<object, Exception?, string>>());
}
[Fact]
public async Task StartAsync_WhenLoggingIsDisabledAndTheDirectoryExistsNonEmptyWithoutTheMarker_ShouldNotLogAnError()
{
// Arrange
_mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(false);
Directory.CreateDirectory(_cacheDirectory);
File.WriteAllText(Path.Combine(_cacheDirectory, "operator-data.txt"), "operator data");
// Act
await _sut.StartAsync(CancellationToken.None);
// Assert
Assert.False(TranscodingCachePaths.HasCacheMarker(_cacheDirectory));
Assert.False(_toolchainStatus.IsTranscoderAvailable);
_mockLogger.DidNotReceive().Log(
LogLevel.Error,
Arg.Any<EventId>(),
Arg.Any<object>(),
Arg.Any<Exception?>(),
Arg.Any<Func<object, Exception?, string>>());
}
[Fact]
public async Task StartAsync_WhenTheDirectoryIsMarked_ShouldRemoveOnlyTheEntriesOfTheCacheNamespace()
{
@@ -15,6 +15,7 @@ using Microsoft.Extensions.Logging;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
@@ -106,6 +107,7 @@ public class BooksMediaLibraryItemDeletionStrategyTests
public async Task DeleteItemAsync_WhenDeleteArtworkFails_ShouldStillDeleteTheBook()
{
// Arrange
_mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(true);
LibraryId libraryId = _libraryIdFixture.Create();
BookEntity book = _bookEntityFixture.Create(path: "/books/deleted.epub");
LibraryEntity library = _libraryEntityFixture.Create(id: libraryId.Value, title: "My Library");
@@ -129,6 +131,12 @@ public class BooksMediaLibraryItemDeletionStrategyTests
Assert.True(result.IsSuccess);
await _mockBookRepository.Received(1).DeleteByIdAsync(book.Id, Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
_mockLogger.Received(1).Log(
LogLevel.Warning,
Arg.Any<EventId>(),
Arg.Is<object>(state => state.ToString()!.Contains("Failed to delete the stored artwork of the book")),
Arg.Any<Exception?>(),
Arg.Any<Func<object, Exception?, string>>());
}
[Fact]
@@ -52,6 +52,7 @@ public class MusicMediaLibraryItemDeletionStrategyTests
_mockMusicArtworkRepository = Substitute.For<IMusicArtworkRepository>();
_mockMusicArtworkService = Substitute.For<IMusicArtworkService>();
_mockLogger = Substitute.For<ILogger<MusicMediaLibraryItemDeletionStrategy>>();
_mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(true);
_mockUnitOfWork.TrackRepository.Returns(_mockTrackRepository);
_mockUnitOfWork.AlbumRepository.Returns(_mockAlbumRepository);
_mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository);
@@ -293,6 +294,54 @@ public class MusicMediaLibraryItemDeletionStrategyTests
Arg.Any<Func<object, Exception?, string>>());
}
[Fact]
public async Task DeleteItemAsync_WhenLoggingIsDisabledAndDeletingAStoredArtworkFileFails_ShouldNotLogAWarningButStillDeleteTheRow()
{
// Arrange
_mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(false);
LibraryId libraryId = _libraryIdFixture.Create();
Guid albumId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
TrackEntity track = _trackEntityFixture.Create(albumId: albumId, path: "/music/deleted.flac");
AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, includeTracks: false);
AlbumEntity otherAlbum = _albumEntityFixture.Create(artistId: artistId, includeTracks: false);
MusicArtworkEntity trackArtwork = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Track, ownerId: track.Id, fileName: "/media/music/track-cover.jpg");
_mockTrackRepository.GetByPathAsync(libraryId.Value, track.Path, Arg.Any<CancellationToken>())
.Returns(Result.From<TrackEntity?>(track));
_mockMusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Track, track.Id, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MusicArtworkEntity>>([trackArtwork]));
_mockMusicArtworkService.DeleteStoredArtwork(trackArtwork.FileName!)
.Returns(Errors.FileSystemManagement.FileNotFound);
_mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Track, track.Id, Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
_mockTrackRepository.DeleteByIdAsync(track.Id, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Deleted));
_mockAlbumRepository.GetIncludingDeletedByIdAsync(albumId, Arg.Any<CancellationToken>())
.Returns(Result.From<AlbumEntity?>(album));
_mockTrackRepository.GetByAlbumIdIncludingDeletedAsync(albumId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<TrackEntity>>([track]));
_mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
_mockAlbumRepository.DeleteByIdAsync(albumId, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Deleted));
_mockAlbumRepository.GetByArtistIdIncludingDeletedAsync(artistId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<AlbumEntity>>([otherAlbum]));
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
// Act
Result<Success> result = await _sut.DeleteItemAsync(libraryId.Value, track.Path, CancellationToken.None);
// Assert
Assert.True(result.IsSuccess);
await _mockMusicArtworkRepository.Received(1).DeleteByOwnerAsync(MusicArtworkOwnerType.Track, track.Id, Arg.Any<CancellationToken>());
_mockLogger.DidNotReceive().Log(
LogLevel.Warning,
Arg.Any<EventId>(),
Arg.Any<object>(),
Arg.Any<Exception?>(),
Arg.Any<Func<object, Exception?, string>>());
}
[Fact]
public async Task DeleteItemAsync_WhenAlbumWasAlreadyRemoved_ShouldPersistTheTrackDeletion()
{
@@ -113,6 +113,7 @@ public class PublicHostValidationHandlerTests
{
// Arrange
ILogger<PublicHostValidationHandler> mockLogger = Substitute.For<ILogger<PublicHostValidationHandler>>();
mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(true);
StubHttpMessageHandler innerHandler = new();
PublicHostValidationHandler handler = new(CreateValidator(), mockLogger) { InnerHandler = innerHandler };
using HttpClient client = new(handler);
@@ -23,6 +23,7 @@ using Microsoft.Extensions.Logging;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
@@ -120,6 +121,7 @@ public class PluginDetectionSyncJobTests
public async Task StartAsync_WhenUpsertFails_ShouldLogErrorAndContinueWithOtherPlugins()
{
// Arrange
_mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(true);
IPlugin failingPlugin = CreatePlugin(Guid.NewGuid(), "Failing Plugin", new Version(1, 0, 0));
IPlugin successfulPlugin = CreatePlugin(Guid.NewGuid(), "Successful Plugin", new Version(1, 0, 0));
_mockPluginManager.GetPlugins().Returns([failingPlugin, successfulPlugin]);
@@ -139,6 +141,12 @@ public class PluginDetectionSyncJobTests
// Assert
await _mockPluginRepository.Received(1).UpsertAsync(Arg.Is<PluginEntity>(plugin => plugin.Id == successfulPlugin.Id), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
_mockLogger.Received(1).Log(
LogLevel.Error,
Arg.Any<EventId>(),
Arg.Is<object>(state => state.ToString()!.Contains("Failed to persist the detection of plugin")),
Arg.Any<Exception?>(),
Arg.Any<Func<object, Exception?, string>>());
}
[Fact]
@@ -9,6 +9,7 @@ using Microsoft.Extensions.Logging;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
using System.Threading;
@@ -96,6 +97,7 @@ public class PluginSettingsStoreTests
public async Task GetSettingsAsync_WhenRepositoryReturnsFailure_ShouldReturnNullAndLogWarning()
{
// Arrange
_mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(true);
Guid pluginId = Guid.NewGuid();
_mockPluginRepository.GetByIdAsync(pluginId, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Error.Failure("Database.Error", "Failed to retrieve the plugin"));
@@ -105,5 +107,11 @@ public class PluginSettingsStoreTests
// Assert
Assert.Null(result);
_mockLogger.Received(1).Log(
LogLevel.Warning,
Arg.Any<EventId>(),
Arg.Is<object>(state => state.ToString()!.Contains("Failed to read the settings of the plugin")),
Arg.Any<Exception?>(),
Arg.Any<Func<object, Exception?, string>>());
}
}
@@ -25,6 +25,7 @@ using Microsoft.Extensions.Logging;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
@@ -49,6 +50,7 @@ public class ScheduledJobSchedulerJobTests
private readonly IDomainEventPublisher _mockDomainEventPublisher;
private readonly IScheduledTaskExecutorFactory _mockTaskExecutorFactory;
private readonly IScheduledTaskExecutor _mockTaskExecutor;
private readonly ILogger<ScheduledJobSchedulerJob> _mockLogger;
private readonly ScheduledJobRuntimeRegistry _runtimeRegistry;
private readonly ScheduledJobSchedulerJob _sut;
private readonly Dictionary<Type, object> _services;
@@ -95,8 +97,8 @@ public class ScheduledJobSchedulerJobTests
.Returns(callInfo => _services.TryGetValue((Type)callInfo[0]!, out object? service) ? service : null);
_runtimeRegistry = new ScheduledJobRuntimeRegistry();
ILogger<ScheduledJobSchedulerJob> logger = Substitute.For<ILogger<ScheduledJobSchedulerJob>>();
_sut = new ScheduledJobSchedulerJob(_runtimeRegistry, logger, _mockServiceScopeFactory);
_mockLogger = Substitute.For<ILogger<ScheduledJobSchedulerJob>>();
_sut = new ScheduledJobSchedulerJob(_runtimeRegistry, _mockLogger, _mockServiceScopeFactory);
}
[Fact]
@@ -555,6 +557,7 @@ public class ScheduledJobSchedulerJobTests
public async Task ExecuteScheduledJobRunAsync_WhenTheTaskPayloadFails_ShouldLogTheFailureAndStillCompleteTheExecution()
{
// Arrange
_mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(true);
ScheduledJobEntity addedJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Added, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60);
ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(addedJob.Id);
_mockScheduledJobRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>()).Returns(addedJob);
@@ -568,12 +571,19 @@ public class ScheduledJobSchedulerJobTests
// Assert
await _mockTaskExecutor.Received(1).ExecutePayloadAsync(Arg.Any<ScheduledJob>(), Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<ScheduledJobExecutionCompletedDomainEvent>(domainEvent => !domainEvent.IsCycleRun), Arg.Any<CancellationToken>());
_mockLogger.Received(1).Log(
LogLevel.Warning,
Arg.Any<EventId>(),
Arg.Is<object>(state => state.ToString()!.Contains("failed:")),
Arg.Any<Exception?>(),
Arg.Any<Func<object, Exception?, string>>());
}
[Fact]
public async Task ExecuteScheduledJobRunAsync_WhenTheTaskPayloadThrows_ShouldLogTheExceptionAndStillCompleteTheExecution()
{
// Arrange
_mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(true);
ScheduledJobEntity addedJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Added, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60);
ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(addedJob.Id);
_mockScheduledJobRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>()).Returns(addedJob);
@@ -586,6 +596,12 @@ public class ScheduledJobSchedulerJobTests
// Assert
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<ScheduledJobExecutionCompletedDomainEvent>(domainEvent => !domainEvent.IsCycleRun), Arg.Any<CancellationToken>());
_mockLogger.Received(1).Log(
LogLevel.Error,
Arg.Any<EventId>(),
Arg.Any<object>(),
Arg.Is<Exception>(exception => exception is InvalidOperationException && exception.Message == "The task threw."),
Arg.Any<Func<object, Exception?, string>>());
}
[Fact]
@@ -52,6 +52,7 @@ public class ThemeSynchronizerTests : IDisposable
_mockUnitOfWork.ThemeRepository.Returns(_mockThemeRepository);
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
_mockLogger = Substitute.For<ILogger>();
_mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(true);
_mockThemeService.GetBundledThemeArchivePaths().Returns([]);
_mockThemeService.HasThemePack(Arg.Any<string>()).Returns(true);
_mockThemeService.DefaultThemeId.Returns("lumina-default");
@@ -79,6 +80,28 @@ public class ThemeSynchronizerTests : IDisposable
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task SynchronizeAsync_WhenLoggingIsDisabledAndTheInstalledThemesCannotBeRead_ShouldNotLogAWarning()
{
// Arrange
_mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(false);
_mockThemeRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>())
.Returns(Error.Failure("Themes.NotFound", "Failed to read the installed themes"));
_mockThemeService.GetBundledThemeArchivePaths().Returns(["bundled.zip"]);
// Act
await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None);
// Assert
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
_mockLogger.DidNotReceive().Log(
LogLevel.Warning,
Arg.Any<EventId>(),
Arg.Any<object>(),
Arg.Any<Exception?>(),
Arg.Any<Func<object, Exception?, string>>());
}
[Fact]
public async Task SynchronizeAsync_WhenABundledArchiveManifestCannotBeRead_ShouldSkipThatArchive()
{
@@ -235,6 +258,12 @@ public class ThemeSynchronizerTests : IDisposable
// Assert
await _mockThemeRepository.Received(1).InsertAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
_mockLogger.Received(1).Log(
LogLevel.Warning,
Arg.Any<EventId>(),
Arg.Is<object>(state => state.ToString()!.Contains("Failed to persist the detection of theme")),
Arg.Any<Exception?>(),
Arg.Any<Func<object, Exception?, string>>());
}
[Fact]
@@ -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()
{
@@ -41,6 +41,7 @@ public class ExceptionHandlingMiddlewareTests
public ExceptionHandlingMiddlewareTests()
{
_mockLogger = Substitute.For<ILogger<ExceptionHandlingMiddleware>>();
_mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(true);
_mockStringLocalizer = Substitute.For<IStringLocalizer<ExceptionHandlingMiddleware>>();
_mockStringLocalizer[Arg.Any<string>()].Returns(callInfo => new LocalizedString(callInfo.Arg<string>(), $"localized:{callInfo.Arg<string>()}"));
_mockAuthenticationService = Substitute.For<IAuthenticationService>();
@@ -91,6 +92,27 @@ public class ExceptionHandlingMiddlewareTests
Arg.Any<Func<object, Exception?, string>>());
}
[Fact]
public async Task InvokeAsync_WhenLoggingIsDisabledAndNextThrowsNonApiExceptionAndApiRequest_ShouldNotLogError()
{
// Arrange
_mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(false);
DefaultHttpContext httpContext = CreateHttpContext(isApiRequest: true);
_nextDelegate = _ => throw new InvalidOperationException("Unexpected failure");
// Act
await _sut.InvokeAsync(httpContext);
// Assert
Assert.Contains("application/json", httpContext.Response.ContentType);
_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_WhenNextThrowsNonApiExceptionAndPageRequest_ShouldWriteHtmlErrorPage()
{