diff --git a/src/Lumina.Application/Common/Telemetry/ApplicationHandlerTelemetry.cs b/src/Lumina.Application/Common/Telemetry/ApplicationHandlerTelemetry.cs index 493723db..ebb98182 100644 --- a/src/Lumina.Application/Common/Telemetry/ApplicationHandlerTelemetry.cs +++ b/src/Lumina.Application/Common/Telemetry/ApplicationHandlerTelemetry.cs @@ -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); } /// @@ -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); } /// @@ -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); } /// diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Deletion/BooksMediaLibraryItemDeletionStrategy.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Deletion/BooksMediaLibraryItemDeletionStrategy.cs index 1bab3103..3939ef51 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Deletion/BooksMediaLibraryItemDeletionStrategy.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Deletion/BooksMediaLibraryItemDeletionStrategy.cs @@ -72,7 +72,8 @@ internal sealed class BooksMediaLibraryItemDeletionStrategy : IMediaLibraryItemD Result 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 deleteBookResult = await _unitOfWork.BookRepository.DeleteByIdAsync(book.Id, cancellationToken).ConfigureAwait(false); diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Deletion/MusicMediaLibraryItemDeletionStrategy.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Deletion/MusicMediaLibraryItemDeletionStrategy.cs index e17f790a..fbd00b4a 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Deletion/MusicMediaLibraryItemDeletionStrategy.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Deletion/MusicMediaLibraryItemDeletionStrategy.cs @@ -142,7 +142,8 @@ internal sealed class MusicMediaLibraryItemDeletionStrategy : IMediaLibraryItemD Result 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); diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryMediaItemDeletedDomainEventHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryMediaItemDeletedDomainEventHandler.cs index 8d63a811..713f5438 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryMediaItemDeletedDomainEventHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryMediaItemDeletedDomainEventHandler.cs @@ -61,7 +61,8 @@ public class LibraryMediaItemDeletedDomainEventHandler : IDomainEventHandler 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; } diff --git a/src/Lumina.Application/Core/Themes/Management/Queries/GetThemeTemplate/GetThemeTemplateQueryHandler.cs b/src/Lumina.Application/Core/Themes/Management/Queries/GetThemeTemplate/GetThemeTemplateQueryHandler.cs index 57402dfb..b956ca91 100644 --- a/src/Lumina.Application/Core/Themes/Management/Queries/GetThemeTemplate/GetThemeTemplateQueryHandler.cs +++ b/src/Lumina.Application/Core/Themes/Management/Queries/GetThemeTemplate/GetThemeTemplateQueryHandler.cs @@ -133,7 +133,8 @@ public class GetThemeTemplateQueryHandler : IQueryHandlerThe exception that reports the rejection. 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); } diff --git a/src/Lumina.Infrastructure/Common/Networking/PublicHostValidationHandler.cs b/src/Lumina.Infrastructure/Common/Networking/PublicHostValidationHandler.cs index bb19477d..65ce53bb 100644 --- a/src/Lumina.Infrastructure/Common/Networking/PublicHostValidationHandler.cs +++ b/src/Lumina.Infrastructure/Common/Networking/PublicHostValidationHandler.cs @@ -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); } diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TrackNormalizationService.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TrackNormalizationService.cs index a3d5a2ea..a25228de 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TrackNormalizationService.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TrackNormalizationService.cs @@ -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(); diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingStartupInitializer.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingStartupInitializer.cs index 93b69bc7..9410aa8a 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingStartupInitializer.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingStartupInitializer.cs @@ -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); } } diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicFileSystemDiscoveryJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicFileSystemDiscoveryJob.cs index e11b5076..c1516958 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicFileSystemDiscoveryJob.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicFileSystemDiscoveryJob.cs @@ -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); } }); } diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanArtworkEnricher.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanArtworkEnricher.cs index 468a7b6e..a1e31f62 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanArtworkEnricher.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanArtworkEnricher.cs @@ -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 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 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 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 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 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; } diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanMetadataEnricher.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanMetadataEnricher.cs index dbebb795..76472312 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanMetadataEnricher.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanMetadataEnricher.cs @@ -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); } } diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMetadataExtractionJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMetadataExtractionJob.cs index 209ce725..0c63dad7 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMetadataExtractionJob.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMetadataExtractionJob.cs @@ -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)) diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksFileSystemDiscoveryJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksFileSystemDiscoveryJob.cs index 09735d8c..263e7a58 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksFileSystemDiscoveryJob.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksFileSystemDiscoveryJob.cs @@ -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); } }); } diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksMediaLibraryScanArtworkEnricher.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksMediaLibraryScanArtworkEnricher.cs index c8f6587a..0bb01e3c 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksMediaLibraryScanArtworkEnricher.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksMediaLibraryScanArtworkEnricher.cs @@ -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); } diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksMediaLibraryScanMetadataEnricher.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksMediaLibraryScanMetadataEnricher.cs index d508ff8c..3ca8f89a 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksMediaLibraryScanMetadataEnricher.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksMediaLibraryScanMetadataEnricher.cs @@ -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); } diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Queue/MediaLibraryScanProcessorJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Queue/MediaLibraryScanProcessorJob.cs index e09f01d2..80886e2c 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Queue/MediaLibraryScanProcessorJob.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Queue/MediaLibraryScanProcessorJob.cs @@ -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 /// A task that represents the asynchronous operation. 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); } } diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/BookReadingService.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/BookReadingService.cs index cdfb5059..29c507a4 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/BookReadingService.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/BookReadingService.cs @@ -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."); } } diff --git a/src/Lumina.Infrastructure/Core/Plugins/PluginDetectionSyncJob.cs b/src/Lumina.Infrastructure/Core/Plugins/PluginDetectionSyncJob.cs index aaa968e6..96a4c43d 100644 --- a/src/Lumina.Infrastructure/Core/Plugins/PluginDetectionSyncJob.cs +++ b/src/Lumina.Infrastructure/Core/Plugins/PluginDetectionSyncJob.cs @@ -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(); @@ -78,7 +79,8 @@ internal sealed class PluginDetectionSyncJob : BackgroundService }; Result 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 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 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 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 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); } } diff --git a/src/Lumina.Infrastructure/Core/Plugins/PluginSettingsStore.cs b/src/Lumina.Infrastructure/Core/Plugins/PluginSettingsStore.cs index b4413224..1d43e4f8 100644 --- a/src/Lumina.Infrastructure/Core/Plugins/PluginSettingsStore.cs +++ b/src/Lumina.Infrastructure/Core/Plugins/PluginSettingsStore.cs @@ -44,7 +44,8 @@ internal sealed class PluginSettingsStore : IPluginSettingsStore Result 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; } diff --git a/src/Lumina.Infrastructure/Core/Scheduling/Execution/ScheduledJobSchedulerJob.cs b/src/Lumina.Infrastructure/Core/Scheduling/Execution/ScheduledJobSchedulerJob.cs index cc884da4..60d89e35 100644 --- a/src/Lumina.Infrastructure/Core/Scheduling/Execution/ScheduledJobSchedulerJob.cs +++ b/src/Lumina.Infrastructure/Core/Scheduling/Execution/ScheduledJobSchedulerJob.cs @@ -133,7 +133,8 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS Result> 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(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 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 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> 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 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 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; } } diff --git a/src/Lumina.Infrastructure/Core/Scheduling/Execution/TaskExecutors/CleanScheduledJobExecutionHistoryTaskExecutor.cs b/src/Lumina.Infrastructure/Core/Scheduling/Execution/TaskExecutors/CleanScheduledJobExecutionHistoryTaskExecutor.cs index b0aac116..7c53f702 100644 --- a/src/Lumina.Infrastructure/Core/Scheduling/Execution/TaskExecutors/CleanScheduledJobExecutionHistoryTaskExecutor.cs +++ b/src/Lumina.Infrastructure/Core/Scheduling/Execution/TaskExecutors/CleanScheduledJobExecutionHistoryTaskExecutor.cs @@ -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; } } diff --git a/src/Lumina.Infrastructure/Core/Scheduling/Execution/TaskExecutors/MediaLibraryScanTaskExecutor.cs b/src/Lumina.Infrastructure/Core/Scheduling/Execution/TaskExecutors/MediaLibraryScanTaskExecutor.cs index 5af50bcb..41462924 100644 --- a/src/Lumina.Infrastructure/Core/Scheduling/Execution/TaskExecutors/MediaLibraryScanTaskExecutor.cs +++ b/src/Lumina.Infrastructure/Core/Scheduling/Execution/TaskExecutors/MediaLibraryScanTaskExecutor.cs @@ -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; } } diff --git a/src/Lumina.Infrastructure/Core/Scheduling/Execution/TaskExecutors/RepairThemesTaskExecutor.cs b/src/Lumina.Infrastructure/Core/Scheduling/Execution/TaskExecutors/RepairThemesTaskExecutor.cs index b9bbf77e..1de227d1 100644 --- a/src/Lumina.Infrastructure/Core/Scheduling/Execution/TaskExecutors/RepairThemesTaskExecutor.cs +++ b/src/Lumina.Infrastructure/Core/Scheduling/Execution/TaskExecutors/RepairThemesTaskExecutor.cs @@ -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)); } } diff --git a/src/Lumina.Infrastructure/Core/Scheduling/Execution/TaskExecutors/TechnicalDataCleanupTaskExecutor.cs b/src/Lumina.Infrastructure/Core/Scheduling/Execution/TaskExecutors/TechnicalDataCleanupTaskExecutor.cs index 8a56b8c6..316bf8c2 100644 --- a/src/Lumina.Infrastructure/Core/Scheduling/Execution/TaskExecutors/TechnicalDataCleanupTaskExecutor.cs +++ b/src/Lumina.Infrastructure/Core/Scheduling/Execution/TaskExecutors/TechnicalDataCleanupTaskExecutor.cs @@ -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; } } diff --git a/src/Lumina.Infrastructure/Core/Scheduling/Execution/TaskExecutors/TemporaryFilesCleanupTaskExecutor.cs b/src/Lumina.Infrastructure/Core/Scheduling/Execution/TaskExecutors/TemporaryFilesCleanupTaskExecutor.cs index 8caabe91..ee537e3b 100644 --- a/src/Lumina.Infrastructure/Core/Scheduling/Execution/TaskExecutors/TemporaryFilesCleanupTaskExecutor.cs +++ b/src/Lumina.Infrastructure/Core/Scheduling/Execution/TaskExecutors/TemporaryFilesCleanupTaskExecutor.cs @@ -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))); } } diff --git a/src/Lumina.Infrastructure/Core/Themes/ThemeService.cs b/src/Lumina.Infrastructure/Core/Themes/ThemeService.cs index 976b3689..c886f8ca 100644 --- a/src/Lumina.Infrastructure/Core/Themes/ThemeService.cs +++ b/src/Lumina.Infrastructure/Core/Themes/ThemeService.cs @@ -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); } } } diff --git a/src/Lumina.Infrastructure/Core/Themes/ThemeSynchronizer.cs b/src/Lumina.Infrastructure/Core/Themes/ThemeSynchronizer.cs index 4f5a886f..717310ac 100644 --- a/src/Lumina.Infrastructure/Core/Themes/ThemeSynchronizer.cs +++ b/src/Lumina.Infrastructure/Core/Themes/ThemeSynchronizer.cs @@ -35,7 +35,8 @@ internal static class ThemeSynchronizer Result> getThemesResult = await unitOfWork.ThemeRepository.GetAllAsync(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 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 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 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 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 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 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 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); } } diff --git a/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs b/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs index f8587ae3..d40763d9 100644 --- a/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs +++ b/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs @@ -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"; diff --git a/src/Lumina.Presentation.Api/Common/Middlewares/EventualConsistencyMiddleware.cs b/src/Lumina.Presentation.Api/Common/Middlewares/EventualConsistencyMiddleware.cs index 9d04b5a3..dae01871 100644 --- a/src/Lumina.Presentation.Api/Common/Middlewares/EventualConsistencyMiddleware.cs +++ b/src/Lumina.Presentation.Api/Common/Middlewares/EventualConsistencyMiddleware.cs @@ -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); } } }); diff --git a/src/Lumina.Presentation.Api/Common/Middlewares/ExceptionHandlingMiddleware.cs b/src/Lumina.Presentation.Api/Common/Middlewares/ExceptionHandlingMiddleware.cs index ea25fb14..1bb225bf 100644 --- a/src/Lumina.Presentation.Api/Common/Middlewares/ExceptionHandlingMiddleware.cs +++ b/src/Lumina.Presentation.Api/Common/Middlewares/ExceptionHandlingMiddleware.cs @@ -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); } } diff --git a/src/Lumina.Presentation.Web/Common/Middlewares/ExceptionHandlingMiddleware.cs b/src/Lumina.Presentation.Web/Common/Middlewares/ExceptionHandlingMiddleware.cs index 9ffee6e2..0b55a4e6 100644 --- a/src/Lumina.Presentation.Web/Common/Middlewares/ExceptionHandlingMiddleware.cs +++ b/src/Lumina.Presentation.Web/Common/Middlewares/ExceptionHandlingMiddleware.cs @@ -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()]}
"); diff --git a/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingStartupInitializerTests.cs b/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingStartupInitializerTests.cs index 1e89b336..7707c7b4 100644 --- a/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingStartupInitializerTests.cs +++ b/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingStartupInitializerTests.cs @@ -43,6 +43,7 @@ public class TranscodingStartupInitializerTests : IDisposable _settings = _transcodingSettingsDtoFixture.Create(ffmpegPath: missingFfmpegPath, cacheDirectory: _cacheDirectory); _toolchainStatus = new TranscodingToolchainStatus(); _mockLogger = Substitute.For>(); + _mockLogger.IsEnabled(Arg.Any()).Returns(true); _sut = new TranscodingStartupInitializer(Options.Create(_settings), _toolchainStatus, _mockLogger); } @@ -102,6 +103,28 @@ public class TranscodingStartupInitializerTests : IDisposable Arg.Any>()); } + [Fact] + public async Task StartAsync_WhenLoggingIsDisabledAndTheDirectoryExistsNonEmptyWithoutTheMarker_ShouldNotLogAnError() + { + // Arrange + _mockLogger.IsEnabled(Arg.Any()).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(), + Arg.Any(), + Arg.Any(), + Arg.Any>()); + } + [Fact] public async Task StartAsync_WhenTheDirectoryIsMarked_ShouldRemoveOnlyTheEntriesOfTheCacheNamespace() { diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Deletion/BooksMediaLibraryItemDeletionStrategyTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Deletion/BooksMediaLibraryItemDeletionStrategyTests.cs index f57a3dd1..919ec930 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Deletion/BooksMediaLibraryItemDeletionStrategyTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Deletion/BooksMediaLibraryItemDeletionStrategyTests.cs @@ -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()).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()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + _mockLogger.Received(1).Log( + LogLevel.Warning, + Arg.Any(), + Arg.Is(state => state.ToString()!.Contains("Failed to delete the stored artwork of the book")), + Arg.Any(), + Arg.Any>()); } [Fact] diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Deletion/MusicMediaLibraryItemDeletionStrategyTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Deletion/MusicMediaLibraryItemDeletionStrategyTests.cs index 24715550..8ce95a5b 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Deletion/MusicMediaLibraryItemDeletionStrategyTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Deletion/MusicMediaLibraryItemDeletionStrategyTests.cs @@ -52,6 +52,7 @@ public class MusicMediaLibraryItemDeletionStrategyTests _mockMusicArtworkRepository = Substitute.For(); _mockMusicArtworkService = Substitute.For(); _mockLogger = Substitute.For>(); + _mockLogger.IsEnabled(Arg.Any()).Returns(true); _mockUnitOfWork.TrackRepository.Returns(_mockTrackRepository); _mockUnitOfWork.AlbumRepository.Returns(_mockAlbumRepository); _mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository); @@ -293,6 +294,54 @@ public class MusicMediaLibraryItemDeletionStrategyTests Arg.Any>()); } + [Fact] + public async Task DeleteItemAsync_WhenLoggingIsDisabledAndDeletingAStoredArtworkFileFails_ShouldNotLogAWarningButStillDeleteTheRow() + { + // Arrange + _mockLogger.IsEnabled(Arg.Any()).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()) + .Returns(Result.From(track)); + _mockMusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Track, track.Id, Arg.Any()) + .Returns(Result.From>([trackArtwork])); + _mockMusicArtworkService.DeleteStoredArtwork(trackArtwork.FileName!) + .Returns(Errors.FileSystemManagement.FileNotFound); + _mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Track, track.Id, Arg.Any()) + .Returns(Result.Deleted); + _mockTrackRepository.DeleteByIdAsync(track.Id, Arg.Any()) + .Returns(Result.From(Result.Deleted)); + _mockAlbumRepository.GetIncludingDeletedByIdAsync(albumId, Arg.Any()) + .Returns(Result.From(album)); + _mockTrackRepository.GetByAlbumIdIncludingDeletedAsync(albumId, Arg.Any()) + .Returns(Result.From>([track])); + _mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any()) + .Returns(Result.Deleted); + _mockAlbumRepository.DeleteByIdAsync(albumId, Arg.Any()) + .Returns(Result.From(Result.Deleted)); + _mockAlbumRepository.GetByArtistIdIncludingDeletedAsync(artistId, Arg.Any()) + .Returns(Result.From>([otherAlbum])); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); + + // Act + Result 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()); + _mockLogger.DidNotReceive().Log( + LogLevel.Warning, + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any>()); + } + [Fact] public async Task DeleteItemAsync_WhenAlbumWasAlreadyRemoved_ShouldPersistTheTrackDeletion() { diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Networking/PublicHostValidationHandlerTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Networking/PublicHostValidationHandlerTests.cs index 277e2909..2bc3030e 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Networking/PublicHostValidationHandlerTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Networking/PublicHostValidationHandlerTests.cs @@ -113,6 +113,7 @@ public class PublicHostValidationHandlerTests { // Arrange ILogger mockLogger = Substitute.For>(); + mockLogger.IsEnabled(Arg.Any()).Returns(true); StubHttpMessageHandler innerHandler = new(); PublicHostValidationHandler handler = new(CreateValidator(), mockLogger) { InnerHandler = innerHandler }; using HttpClient client = new(handler); diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginDetectionSyncJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginDetectionSyncJobTests.cs index e1996439..48a20e7f 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginDetectionSyncJobTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginDetectionSyncJobTests.cs @@ -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()).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(plugin => plugin.Id == successfulPlugin.Id), Arg.Any()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + _mockLogger.Received(1).Log( + LogLevel.Error, + Arg.Any(), + Arg.Is(state => state.ToString()!.Contains("Failed to persist the detection of plugin")), + Arg.Any(), + Arg.Any>()); } [Fact] diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginSettingsStoreTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginSettingsStoreTests.cs index d181af21..a2ea341f 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginSettingsStoreTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginSettingsStoreTests.cs @@ -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()).Returns(true); Guid pluginId = Guid.NewGuid(); _mockPluginRepository.GetByIdAsync(pluginId, cancellationToken: Arg.Any()) .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(), + Arg.Is(state => state.ToString()!.Contains("Failed to read the settings of the plugin")), + Arg.Any(), + Arg.Any>()); } } diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/ScheduledJobSchedulerJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/ScheduledJobSchedulerJobTests.cs index 0fbc940e..5163acb0 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/ScheduledJobSchedulerJobTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/ScheduledJobSchedulerJobTests.cs @@ -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 _mockLogger; private readonly ScheduledJobRuntimeRegistry _runtimeRegistry; private readonly ScheduledJobSchedulerJob _sut; private readonly Dictionary _services; @@ -95,8 +97,8 @@ public class ScheduledJobSchedulerJobTests .Returns(callInfo => _services.TryGetValue((Type)callInfo[0]!, out object? service) ? service : null); _runtimeRegistry = new ScheduledJobRuntimeRegistry(); - ILogger logger = Substitute.For>(); - _sut = new ScheduledJobSchedulerJob(_runtimeRegistry, logger, _mockServiceScopeFactory); + _mockLogger = Substitute.For>(); + _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()).Returns(true); ScheduledJobEntity addedJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Added, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(addedJob.Id); _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(addedJob); @@ -568,12 +571,19 @@ public class ScheduledJobSchedulerJobTests // Assert await _mockTaskExecutor.Received(1).ExecutePayloadAsync(Arg.Any(), Arg.Any()); await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => !domainEvent.IsCycleRun), Arg.Any()); + _mockLogger.Received(1).Log( + LogLevel.Warning, + Arg.Any(), + Arg.Is(state => state.ToString()!.Contains("failed:")), + Arg.Any(), + Arg.Any>()); } [Fact] public async Task ExecuteScheduledJobRunAsync_WhenTheTaskPayloadThrows_ShouldLogTheExceptionAndStillCompleteTheExecution() { // Arrange + _mockLogger.IsEnabled(Arg.Any()).Returns(true); ScheduledJobEntity addedJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Added, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(addedJob.Id); _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(addedJob); @@ -586,6 +596,12 @@ public class ScheduledJobSchedulerJobTests // Assert await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => !domainEvent.IsCycleRun), Arg.Any()); + _mockLogger.Received(1).Log( + LogLevel.Error, + Arg.Any(), + Arg.Any(), + Arg.Is(exception => exception is InvalidOperationException && exception.Message == "The task threw."), + Arg.Any>()); } [Fact] diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeSynchronizerTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeSynchronizerTests.cs index 3594e497..ce2015cd 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeSynchronizerTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeSynchronizerTests.cs @@ -52,6 +52,7 @@ public class ThemeSynchronizerTests : IDisposable _mockUnitOfWork.ThemeRepository.Returns(_mockThemeRepository); _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockLogger = Substitute.For(); + _mockLogger.IsEnabled(Arg.Any()).Returns(true); _mockThemeService.GetBundledThemeArchivePaths().Returns([]); _mockThemeService.HasThemePack(Arg.Any()).Returns(true); _mockThemeService.DefaultThemeId.Returns("lumina-default"); @@ -79,6 +80,28 @@ public class ThemeSynchronizerTests : IDisposable await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } + [Fact] + public async Task SynchronizeAsync_WhenLoggingIsDisabledAndTheInstalledThemesCannotBeRead_ShouldNotLogAWarning() + { + // Arrange + _mockLogger.IsEnabled(Arg.Any()).Returns(false); + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()) + .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()); + _mockLogger.DidNotReceive().Log( + LogLevel.Warning, + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any>()); + } + [Fact] public async Task SynchronizeAsync_WhenABundledArchiveManifestCannotBeRead_ShouldSkipThatArchive() { @@ -235,6 +258,12 @@ public class ThemeSynchronizerTests : IDisposable // Assert await _mockThemeRepository.Received(1).InsertAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + _mockLogger.Received(1).Log( + LogLevel.Warning, + Arg.Any(), + Arg.Is(state => state.ToString()!.Contains("Failed to persist the detection of theme")), + Arg.Any(), + Arg.Any>()); } [Fact] diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Common/Middlewares/EventualConsistencyMiddlewareTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Common/Middlewares/EventualConsistencyMiddlewareTests.cs index 2253c130..2b656c37 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Common/Middlewares/EventualConsistencyMiddlewareTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Common/Middlewares/EventualConsistencyMiddlewareTests.cs @@ -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 mockLogger = Substitute.For>(); + mockLogger.IsEnabled(Arg.Any()).Returns(true); EventualConsistencyMiddleware sut = new(_ => Task.CompletedTask, mockLogger); IUnitOfWork mockUnitOfWork = Substitute.For(); 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()); await mockPublisher.DidNotReceive().PublishAsync(Arg.Any(), Arg.Any()); + mockLogger.Received(1).Log( + LogLevel.Error, + Arg.Any(), + Arg.Any(), + Arg.Is(exception => exception is InvalidOperationException && exception.Message == "commit failed"), + Arg.Any>()); } /// diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Common/Middlewares/ExceptionHandlingMiddlewareTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Common/Middlewares/ExceptionHandlingMiddlewareTests.cs index 819e0d03..9c45742c 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Common/Middlewares/ExceptionHandlingMiddlewareTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Common/Middlewares/ExceptionHandlingMiddlewareTests.cs @@ -33,6 +33,7 @@ public class ExceptionHandlingMiddlewareTests public ExceptionHandlingMiddlewareTests() { _mockLogger = Substitute.For>(); + _mockLogger.IsEnabled(Arg.Any()).Returns(true); _sut = new ExceptionHandlingMiddleware(context => _nextDelegate(context), _mockLogger); } @@ -87,6 +88,30 @@ public class ExceptionHandlingMiddlewareTests Arg.Any>()); } + [Fact] + public async Task InvokeAsync_WhenLoggingIsDisabledAndNextThrowsException_ShouldNotLogTheException() + { + // Arrange + _mockLogger.IsEnabled(Arg.Any()).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(), + Arg.Any(), + Arg.Any(), + Arg.Any>()); + } + [Fact] public async Task InvokeAsync_WhenNextThrowsExceptionAndActivityIsCurrent_ShouldUseTheActivityIdAsTraceId() { diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Middlewares/ExceptionHandlingMiddlewareTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Middlewares/ExceptionHandlingMiddlewareTests.cs index 7da7887d..3734824b 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Middlewares/ExceptionHandlingMiddlewareTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Middlewares/ExceptionHandlingMiddlewareTests.cs @@ -41,6 +41,7 @@ public class ExceptionHandlingMiddlewareTests public ExceptionHandlingMiddlewareTests() { _mockLogger = Substitute.For>(); + _mockLogger.IsEnabled(Arg.Any()).Returns(true); _mockStringLocalizer = Substitute.For>(); _mockStringLocalizer[Arg.Any()].Returns(callInfo => new LocalizedString(callInfo.Arg(), $"localized:{callInfo.Arg()}")); _mockAuthenticationService = Substitute.For(); @@ -91,6 +92,27 @@ public class ExceptionHandlingMiddlewareTests Arg.Any>()); } + [Fact] + public async Task InvokeAsync_WhenLoggingIsDisabledAndNextThrowsNonApiExceptionAndApiRequest_ShouldNotLogError() + { + // Arrange + _mockLogger.IsEnabled(Arg.Any()).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(), + Arg.Any(), + Arg.Any(), + Arg.Any>()); + } + [Fact] public async Task InvokeAsync_WhenNextThrowsNonApiExceptionAndPageRequest_ShouldWriteHtmlErrorPage() {