diff --git a/.editorconfig b/.editorconfig index 99cb0d7d..d772b8b4 100644 --- a/.editorconfig +++ b/.editorconfig @@ -464,11 +464,21 @@ stylecop.documentation.xmlHeader = false # https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1200.md dotnet_diagnostic.SA1623.severity = none +# CA1848: Use the LoggerMessage delegates +# Justification: This rule currently throws an exception for our codebase. +# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1848 +dotnet_diagnostic.CA1848.severity = none + # CA1859: Use concrete types when possible # Justification: This rule currently throws an exception for our codebase. # https://github.com/dotnet/roslyn-analyzers/issues/6852 dotnet_diagnostic.CA1859.severity = none +# CA2254: Template should be a static expression +# Justification: This rule currently throws an exception for our codebase. +# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca2254 +dotnet_diagnostic.CA2254.severity = none + # NU5104: A stable release of a package should not have a prerelease dependency # Justification: The Mono.Unix package that allows our tool to be built on ARM is labeled as 7.1.0-final.1.21458.1 which is detected as a prerelease dependency. # https://learn.microsoft.com/en-us/nuget/reference/errors-and-warnings/nu5104 diff --git a/src/Microsoft.Sbom.Api/Config/ConfigPostProcessor.cs b/src/Microsoft.Sbom.Api/Config/ConfigPostProcessor.cs index 88566564..f433955d 100644 --- a/src/Microsoft.Sbom.Api/Config/ConfigPostProcessor.cs +++ b/src/Microsoft.Sbom.Api/Config/ConfigPostProcessor.cs @@ -7,6 +7,7 @@ using System.IO; using System.Linq; using AutoMapper; +using Microsoft.Extensions.Logging; using Microsoft.Sbom.Api.Output.Telemetry; using Microsoft.Sbom.Common; using Microsoft.Sbom.Common.Config; diff --git a/src/Microsoft.Sbom.Api/Converters/ComponentToExternalReferenceInfoConverter.cs b/src/Microsoft.Sbom.Api/Converters/ComponentToExternalReferenceInfoConverter.cs index e3d75a97..b6d75f73 100644 --- a/src/Microsoft.Sbom.Api/Converters/ComponentToExternalReferenceInfoConverter.cs +++ b/src/Microsoft.Sbom.Api/Converters/ComponentToExternalReferenceInfoConverter.cs @@ -7,11 +7,11 @@ using System.Threading.Tasks; using Microsoft.ComponentDetection.Contracts.BcdeModels; using Microsoft.ComponentDetection.Contracts.TypedComponent; +using Microsoft.Extensions.Logging; using Microsoft.Sbom.Api.Entities; using Microsoft.Sbom.Contracts; using Microsoft.Sbom.Contracts.Enums; using Microsoft.Sbom.Extensions.Entities; -using Serilog; namespace Microsoft.Sbom.Api.Converters; @@ -20,9 +20,9 @@ namespace Microsoft.Sbom.Api.Converters; /// public class ComponentToExternalReferenceInfoConverter { - private readonly ILogger log; + private readonly ILogger log; - public ComponentToExternalReferenceInfoConverter(ILogger log) + public ComponentToExternalReferenceInfoConverter(ILogger log) { this.log = log ?? throw new ArgumentNullException(nameof(log)); } @@ -43,7 +43,7 @@ public ComponentToExternalReferenceInfoConverter(ILogger log) } catch (Exception e) { - log.Debug($"Encountered an error while converting SBOM component {scannedComponent.Component.Id} to external reference: {e.Message}"); + log.LogDebug($"Encountered an error while converting SBOM component {scannedComponent.Component.Id} to external reference: {e.Message}"); await errors.Writer.WriteAsync(new FileValidationResult { ErrorType = Entities.ErrorType.PackageError, diff --git a/src/Microsoft.Sbom.Api/Converters/ExternalReferenceInfoToPathConverter.cs b/src/Microsoft.Sbom.Api/Converters/ExternalReferenceInfoToPathConverter.cs index 27604c8a..f2b69da9 100644 --- a/src/Microsoft.Sbom.Api/Converters/ExternalReferenceInfoToPathConverter.cs +++ b/src/Microsoft.Sbom.Api/Converters/ExternalReferenceInfoToPathConverter.cs @@ -4,9 +4,9 @@ using System; using System.Threading.Channels; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; using Microsoft.Sbom.Api.Entities; using Microsoft.Sbom.Extensions.Entities; -using Serilog; namespace Microsoft.Sbom.Api.Converters; @@ -15,9 +15,9 @@ namespace Microsoft.Sbom.Api.Converters; /// public class ExternalReferenceInfoToPathConverter { - private readonly ILogger log; + private readonly ILogger log; - public ExternalReferenceInfoToPathConverter(ILogger log) + public ExternalReferenceInfoToPathConverter(ILogger log) { this.log = log ?? throw new ArgumentNullException(nameof(log)); } @@ -37,7 +37,7 @@ public ExternalReferenceInfoToPathConverter(ILogger log) if (path == null) { - log.Debug($"Encountered an error while converting external reference {externalDocumentRef.ExternalDocumentName} for null path."); + log.LogDebug($"Encountered an error while converting external reference {externalDocumentRef.ExternalDocumentName} for null path."); await errors.Writer.WriteAsync(new FileValidationResult { ErrorType = ErrorType.Other, @@ -53,7 +53,7 @@ await errors.Writer.WriteAsync(new FileValidationResult } catch (Exception e) { - log.Debug($"Encountered an error while converting external reference {externalDocumentRef.ExternalDocumentName} to path: {e.Message}"); + log.LogDebug($"Encountered an error while converting external reference {externalDocumentRef.ExternalDocumentName} to path: {e.Message}"); await errors.Writer.WriteAsync(new FileValidationResult { ErrorType = ErrorType.Other, diff --git a/src/Microsoft.Sbom.Api/Executors/ComponentDetectionBaseWalker.cs b/src/Microsoft.Sbom.Api/Executors/ComponentDetectionBaseWalker.cs index d4240c50..77f53eff 100644 --- a/src/Microsoft.Sbom.Api/Executors/ComponentDetectionBaseWalker.cs +++ b/src/Microsoft.Sbom.Api/Executors/ComponentDetectionBaseWalker.cs @@ -10,7 +10,6 @@ using System.Threading.Tasks; using Microsoft.ComponentDetection.Contracts; using Microsoft.ComponentDetection.Contracts.BcdeModels; -using Microsoft.Sbom.Adapters.ComponentDetection; using Microsoft.Sbom.Api.Config.Extensions; using Microsoft.Sbom.Api.Exceptions; using Microsoft.Sbom.Api.PackageDetails; @@ -19,16 +18,18 @@ using Microsoft.Sbom.Common.Config; using Microsoft.Sbom.Extensions; using Constants = Microsoft.Sbom.Api.Utils.Constants; -using ILogger = Serilog.ILogger; namespace Microsoft.Sbom.Api.Executors; +using Microsoft.Extensions.Logging; +using Microsoft.Sbom.Adapters.ComponentDetection; + /// /// Abstract class that runs component detection tool in the given folder. /// public abstract class ComponentDetectionBaseWalker { - private readonly ILogger log; + private readonly ILogger log; private readonly ComponentDetectorCachedExecutor componentDetector; private readonly IConfiguration configuration; private readonly ISbomConfigProvider sbomConfigs; @@ -42,7 +43,7 @@ public abstract class ComponentDetectionBaseWalker private ComponentDetectionCliArgumentBuilder cliArgumentBuilder; public ComponentDetectionBaseWalker( - ILogger log, + ILogger log, ComponentDetectorCachedExecutor componentDetector, IConfiguration configuration, ISbomConfigProvider sbomConfigs, @@ -63,7 +64,7 @@ public ComponentDetectionBaseWalker( { if (fileSystemUtils.FileExists(buildComponentDirPath)) { - log.Debug($"Scanning for packages under the root path {buildComponentDirPath}."); + log.LogDebug($"Scanning for packages under the root path {buildComponentDirPath}."); } // If the buildComponentDirPath is null or empty, make sure we have a ManifestDirPath and create a new temp directory with a random name. @@ -151,7 +152,7 @@ async Task Scan(string path) LicenseDictionary = licenseInformationFetcher.GetLicenseDictionary(); - log.Information($"Found license information for {LicenseDictionary.Count} out of {uniqueComponents.Count()} unique components."); + log.LogInformation($"Found license information for {LicenseDictionary.Count} out of {uniqueComponents.Count()} unique components."); } } @@ -196,7 +197,7 @@ async Task Scan(string path) } catch (Exception e) { - log.Error($"Unknown error while running CD scan: {e}"); + log.LogError($"Unknown error while running CD scan: {e}"); await errors.Writer.WriteAsync(new ComponentDetectorException("Unknown exception", e)); return; } diff --git a/src/Microsoft.Sbom.Api/Executors/ComponentToPackageInfoConverter.cs b/src/Microsoft.Sbom.Api/Executors/ComponentToPackageInfoConverter.cs index 8aa02c03..83da5790 100644 --- a/src/Microsoft.Sbom.Api/Executors/ComponentToPackageInfoConverter.cs +++ b/src/Microsoft.Sbom.Api/Executors/ComponentToPackageInfoConverter.cs @@ -6,28 +6,27 @@ using System.Threading.Channels; using System.Threading.Tasks; using Microsoft.ComponentDetection.Contracts.BcdeModels; +using Microsoft.Extensions.Logging; +using Microsoft.Sbom.Adapters.ComponentDetection; using Microsoft.Sbom.Adapters.Report; using Microsoft.Sbom.Api.Entities; using Microsoft.Sbom.Contracts; -using Serilog; namespace Microsoft.Sbom.Api.Executors; -using Microsoft.Sbom.Adapters.ComponentDetection; - /// /// Takes a object and converts it to a /// object using a . /// public class ComponentToPackageInfoConverter { - private readonly ILogger log; + private readonly ILogger log; // TODO: Remove and use interface // For unit testing only public ComponentToPackageInfoConverter() { } - public ComponentToPackageInfoConverter(ILogger log) + public ComponentToPackageInfoConverter(ILogger log) { this.log = log ?? throw new ArgumentNullException(nameof(log)); } @@ -56,7 +55,7 @@ async Task ConvertComponentToPackage(ExtendedScannedComponent scannedComponent, if (sbom == null) { - log.Debug($"Unable to serialize component '{scannedComponent.Component.Id}' of type '{scannedComponent.DetectorId}'. " + + log.LogDebug($"Unable to serialize component '{scannedComponent.Component.Id}' of type '{scannedComponent.DetectorId}'. " + $"This component won't be included in the generated SBOM."); } else @@ -66,7 +65,7 @@ async Task ConvertComponentToPackage(ExtendedScannedComponent scannedComponent, } catch (Exception e) { - log.Debug($"Encountered an error while processing package {scannedComponent.Component.Id}: {e.Message}"); + log.LogDebug($"Encountered an error while processing package {scannedComponent.Component.Id}: {e.Message}"); await errors.Writer.WriteAsync(new FileValidationResult { ErrorType = ErrorType.PackageError, diff --git a/src/Microsoft.Sbom.Api/Executors/DirectoryWalker.cs b/src/Microsoft.Sbom.Api/Executors/DirectoryWalker.cs index 90d05b91..4b8d63b5 100644 --- a/src/Microsoft.Sbom.Api/Executors/DirectoryWalker.cs +++ b/src/Microsoft.Sbom.Api/Executors/DirectoryWalker.cs @@ -5,11 +5,11 @@ using System.Linq; using System.Threading.Channels; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; using Microsoft.Sbom.Api.Entities; using Microsoft.Sbom.Api.Exceptions; using Microsoft.Sbom.Common; using Microsoft.Sbom.Common.Config; -using Serilog; namespace Microsoft.Sbom.Api.Executors; @@ -20,10 +20,10 @@ namespace Microsoft.Sbom.Api.Executors; public class DirectoryWalker { private readonly IFileSystemUtils fileSystemUtils; - private readonly ILogger log; + private readonly ILogger log; private readonly bool followSymlinks; - public DirectoryWalker(IFileSystemUtils fileSystemUtils, ILogger log, IConfiguration configuration) + public DirectoryWalker(IFileSystemUtils fileSystemUtils, ILogger log, IConfiguration configuration) { if (configuration is null) { @@ -37,13 +37,13 @@ public DirectoryWalker(IFileSystemUtils fileSystemUtils, ILogger log, IConfigura if (!followSymlinks) { - log.Information("FollowSymlinks parameter is set to false, we won't follow symbolic links while traversing the filesystem."); + log.LogInformation("FollowSymlinks parameter is set to false, we won't follow symbolic links while traversing the filesystem."); } } public (ChannelReader file, ChannelReader errors) GetFilesRecursively(string root) { - log.Debug($"Enumerating files under the root path {root}."); + log.LogDebug($"Enumerating files under the root path {root}."); if (!fileSystemUtils.DirectoryExists(root)) { @@ -57,10 +57,10 @@ async Task WalkDir(string path) { try { - log.Verbose("Enumerating files under the directory {path}", path); + log.LogTrace("Enumerating files under the directory {Path}", path); foreach (var file in fileSystemUtils.GetFilesInDirectory(path, followSymlinks)) { - log.Verbose("Found file {file}.", file); + log.LogTrace("Found file {File}.", file); await output.Writer.WriteAsync(file); } @@ -69,7 +69,7 @@ async Task WalkDir(string path) } catch (Exception e) { - log.Debug($"Encountered an unknown error for {path}: {e.Message}"); + log.LogDebug($"Encountered an unknown error for {path}: {e.Message}"); await errors.Writer.WriteAsync(new FileValidationResult { ErrorType = ErrorType.Other, diff --git a/src/Microsoft.Sbom.Api/Executors/EnumeratorChannel.cs b/src/Microsoft.Sbom.Api/Executors/EnumeratorChannel.cs index 7c56a162..44622f73 100644 --- a/src/Microsoft.Sbom.Api/Executors/EnumeratorChannel.cs +++ b/src/Microsoft.Sbom.Api/Executors/EnumeratorChannel.cs @@ -5,8 +5,8 @@ using System.Collections.Generic; using System.Threading.Channels; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; using Microsoft.Sbom.Api.Entities; -using Serilog; namespace Microsoft.Sbom.Api.Executors; @@ -15,9 +15,9 @@ namespace Microsoft.Sbom.Api.Executors; /// public class EnumeratorChannel { - private readonly ILogger log; + private readonly ILogger log; - public EnumeratorChannel(ILogger log) + public EnumeratorChannel(ILogger log) { this.log = log ?? throw new ArgumentNullException(nameof(log)); } @@ -44,7 +44,7 @@ async Task Enumerate() } catch (Exception e) { - log.Debug($"Encountered an unknown error while enumerating: {e.Message}"); + log.LogDebug($"Encountered an unknown error while enumerating: {e.Message}"); await errors.Writer.WriteAsync(new FileValidationResult { ErrorType = ErrorType.Other diff --git a/src/Microsoft.Sbom.Api/Executors/ExternalDocumentReferenceWriter.cs b/src/Microsoft.Sbom.Api/Executors/ExternalDocumentReferenceWriter.cs index bac3111c..f40789bd 100644 --- a/src/Microsoft.Sbom.Api/Executors/ExternalDocumentReferenceWriter.cs +++ b/src/Microsoft.Sbom.Api/Executors/ExternalDocumentReferenceWriter.cs @@ -5,11 +5,11 @@ using System.Collections.Generic; using System.Threading.Channels; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; using Microsoft.Sbom.Api.Entities; using Microsoft.Sbom.Api.Manifest; using Microsoft.Sbom.Extensions; using Microsoft.Sbom.Extensions.Entities; -using Serilog; namespace Microsoft.Sbom.Api.Executors; @@ -20,11 +20,11 @@ namespace Microsoft.Sbom.Api.Executors; public class ExternalDocumentReferenceWriter { private readonly ManifestGeneratorProvider manifestGeneratorProvider; - private readonly ILogger log; + private readonly ILogger log; public ExternalDocumentReferenceWriter( ManifestGeneratorProvider manifestGeneratorProvider, - ILogger log) + ILogger log) { this.manifestGeneratorProvider = manifestGeneratorProvider ?? throw new ArgumentNullException(nameof(manifestGeneratorProvider)); this.log = log ?? throw new ArgumentNullException(nameof(log)); @@ -61,7 +61,7 @@ public ExternalDocumentReferenceWriter( } catch (Exception e) { - log.Warning($"Encountered an error while generating json for external document reference {externalDocumentReferenceInfo.ExternalDocumentName}: {e.Message}"); + log.LogWarning($"Encountered an error while generating json for external document reference {externalDocumentReferenceInfo.ExternalDocumentName}: {e.Message}"); await errors.Writer.WriteAsync(new FileValidationResult { ErrorType = ErrorType.JsonSerializationError, diff --git a/src/Microsoft.Sbom.Api/Executors/FileFilterer.cs b/src/Microsoft.Sbom.Api/Executors/FileFilterer.cs index 9b317079..8b50d87c 100644 --- a/src/Microsoft.Sbom.Api/Executors/FileFilterer.cs +++ b/src/Microsoft.Sbom.Api/Executors/FileFilterer.cs @@ -6,12 +6,12 @@ using System.Linq; using System.Threading.Channels; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; using Microsoft.Sbom.Api.Entities; using Microsoft.Sbom.Api.Filters; using Microsoft.Sbom.Common; using Microsoft.Sbom.Common.Config; using Microsoft.Sbom.Extensions.Entities; -using Serilog; namespace Microsoft.Sbom.Api.Executors; @@ -21,13 +21,13 @@ namespace Microsoft.Sbom.Api.Executors; public class FileFilterer { private readonly IFilter rootPathFilter; - private readonly ILogger log; + private readonly ILogger log; private readonly IFileSystemUtils fileSystemUtils; private readonly IConfiguration configuration; public FileFilterer( IFilter rootPathFilter, - ILogger log, + ILogger log, IConfiguration configuration, IFileSystemUtils fileSystemUtils) { @@ -96,7 +96,7 @@ await errors.Writer.WriteAsync(new FileValidationResult } catch (Exception e) { - log.Debug($"Encountered an error while filtering file {file.Path}: {e.Message}"); + log.LogDebug($"Encountered an error while filtering file {file.Path}: {e.Message}"); await errors.Writer.WriteAsync(new FileValidationResult { ErrorType = ErrorType.Other, diff --git a/src/Microsoft.Sbom.Api/Executors/FileHasher.cs b/src/Microsoft.Sbom.Api/Executors/FileHasher.cs index 6b3d2dd1..8d585e8b 100644 --- a/src/Microsoft.Sbom.Api/Executors/FileHasher.cs +++ b/src/Microsoft.Sbom.Api/Executors/FileHasher.cs @@ -5,6 +5,7 @@ using System.Linq; using System.Threading.Channels; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; using Microsoft.Sbom.Api.Convertors; using Microsoft.Sbom.Api.Entities; using Microsoft.Sbom.Api.Exceptions; @@ -12,12 +13,10 @@ using Microsoft.Sbom.Api.Manifest; using Microsoft.Sbom.Api.Utils; using Microsoft.Sbom.Common.Config; -using Microsoft.Sbom.Contracts; using Microsoft.Sbom.Contracts.Enums; using Microsoft.Sbom.Entities; using Microsoft.Sbom.Extensions; using Microsoft.Sbom.Extensions.Entities; -using Serilog; using IConfiguration = Microsoft.Sbom.Common.Config.IConfiguration; namespace Microsoft.Sbom.Api.Executors; @@ -30,7 +29,7 @@ public class FileHasher { private readonly IHashCodeGenerator hashCodeGenerator; private readonly IManifestPathConverter manifestPathConverter; - private readonly ILogger log; + private readonly ILogger log; private readonly IConfiguration configuration; private readonly ISbomConfigProvider sbomConfigs; private readonly ManifestGeneratorProvider manifestGeneratorProvider; @@ -67,7 +66,7 @@ private AlgorithmName[] HashAlgorithmNames public FileHasher( IHashCodeGenerator hashCodeGenerator, IManifestPathConverter manifestPathConverter, - ILogger log, + ILogger log, IConfiguration configuration, ISbomConfigProvider sbomConfigs, ManifestGeneratorProvider manifestGeneratorProvider, @@ -144,7 +143,7 @@ await output.Writer.WriteAsync( ManifestData.HashesMap.Remove(relativeFilePath); } - log.Error($"Encountered an error while generating hash for file {file}: {e.Message}"); + log.LogError($"Encountered an error while generating hash for file {file}: {e.Message}"); await errors.Writer.WriteAsync(new FileValidationResult { ErrorType = Entities.ErrorType.Other, diff --git a/src/Microsoft.Sbom.Api/Executors/FileInfoWriter.cs b/src/Microsoft.Sbom.Api/Executors/FileInfoWriter.cs index c2706595..d9659e28 100644 --- a/src/Microsoft.Sbom.Api/Executors/FileInfoWriter.cs +++ b/src/Microsoft.Sbom.Api/Executors/FileInfoWriter.cs @@ -6,11 +6,11 @@ using System.Linq; using System.Threading.Channels; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; using Microsoft.Sbom.Api.Entities; using Microsoft.Sbom.Api.Manifest; using Microsoft.Sbom.Extensions; using Microsoft.Sbom.Extensions.Entities; -using Serilog; namespace Microsoft.Sbom.Api.Executors; @@ -21,9 +21,9 @@ namespace Microsoft.Sbom.Api.Executors; public class FileInfoWriter { private readonly ManifestGeneratorProvider manifestGeneratorProvider; - private readonly ILogger log; + private readonly ILogger log; - public FileInfoWriter(ManifestGeneratorProvider manifestGeneratorProvider, ILogger log) + public FileInfoWriter(ManifestGeneratorProvider manifestGeneratorProvider, ILogger log) { if (manifestGeneratorProvider is null) { @@ -59,7 +59,7 @@ private async Task Generate(IList filesArraySupportingSBOMs, Intern { foreach (var config in filesArraySupportingSBOMs) { - log.Verbose("Generating json for file {file} into {config}", sbomFile.Path, config.ManifestJsonFilePath); + log.LogTrace("Generating json for file {File} into {Config}", sbomFile.Path, config.ManifestJsonFilePath); var generationResult = manifestGeneratorProvider .Get(config.ManifestInfo) .GenerateJsonDocument(sbomFile); @@ -81,7 +81,7 @@ private async Task Generate(IList filesArraySupportingSBOMs, Intern } catch (Exception e) { - log.Debug($"Encountered an error while generating json for file {sbomFile.Path}: {e.Message}"); + log.LogDebug($"Encountered an error while generating json for file {sbomFile.Path}: {e.Message}"); await errors.Writer.WriteAsync(new FileValidationResult { ErrorType = ErrorType.JsonSerializationError, diff --git a/src/Microsoft.Sbom.Api/Executors/FileListEnumerator.cs b/src/Microsoft.Sbom.Api/Executors/FileListEnumerator.cs index 38663d2a..e59ab3d7 100644 --- a/src/Microsoft.Sbom.Api/Executors/FileListEnumerator.cs +++ b/src/Microsoft.Sbom.Api/Executors/FileListEnumerator.cs @@ -2,14 +2,13 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; -using System.Collections.Generic; using System.Linq; using System.Threading.Channels; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; using Microsoft.Sbom.Api.Entities; using Microsoft.Sbom.Api.Exceptions; using Microsoft.Sbom.Common; -using Serilog; namespace Microsoft.Sbom.Api.Executors; @@ -20,14 +19,14 @@ namespace Microsoft.Sbom.Api.Executors; public class FileListEnumerator { private readonly IFileSystemUtils fileSystemUtils; - private readonly ILogger log; + private readonly ILogger log; /// /// FileListEnumerator constructor for dependency injection. /// /// IFileSystemUtils interface used for this instance. /// Ilogger interface used for this instance. - public FileListEnumerator(IFileSystemUtils fileSystemUtils, ILogger log) + public FileListEnumerator(IFileSystemUtils fileSystemUtils, ILogger log) { this.fileSystemUtils = fileSystemUtils ?? throw new ArgumentNullException(nameof(fileSystemUtils)); this.log = log ?? throw new ArgumentNullException(nameof(log)); @@ -46,7 +45,7 @@ public FileListEnumerator(IFileSystemUtils fileSystemUtils, ILogger log) throw new ArgumentException($"'{nameof(listFile)}' cannot be null or whitespace.", nameof(listFile)); } - log.Debug($"Enumerating all files from {nameof(listFile)}."); + log.LogDebug($"Enumerating all files from {nameof(listFile)}."); if (!fileSystemUtils.FileExists(listFile)) { diff --git a/src/Microsoft.Sbom.Api/Executors/HashValidator.cs b/src/Microsoft.Sbom.Api/Executors/HashValidator.cs index 2ad2c696..e9e85b97 100644 --- a/src/Microsoft.Sbom.Api/Executors/HashValidator.cs +++ b/src/Microsoft.Sbom.Api/Executors/HashValidator.cs @@ -6,7 +6,6 @@ using System.Threading.Tasks; using Microsoft.Sbom.Api.Entities; using Microsoft.Sbom.Common.Config; -using Microsoft.Sbom.Contracts; using Microsoft.Sbom.Extensions.Entities; namespace Microsoft.Sbom.Api.Executors; diff --git a/src/Microsoft.Sbom.Api/Executors/LicenseInformationFetcher.cs b/src/Microsoft.Sbom.Api/Executors/LicenseInformationFetcher.cs index 47dc6f7d..578e3c29 100644 --- a/src/Microsoft.Sbom.Api/Executors/LicenseInformationFetcher.cs +++ b/src/Microsoft.Sbom.Api/Executors/LicenseInformationFetcher.cs @@ -7,21 +7,21 @@ using System.Linq; using System.Threading.Tasks; using Microsoft.ComponentDetection.Contracts.BcdeModels; +using Microsoft.Extensions.Logging; using Microsoft.Sbom.Api.Exceptions; using Microsoft.Sbom.Api.Output.Telemetry; using Newtonsoft.Json.Linq; -using Serilog; namespace Microsoft.Sbom.Api.Executors; public class LicenseInformationFetcher : ILicenseInformationFetcher { - private readonly ILogger log; + private readonly ILogger log; private readonly IRecorder recorder; private readonly ILicenseInformationService licenseInformationService; private readonly ConcurrentDictionary licenseDictionary = new ConcurrentDictionary(); - public LicenseInformationFetcher(ILogger log, IRecorder recorder, ILicenseInformationService licenseInformationService) + public LicenseInformationFetcher(ILogger log, IRecorder recorder, ILicenseInformationService licenseInformationService) { this.log = log ?? throw new ArgumentNullException(nameof(log)); this.recorder = recorder ?? throw new ArgumentNullException(nameof(recorder)); @@ -73,7 +73,7 @@ public List ConvertComponentsToListForApi(IEnumerable break; default: - log.Debug($"License retrieval for component type {componentType} is not supported yet."); + log.LogDebug($"License retrieval for component type {componentType} is not supported yet."); break; } } @@ -130,7 +130,7 @@ public Dictionary ConvertClearlyDefinedApiResponseToList(string catch { recorder.RecordAPIException(new ClearlyDefinedResponseParsingException("Encountered error while attempting to parse response. License information may not be fully recorded.")); - log.Warning("Encountered error while attempting to parse response. License information may not be fully recorded."); + log.LogWarning("Encountered error while attempting to parse response. License information may not be fully recorded."); return extractedLicenses; } diff --git a/src/Microsoft.Sbom.Api/Executors/LicenseInformationService.cs b/src/Microsoft.Sbom.Api/Executors/LicenseInformationService.cs index c2a2a150..0df56a64 100644 --- a/src/Microsoft.Sbom.Api/Executors/LicenseInformationService.cs +++ b/src/Microsoft.Sbom.Api/Executors/LicenseInformationService.cs @@ -9,20 +9,20 @@ using System.Text; using System.Text.Json; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; using Microsoft.Sbom.Api.Exceptions; using Microsoft.Sbom.Api.Output.Telemetry; -using Serilog; namespace Microsoft.Sbom.Api.Executors; public class LicenseInformationService : ILicenseInformationService { - private readonly ILogger log; + private readonly ILogger log; private readonly IRecorder recorder; private readonly HttpClient httpClient; private const int ClientTimeoutSeconds = 30; - public LicenseInformationService(ILogger log, IRecorder recorder, HttpClient httpClient) + public LicenseInformationService(ILogger log, IRecorder recorder, HttpClient httpClient) { this.log = log ?? throw new ArgumentNullException(nameof(log)); this.recorder = recorder ?? throw new ArgumentNullException(nameof(recorder)); @@ -45,7 +45,7 @@ public async Task> FetchLicenseInformationFromAPI(List list var batch = listOfComponentsForApi.Skip(i).Take(batchSize).ToList(); var formattedData = JsonSerializer.Serialize(batch); - log.Debug($"Retrieving license information for {batch.Count} components..."); + log.LogDebug($"Retrieving license information for {batch.Count} components..."); var content = new StringContent(formattedData, Encoding.UTF8, "application/json"); content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); @@ -58,13 +58,13 @@ public async Task> FetchLicenseInformationFromAPI(List list } catch (Exception e) { - log.Warning($"Error encountered while fetching license information from API, resulting SBOM may have incomplete license information: {e.Message}"); + log.LogWarning($"Error encountered while fetching license information from API, resulting SBOM may have incomplete license information: {e.Message}"); recorder.RecordAPIException(new ClearlyDefinedResponseNotSuccessfulException(e.Message)); } stopwatch.Stop(); - log.Debug($"Retrieving license information for {batch.Count} components took {stopwatch.Elapsed.TotalSeconds} seconds"); + log.LogDebug($"Retrieving license information for {batch.Count} components took {stopwatch.Elapsed.TotalSeconds} seconds"); } foreach (var response in responses) @@ -75,7 +75,7 @@ public async Task> FetchLicenseInformationFromAPI(List list } else { - log.Warning($"Error encountered while fetching license information from API, resulting SBOM may have incomplete license information. Request returned status code: {response.StatusCode}"); + log.LogWarning($"Error encountered while fetching license information from API, resulting SBOM may have incomplete license information. Request returned status code: {response.StatusCode}"); recorder.RecordAPIException(new ClearlyDefinedResponseNotSuccessfulException($"Request returned status code: {response.StatusCode}")); } } diff --git a/src/Microsoft.Sbom.Api/Executors/ManifestFileFilterer.cs b/src/Microsoft.Sbom.Api/Executors/ManifestFileFilterer.cs index 4d78dd4f..98895f27 100644 --- a/src/Microsoft.Sbom.Api/Executors/ManifestFileFilterer.cs +++ b/src/Microsoft.Sbom.Api/Executors/ManifestFileFilterer.cs @@ -5,12 +5,12 @@ using System.Collections.Generic; using System.Threading.Channels; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; using Microsoft.Sbom.Api.Entities; using Microsoft.Sbom.Api.Filters; using Microsoft.Sbom.Common; using Microsoft.Sbom.Common.Config; using Microsoft.Sbom.Extensions.Entities; -using Serilog; namespace Microsoft.Sbom.Api.Executors; @@ -23,14 +23,14 @@ public class ManifestFileFilterer private readonly ManifestData manifestData; private readonly IFilter rootPathFilter; private readonly IConfiguration configuration; - private readonly ILogger log; + private readonly ILogger log; private readonly IFileSystemUtils fileSystemUtils; public ManifestFileFilterer( ManifestData manifestData, IFilter rootPathFilter, IConfiguration configuration, - ILogger log, + ILogger log, IFileSystemUtils fileSystemUtils) { this.manifestData = manifestData ?? throw new ArgumentNullException(nameof(manifestData)); @@ -69,7 +69,7 @@ await errors.Writer.WriteAsync(new FileValidationResult } catch (Exception e) { - log.Debug($"Encountered an error while filtering file {manifestFile} from the manifest: {e.Message}"); + log.LogDebug($"Encountered an error while filtering file {manifestFile} from the manifest: {e.Message}"); await errors.Writer.WriteAsync(new FileValidationResult { ErrorType = ErrorType.Other, diff --git a/src/Microsoft.Sbom.Api/Executors/ManifestFolderFilterer.cs b/src/Microsoft.Sbom.Api/Executors/ManifestFolderFilterer.cs index 06b123de..b28da61b 100644 --- a/src/Microsoft.Sbom.Api/Executors/ManifestFolderFilterer.cs +++ b/src/Microsoft.Sbom.Api/Executors/ManifestFolderFilterer.cs @@ -4,9 +4,9 @@ using System; using System.Threading.Channels; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; using Microsoft.Sbom.Api.Entities; using Microsoft.Sbom.Api.Filters; -using Serilog; namespace Microsoft.Sbom.Api.Executors; @@ -16,11 +16,11 @@ namespace Microsoft.Sbom.Api.Executors; public class ManifestFolderFilterer { private readonly IFilter manifestFolderFilter; - private readonly ILogger log; + private readonly ILogger log; public ManifestFolderFilterer( IFilter manifestFolderFilter, - ILogger log) + ILogger log) { ArgumentNullException.ThrowIfNull(manifestFolderFilter); ArgumentNullException.ThrowIfNull(log); @@ -66,7 +66,7 @@ await errors.Writer.WriteAsync(new FileValidationResult } catch (Exception e) { - log.Debug($"Encountered an error while filtering file {file}: {e.Message}"); + log.LogDebug($"Encountered an error while filtering file {file}: {e.Message}"); await errors.Writer.WriteAsync(new FileValidationResult { ErrorType = ErrorType.Other, diff --git a/src/Microsoft.Sbom.Api/Executors/PackageInfoJsonWriter.cs b/src/Microsoft.Sbom.Api/Executors/PackageInfoJsonWriter.cs index ba6b4cf5..8c9a38dd 100644 --- a/src/Microsoft.Sbom.Api/Executors/PackageInfoJsonWriter.cs +++ b/src/Microsoft.Sbom.Api/Executors/PackageInfoJsonWriter.cs @@ -5,11 +5,11 @@ using System.Collections.Generic; using System.Threading.Channels; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; using Microsoft.Sbom.Api.Entities; using Microsoft.Sbom.Api.Manifest; using Microsoft.Sbom.Contracts; using Microsoft.Sbom.Extensions; -using Serilog; namespace Microsoft.Sbom.Api.Executors; @@ -20,11 +20,11 @@ namespace Microsoft.Sbom.Api.Executors; public class PackageInfoJsonWriter { private readonly ManifestGeneratorProvider manifestGeneratorProvider; - private readonly ILogger log; + private readonly ILogger log; public PackageInfoJsonWriter( ManifestGeneratorProvider manifestGeneratorProvider, - ILogger log) + ILogger log) { if (manifestGeneratorProvider is null) { @@ -72,7 +72,7 @@ private async Task GenerateJson( } catch (Exception e) { - log.Debug($"Encountered an error while generating json for packageInfo {packageInfo}: {e.Message}"); + log.LogDebug($"Encountered an error while generating json for packageInfo {packageInfo}: {e.Message}"); await errors.Writer.WriteAsync(new FileValidationResult { ErrorType = ErrorType.JsonSerializationError, diff --git a/src/Microsoft.Sbom.Api/Executors/PackagesWalker.cs b/src/Microsoft.Sbom.Api/Executors/PackagesWalker.cs index 0e7e6346..f8d99381 100644 --- a/src/Microsoft.Sbom.Api/Executors/PackagesWalker.cs +++ b/src/Microsoft.Sbom.Api/Executors/PackagesWalker.cs @@ -5,12 +5,12 @@ using System.Linq; using Microsoft.ComponentDetection.Contracts.BcdeModels; using Microsoft.ComponentDetection.Contracts.TypedComponent; +using Microsoft.Extensions.Logging; using Microsoft.Sbom.Api.PackageDetails; using Microsoft.Sbom.Api.Utils; using Microsoft.Sbom.Common; using Microsoft.Sbom.Common.Config; using Microsoft.Sbom.Extensions; -using ILogger = Serilog.ILogger; namespace Microsoft.Sbom.Api.Executors; @@ -19,7 +19,7 @@ namespace Microsoft.Sbom.Api.Executors; /// public class PackagesWalker : ComponentDetectionBaseWalker { - public PackagesWalker(ILogger log, ComponentDetectorCachedExecutor componentDetector, IConfiguration configuration, ISbomConfigProvider sbomConfigs, IFileSystemUtils fileSystemUtils, IPackageDetailsFactory packageDetailsFactory, ILicenseInformationFetcher licenseInformationFetcher) + public PackagesWalker(ILogger log, ComponentDetectorCachedExecutor componentDetector, IConfiguration configuration, ISbomConfigProvider sbomConfigs, IFileSystemUtils fileSystemUtils, IPackageDetailsFactory packageDetailsFactory, ILicenseInformationFetcher licenseInformationFetcher) : base(log, componentDetector, configuration, sbomConfigs, fileSystemUtils, packageDetailsFactory, licenseInformationFetcher) { } diff --git a/src/Microsoft.Sbom.Api/Executors/SBOMComponentsWalker.cs b/src/Microsoft.Sbom.Api/Executors/SBOMComponentsWalker.cs index 5f434ada..45e93979 100644 --- a/src/Microsoft.Sbom.Api/Executors/SBOMComponentsWalker.cs +++ b/src/Microsoft.Sbom.Api/Executors/SBOMComponentsWalker.cs @@ -5,12 +5,12 @@ using System.Linq; using Microsoft.ComponentDetection.Contracts.BcdeModels; using Microsoft.ComponentDetection.Contracts.TypedComponent; +using Microsoft.Extensions.Logging; using Microsoft.Sbom.Api.PackageDetails; using Microsoft.Sbom.Api.Utils; using Microsoft.Sbom.Common; using Microsoft.Sbom.Common.Config; using Microsoft.Sbom.Extensions; -using ILogger = Serilog.ILogger; namespace Microsoft.Sbom.Api.Executors; @@ -19,7 +19,7 @@ namespace Microsoft.Sbom.Api.Executors; /// public class SBOMComponentsWalker : ComponentDetectionBaseWalker { - public SBOMComponentsWalker(ILogger log, ComponentDetectorCachedExecutor componentDetector, IConfiguration configuration, ISbomConfigProvider sbomConfigs, IFileSystemUtils fileSystemUtils, IPackageDetailsFactory packageDetailsFactory, ILicenseInformationFetcher licenseInformationFetcher) + public SBOMComponentsWalker(ILogger log, ComponentDetectorCachedExecutor componentDetector, IConfiguration configuration, ISbomConfigProvider sbomConfigs, IFileSystemUtils fileSystemUtils, IPackageDetailsFactory packageDetailsFactory, ILicenseInformationFetcher licenseInformationFetcher) : base(log, componentDetector, configuration, sbomConfigs, fileSystemUtils, packageDetailsFactory, licenseInformationFetcher) { } diff --git a/src/Microsoft.Sbom.Api/Executors/SPDXSBOMReaderForExternalDocumentReference.cs b/src/Microsoft.Sbom.Api/Executors/SPDXSBOMReaderForExternalDocumentReference.cs index 003838d2..36857bdb 100644 --- a/src/Microsoft.Sbom.Api/Executors/SPDXSBOMReaderForExternalDocumentReference.cs +++ b/src/Microsoft.Sbom.Api/Executors/SPDXSBOMReaderForExternalDocumentReference.cs @@ -7,6 +7,7 @@ using System.Text.Json; using System.Threading.Channels; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; using Microsoft.Sbom.Api.Entities; using Microsoft.Sbom.Api.Exceptions; using Microsoft.Sbom.Api.Hashing; @@ -16,7 +17,6 @@ using Microsoft.Sbom.Contracts.Enums; using Microsoft.Sbom.Extensions; using Microsoft.Sbom.Extensions.Entities; -using Serilog; using Constants = Microsoft.Sbom.Api.Utils.Constants; using ErrorType = Microsoft.Sbom.Api.Entities.ErrorType; @@ -28,7 +28,7 @@ namespace Microsoft.Sbom.Api.Executors; public class SPDXSBOMReaderForExternalDocumentReference : ISBOMReaderForExternalDocumentReference { private readonly IHashCodeGenerator hashCodeGenerator; - private readonly ILogger log; + private readonly ILogger log; private readonly ISbomConfigProvider sbomConfigs; private readonly ManifestGeneratorProvider manifestGeneratorProvider; private AlgorithmName[] hashAlgorithmNames; @@ -54,7 +54,7 @@ private AlgorithmName[] HashAlgorithmNames public SPDXSBOMReaderForExternalDocumentReference( IHashCodeGenerator hashCodeGenerator, - ILogger log, + ILogger log, ISbomConfigProvider sbomConfigs, ManifestGeneratorProvider manifestGeneratorProvider, IFileSystemUtils fileSystemUtils) @@ -83,7 +83,7 @@ public virtual (ChannelReader results, ChannelRea { if (!file.EndsWith(Constants.SPDXFileExtension, StringComparison.OrdinalIgnoreCase)) { - log.Warning($"The file {file} is not an spdx document."); + log.LogWarning($"The file {file} is not an spdx document."); } else { @@ -97,7 +97,7 @@ public virtual (ChannelReader results, ChannelRea } catch (JsonException e) { - log.Error($"Encountered an error while parsing the external SBOM file {file}: {e.Message}"); + log.LogError($"Encountered an error while parsing the external SBOM file {file}: {e.Message}"); await errors.Writer.WriteAsync(new FileValidationResult { ErrorType = ErrorType.Other, @@ -106,7 +106,7 @@ await errors.Writer.WriteAsync(new FileValidationResult } catch (HashGenerationException e) { - log.Debug($"Encountered an error while generating hash for file {file}: {e.Message}"); + log.LogDebug($"Encountered an error while generating hash for file {file}: {e.Message}"); await errors.Writer.WriteAsync(new FileValidationResult { ErrorType = ErrorType.Other, @@ -115,7 +115,7 @@ await errors.Writer.WriteAsync(new FileValidationResult } catch (Exception e) { - log.Debug($"Encountered an error while generating externalDocumentReferenceInfo from file {file}: {e.Message}"); + log.LogDebug($"Encountered an error while generating externalDocumentReferenceInfo from file {file}: {e.Message}"); await errors.Writer.WriteAsync(new FileValidationResult { ErrorType = ErrorType.Other, diff --git a/src/Microsoft.Sbom.Api/Filters/DownloadedRootPathFilter.cs b/src/Microsoft.Sbom.Api/Filters/DownloadedRootPathFilter.cs index 6ab1526e..adf30f1d 100644 --- a/src/Microsoft.Sbom.Api/Filters/DownloadedRootPathFilter.cs +++ b/src/Microsoft.Sbom.Api/Filters/DownloadedRootPathFilter.cs @@ -5,9 +5,9 @@ using System.Collections.Generic; using System.IO; using System.Linq; +using Microsoft.Extensions.Logging; using Microsoft.Sbom.Common; using Microsoft.Sbom.Common.Config; -using Serilog; namespace Microsoft.Sbom.Api.Filters; @@ -19,7 +19,7 @@ public class DownloadedRootPathFilter : IFilter { private readonly IConfiguration configuration; private readonly IFileSystemUtils fileSystemUtils; - private readonly ILogger logger; + private readonly ILogger logger; private bool skipValidation; private HashSet validPaths; @@ -27,7 +27,7 @@ public class DownloadedRootPathFilter : IFilter public DownloadedRootPathFilter( IConfiguration configuration, IFileSystemUtils fileSystemUtils, - ILogger logger) + ILogger logger) { this.configuration = configuration ?? throw new ArgumentNullException(nameof(configuration)); this.fileSystemUtils = fileSystemUtils ?? throw new ArgumentNullException(nameof(fileSystemUtils)); @@ -74,7 +74,7 @@ public bool IsValid(string filePath) /// public void Init() { - logger.Verbose("Adding root path filter valid paths"); + logger.LogTrace("Adding root path filter valid paths"); skipValidation = true; if (configuration.RootPathFilter != null && !string.IsNullOrWhiteSpace(configuration.RootPathFilter.Value)) @@ -89,7 +89,7 @@ public void Init() foreach (var validPath in validPaths) { - logger.Verbose($"Added valid path {validPath}"); + logger.LogTrace($"Added valid path {validPath}"); } } } diff --git a/src/Microsoft.Sbom.Api/Manifest/Configuration/SbomConfigProvider.cs b/src/Microsoft.Sbom.Api/Manifest/Configuration/SbomConfigProvider.cs index ea6d370a..910f562f 100644 --- a/src/Microsoft.Sbom.Api/Manifest/Configuration/SbomConfigProvider.cs +++ b/src/Microsoft.Sbom.Api/Manifest/Configuration/SbomConfigProvider.cs @@ -5,12 +5,12 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; using Microsoft.Sbom.Api.Metadata; using Microsoft.Sbom.Api.Output.Telemetry; using Microsoft.Sbom.Common.Extensions; using Microsoft.Sbom.Extensions; using Microsoft.Sbom.Extensions.Entities; -using Serilog; namespace Microsoft.Sbom.Api.Manifest.Configuration; @@ -70,13 +70,13 @@ private IReadOnlyDictionary MetadataDictionary private readonly IEnumerable manifestConfigHandlers; private readonly IEnumerable metadataProviders; - private readonly ILogger logger; + private readonly ILogger logger; private readonly IRecorder recorder; public SbomConfigProvider( IEnumerable manifestConfigHandlers, IEnumerable metadataProviders, - ILogger logger, + ILogger logger, IRecorder recorder) { this.manifestConfigHandlers = manifestConfigHandlers ?? throw new ArgumentNullException(nameof(manifestConfigHandlers)); @@ -142,7 +142,7 @@ public object GetMetadata(MetadataKey key) { if (MetadataDictionary.TryGetValue(key, out var value)) { - logger.Debug($"Found value for header {key} in internal metadata."); + logger.LogDebug($"Found value for header {key} in internal metadata."); return value; } @@ -153,7 +153,7 @@ public bool TryGetMetadata(MetadataKey key, out object value) { if (MetadataDictionary.ContainsKey(key)) { - logger.Debug($"Found value for header {key} in internal metadata."); + logger.LogDebug($"Found value for header {key} in internal metadata."); value = MetadataDictionary[key]; return true; } @@ -203,7 +203,7 @@ public string GetSBOMNamespaceUri() return provider.GetDocumentNamespaceUri(); } - logger.Error($"Unable to find any provider to generate the namespace."); + logger.LogError($"Unable to find any provider to generate the namespace."); throw new Exception($"Unable to find any provider to generate the namespace."); } diff --git a/src/Microsoft.Sbom.Api/Output/MetadataBuilder.cs b/src/Microsoft.Sbom.Api/Output/MetadataBuilder.cs index 3b315384..0d6f5add 100644 --- a/src/Microsoft.Sbom.Api/Output/MetadataBuilder.cs +++ b/src/Microsoft.Sbom.Api/Output/MetadataBuilder.cs @@ -3,12 +3,12 @@ using System; using System.Text.Json; +using Microsoft.Extensions.Logging; using Microsoft.Sbom.Api.Manifest; using Microsoft.Sbom.Api.Output.Telemetry; using Microsoft.Sbom.Api.Utils; using Microsoft.Sbom.Extensions; using Microsoft.Sbom.Extensions.Entities; -using Serilog; namespace Microsoft.Sbom.Api.Output; @@ -19,12 +19,12 @@ namespace Microsoft.Sbom.Api.Output; public class MetadataBuilder : IMetadataBuilder { private readonly IManifestGenerator manifestGenerator; - private readonly ILogger logger; + private readonly ILogger logger; private readonly ManifestInfo manifestInfo; private readonly IRecorder recorder; public MetadataBuilder( - ILogger logger, + ILogger logger, ManifestGeneratorProvider manifestGeneratorProvider, ManifestInfo manifestInfo, IRecorder recorder) @@ -44,7 +44,7 @@ public string GetHeaderJsonString(IInternalMetadataProvider internalMetadataProv { using (recorder.TraceEvent(string.Format(Events.MetadataBuilder, manifestInfo))) { - logger.Debug("Building the header object."); + logger.LogDebug("Building the header object."); var headerDictionary = manifestGenerator.GetMetadataDictionary(internalMetadataProvider); return JsonSerializer.Serialize(headerDictionary); } @@ -60,7 +60,7 @@ public bool TryGetFilesArrayHeaderName(out string headerName) catch (NotSupportedException) { headerName = null; - logger.Debug("Files array not suppored on this SBOM format."); + logger.LogDebug("Files array not suppored on this SBOM format."); return false; } } @@ -75,7 +75,7 @@ public bool TryGetPackageArrayHeaderName(out string headerName) catch (NotSupportedException) { headerName = null; - logger.Debug("Packages array not suppored on this SBOM format."); + logger.LogDebug("Packages array not suppored on this SBOM format."); return false; } } @@ -90,7 +90,7 @@ public bool TryGetExternalRefArrayHeaderName(out string headerName) catch (NotSupportedException) { headerName = null; - logger.Debug("External Document Reference array not suppored on this SBOM format."); + logger.LogDebug("External Document Reference array not suppored on this SBOM format."); return false; } } @@ -112,7 +112,7 @@ public bool TryGetRootPackageJson(IInternalMetadataProvider internalMetadataProv catch (NotSupportedException) { generationResult = null; - logger.Debug("Root package serialization not supported on this SBOM format."); + logger.LogDebug("Root package serialization not supported on this SBOM format."); return false; } } @@ -127,7 +127,7 @@ public bool TryGetRelationshipsHeaderName(out string headerName) catch (NotSupportedException) { headerName = null; - logger.Debug("Relationships array are not supported on this SBOM format."); + logger.LogDebug("Relationships array are not supported on this SBOM format."); return false; } } diff --git a/src/Microsoft.Sbom.Api/Output/MetadataBuilderFactory.cs b/src/Microsoft.Sbom.Api/Output/MetadataBuilderFactory.cs index 3372d925..cfd5288a 100644 --- a/src/Microsoft.Sbom.Api/Output/MetadataBuilderFactory.cs +++ b/src/Microsoft.Sbom.Api/Output/MetadataBuilderFactory.cs @@ -7,41 +7,39 @@ using Microsoft.Sbom.Common; using Microsoft.Sbom.Extensions; using Microsoft.Sbom.Extensions.Entities; -using Serilog; namespace Microsoft.Sbom.Api.Output; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + /// /// Builds a object for a given SBOM format. /// public class MetadataBuilderFactory : IMetadataBuilderFactory { - private readonly ILogger logger; private readonly ManifestGeneratorProvider manifestGeneratorProvider; private readonly IRecorder recorder; + private readonly IServiceProvider serviceProvider; public MetadataBuilderFactory( - ILogger logger, ManifestGeneratorProvider manifestGeneratorProvider, - IRecorder recorder) + IRecorder recorder, + IServiceProvider serviceProvider) { - if (logger is null) - { - throw new ArgumentNullException(nameof(logger)); - } - if (manifestGeneratorProvider is null) { throw new ArgumentNullException(nameof(manifestGeneratorProvider)); } - this.logger = logger; this.manifestGeneratorProvider = manifestGeneratorProvider; this.recorder = recorder ?? throw new ArgumentNullException(nameof(recorder)); + this.serviceProvider = serviceProvider; } - public IMetadataBuilder Get(ManifestInfo manifestInfo) - { - return new MetadataBuilder(logger, manifestGeneratorProvider, manifestInfo, recorder); - } + public IMetadataBuilder Get(ManifestInfo manifestInfo) => new MetadataBuilder( + this.serviceProvider.GetRequiredService>(), + this.manifestGeneratorProvider, + manifestInfo, + this.recorder); } diff --git a/src/Microsoft.Sbom.Api/Output/Telemetry/TelemetryRecorder.cs b/src/Microsoft.Sbom.Api/Output/Telemetry/TelemetryRecorder.cs index 0a857266..ff317e82 100644 --- a/src/Microsoft.Sbom.Api/Output/Telemetry/TelemetryRecorder.cs +++ b/src/Microsoft.Sbom.Api/Output/Telemetry/TelemetryRecorder.cs @@ -10,6 +10,7 @@ using System.Text.Json.Serialization; using System.Threading; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; using Microsoft.Sbom.Api.Entities; using Microsoft.Sbom.Api.Entities.Output; using Microsoft.Sbom.Api.Output.Telemetry.Entities; @@ -46,9 +47,9 @@ public class TelemetryRecorder : IRecorder public IConfiguration Configuration { get; } - public ILogger Log { get; } + public ILogger Log { get; } - public TelemetryRecorder(IFileSystemUtils fileSystemUtils, IConfiguration configuration, ILogger log) + public TelemetryRecorder(IFileSystemUtils fileSystemUtils, IConfiguration configuration, ILogger log) { FileSystemUtils = fileSystemUtils ?? throw new ArgumentNullException(nameof(fileSystemUtils)); Configuration = configuration ?? throw new ArgumentNullException(nameof(configuration)); @@ -72,49 +73,28 @@ public static TelemetryRecorder Create(IConfiguration configuration, IFileSystem } /// - /// Method to log telemetry in conditions when the tool is not able to start execution of workflow. + /// Method to log telemetry to the telemetryOutput path in conditions when the tool is not able to start execution of workflow. /// - /// Exception that we want to log. + /// Exception that we want to write to the telemetry file path. public async Task LogException(Exception exception) { - var logger = Log; - if (Log is null) - { - logger = new LoggerConfiguration() - .MinimumLevel.ControlledBy(new LoggingLevelSwitch { MinimumLevel = Configuration.Verbosity.Value }) - .WriteTo.Console(outputTemplate: Constants.LoggerTemplate) - .CreateLogger(); - } - // Convert thrown Exception to list of exceptions for the SBOMTelemetry object. var exceptionList = new List { exception }; - try + // Create the telemetry object. + var telemetry = new SBOMTelemetry { - // Create the telemetry object. - var telemetry = new SBOMTelemetry - { - Result = Result.Failure, - Timings = timingRecorders.Select(t => t.ToTiming()).ToList(), - Switches = this.switches, - Parameters = Configuration, - Exceptions = exceptionList.ToDictionary(k => k.GetType().ToString(), v => v.Message), - }; - - // Log to logger. - logger.Information("Could not start execution of workflow. Logging telemetry {@Telemetry}", telemetry); + Result = Result.Failure, + Timings = timingRecorders.Select(t => t.ToTiming()).ToList(), + Switches = this.switches, + Parameters = Configuration, + Exceptions = exceptionList.ToDictionary(k => k.GetType().ToString(), v => v.Message), + }; - await RecordToFile(telemetry, Configuration.TelemetryFilePath?.Value); - } - catch (Exception e) - { - // We shouldn't fail the main workflow due to some failure on the telemetry generation. - // Just log the result and return silently. - logger.Warning($"Failed to log telemetry. Exception: {e.Message}"); - } + await RecordToFile(telemetry, Configuration.TelemetryFilePath?.Value); } public IList Errors => errors; @@ -326,14 +306,14 @@ public async Task FinalizeAndLogTelemetryAsync() }; // Log to logger. - Log.Debug($"Wrote telemetry object to path {Configuration.TelemetryFilePath?.Value}"); + Log.LogDebug($"Wrote telemetry object to path {Configuration.TelemetryFilePath?.Value}"); if (Configuration.ManifestToolAction == ManifestToolActions.Generate && Configuration.BuildComponentPath?.Value != null && this.totalNumberOfPackages == 0) { - Log.Warning("0 Packages were detected during the {Action} workflow.", Configuration.ManifestToolAction); + Log.LogWarning("0 Packages were detected during the {Action} workflow.", Configuration.ManifestToolAction); } - Log.Information("Finished execution of the {Action} workflow {@Telemetry}", Configuration.ManifestToolAction, telemetry); + Log.LogInformation("Finished execution of the {Action} workflow {@Telemetry}", Configuration.ManifestToolAction, telemetry); await RecordToFile(telemetry, Configuration.TelemetryFilePath?.Value); } @@ -341,7 +321,7 @@ public async Task FinalizeAndLogTelemetryAsync() { // We should'nt fail the main workflow due to some failure on the telemetry generation. // Just log the result and return silently. - Log.Warning($"Failed to log telemetry. Exception: {ex.Message}"); + Log.LogWarning($"Failed to log telemetry. Exception: {ex.Message}"); } } } diff --git a/src/Microsoft.Sbom.Api/PackageDetails/ComponentDetailsUtils/MavenUtils.cs b/src/Microsoft.Sbom.Api/PackageDetails/ComponentDetailsUtils/MavenUtils.cs index dfbf038a..3e97a186 100644 --- a/src/Microsoft.Sbom.Api/PackageDetails/ComponentDetailsUtils/MavenUtils.cs +++ b/src/Microsoft.Sbom.Api/PackageDetails/ComponentDetailsUtils/MavenUtils.cs @@ -7,6 +7,7 @@ using System.Runtime.InteropServices; using System.Xml; using Microsoft.ComponentDetection.Contracts.BcdeModels; +using Microsoft.Extensions.Logging; using Microsoft.Sbom.Api.Exceptions; using Microsoft.Sbom.Api.Output.Telemetry; using Microsoft.Sbom.Common; @@ -20,7 +21,7 @@ namespace Microsoft.Sbom.Api.PackageDetails; public class MavenUtils : IPackageManagerUtils { private readonly IFileSystemUtils fileSystemUtils; - private readonly ILogger log; + private readonly ILogger log; private readonly IRecorder recorder; private static readonly string EnvHomePath = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "HOMEPATH" : "HOME"; @@ -30,7 +31,7 @@ public class MavenUtils : IPackageManagerUtils private bool MavenPackagesPathHasReadPermissions => fileSystemUtils.DirectoryHasReadPermissions(MavenPackagesPath); - public MavenUtils(IFileSystemUtils fileSystemUtils, ILogger log, IRecorder recorder) + public MavenUtils(IFileSystemUtils fileSystemUtils, ILogger log, IRecorder recorder) { this.fileSystemUtils = fileSystemUtils ?? throw new ArgumentNullException(nameof(fileSystemUtils)); this.log = log ?? throw new ArgumentNullException(nameof(log)); @@ -75,7 +76,7 @@ public MavenUtils(IFileSystemUtils fileSystemUtils, ILogger log, IRecorder recor } else { - log.Verbose($"Pom location could not be found at: {pomLocation}"); + log.LogTrace($"Pom location could not be found at: {pomLocation}"); } } @@ -138,7 +139,7 @@ public MavenUtils(IFileSystemUtils fileSystemUtils, ILogger log, IRecorder recor } catch (PackageMetadataParsingException e) { - log.Error("Error encountered while extracting supplier info from pom file. Supplier information may be incomplete.", e); + log.LogError($"Error encountered while extracting supplier info from pom file. Supplier information may be incomplete. {e}"); recorder.RecordMetadataException(e); return null; diff --git a/src/Microsoft.Sbom.Api/PackageDetails/ComponentDetailsUtils/NugetUtils.cs b/src/Microsoft.Sbom.Api/PackageDetails/ComponentDetailsUtils/NugetUtils.cs index 7c5e5890..14dbbf68 100644 --- a/src/Microsoft.Sbom.Api/PackageDetails/ComponentDetailsUtils/NugetUtils.cs +++ b/src/Microsoft.Sbom.Api/PackageDetails/ComponentDetailsUtils/NugetUtils.cs @@ -6,11 +6,11 @@ using System.Linq; using System.Xml; using Microsoft.ComponentDetection.Contracts.BcdeModels; +using Microsoft.Extensions.Logging; using Microsoft.Sbom.Api.Exceptions; using Microsoft.Sbom.Api.Output.Telemetry; using Microsoft.Sbom.Common; using NuGet.Configuration; -using Serilog; namespace Microsoft.Sbom.Api.PackageDetails; @@ -20,12 +20,12 @@ namespace Microsoft.Sbom.Api.PackageDetails; public class NugetUtils : IPackageManagerUtils { private readonly IFileSystemUtils fileSystemUtils; - private readonly ILogger log; + private readonly ILogger log; private readonly IRecorder recorder; private static readonly string NugetPackagesPath = SettingsUtility.GetGlobalPackagesFolder(new NullSettings()); - public NugetUtils(IFileSystemUtils fileSystemUtils, ILogger log, IRecorder recorder) + public NugetUtils(IFileSystemUtils fileSystemUtils, ILogger log, IRecorder recorder) { this.fileSystemUtils = fileSystemUtils ?? throw new ArgumentNullException(nameof(fileSystemUtils)); this.log = log ?? throw new ArgumentNullException(nameof(log)); @@ -55,7 +55,7 @@ public string GetMetadataLocation(ScannedComponent scannedComponent) } else { - log.Verbose($"Nuspec file could not be found at: {nuspecLocation}"); + log.LogTrace($"Nuspec file could not be found at: {nuspecLocation}"); } } @@ -106,7 +106,7 @@ public ParsedPackageInformation ParseMetadata(string nuspecPath) } catch (PackageMetadataParsingException e) { - log.Error("Error encountered while extracting supplier info from nuspec file. Supplier information may be incomplete.", e); + log.LogError($"Error encountered while extracting supplier info from nuspec file. Supplier information may be incomplete. {e}"); recorder.RecordMetadataException(e); return null; diff --git a/src/Microsoft.Sbom.Api/PackageDetails/ComponentDetailsUtils/RubyGemsUtils.cs b/src/Microsoft.Sbom.Api/PackageDetails/ComponentDetailsUtils/RubyGemsUtils.cs index 3087747c..5ebad2d7 100644 --- a/src/Microsoft.Sbom.Api/PackageDetails/ComponentDetailsUtils/RubyGemsUtils.cs +++ b/src/Microsoft.Sbom.Api/PackageDetails/ComponentDetailsUtils/RubyGemsUtils.cs @@ -8,11 +8,10 @@ using System.Runtime.InteropServices; using System.Text.RegularExpressions; using Microsoft.ComponentDetection.Contracts.BcdeModels; +using Microsoft.Extensions.Logging; using Microsoft.Sbom.Api.Exceptions; using Microsoft.Sbom.Api.Output.Telemetry; using Microsoft.Sbom.Common; -using Serilog; -using File = System.IO.File; namespace Microsoft.Sbom.Api.PackageDetails; @@ -25,11 +24,11 @@ public class RubyGemsUtils : IPackageManagerUtils private string rubyGemsPath; private readonly IFileSystemUtils fileSystemUtils; - private readonly ILogger logger; + private readonly ILogger logger; private readonly IRecorder recorder; private readonly IProcessExecutor processExecutor; - public RubyGemsUtils(IFileSystemUtils fileSystemUtils, ILogger logger, IRecorder recorder, IProcessExecutor processExecutor) + public RubyGemsUtils(IFileSystemUtils fileSystemUtils, ILogger logger, IRecorder recorder, IProcessExecutor processExecutor) { this.fileSystemUtils = fileSystemUtils ?? throw new ArgumentNullException(nameof(fileSystemUtils)); this.logger = logger ?? throw new ArgumentNullException(nameof(logger)); @@ -80,7 +79,7 @@ public RubyGemsUtils(IFileSystemUtils fileSystemUtils, ILogger logger, IRecorder } } - logger.Verbose($"Could not find gemspec file for {gemspecFileName}"); + logger.LogTrace($"Could not find gemspec file for {gemspecFileName}"); } return null; @@ -156,7 +155,7 @@ public ParsedPackageInformation ParseMetadata(string gemspecLocation) } catch (PackageMetadataParsingException e) { - logger.Error("Error encountered while extracting supplier info from gemspec file. Supplier information may be incomplete.", e); + logger.LogError($"Error encountered while extracting supplier info from gemspec file. Supplier information may be incomplete. {e}"); recorder.RecordMetadataException(e); return null; @@ -215,7 +214,7 @@ private string FindGemExecutablePath() } catch (Exception e) { - logger.Error("Error encountered while finding gem executable path: ", e); + logger.LogError($"Error encountered while finding gem executable path: {e}"); recorder.RecordMetadataException(e); return null; } @@ -234,7 +233,7 @@ private string GetRubyGemsSpecificationsPath() if (string.IsNullOrEmpty(gemExecutablePath) || !fileSystemUtils.FileExists(gemExecutablePath)) { - logger.Error("Unable to find gem executable."); + logger.LogError("Unable to find gem executable."); return null; } @@ -267,7 +266,7 @@ private string GetRubyGemsSpecificationsPath() } catch (Exception e) { - logger.Error("Error encountered while running 'gem env gempath' command: ", e); + logger.LogError($"Error encountered while running 'gem env gempath' command: {e}"); recorder.RecordMetadataException(e); return null; } diff --git a/src/Microsoft.Sbom.Api/PackageDetails/PackageDetailsFactory.cs b/src/Microsoft.Sbom.Api/PackageDetails/PackageDetailsFactory.cs index 1c17e79c..cb4b3fed 100644 --- a/src/Microsoft.Sbom.Api/PackageDetails/PackageDetailsFactory.cs +++ b/src/Microsoft.Sbom.Api/PackageDetails/PackageDetailsFactory.cs @@ -7,9 +7,9 @@ using System.IO; using Microsoft.ComponentDetection.Contracts.BcdeModels; using Microsoft.ComponentDetection.Contracts.TypedComponent; +using Microsoft.Extensions.Logging; using Microsoft.Sbom.Api.Output.Telemetry; using Microsoft.Sbom.Api.Utils; -using Serilog; namespace Microsoft.Sbom.Api.PackageDetails; @@ -18,13 +18,13 @@ namespace Microsoft.Sbom.Api.PackageDetails; /// public class PackageDetailsFactory : IPackageDetailsFactory { - private readonly ILogger log; + private readonly ILogger log; private readonly IRecorder recorder; private readonly IPackageManagerUtils mavenUtils; private readonly IPackageManagerUtils nugetUtils; private readonly IPackageManagerUtils rubygemUtils; - public PackageDetailsFactory(ILogger log, IRecorder recorder, IPackageManagerUtils mavenUtils, IPackageManagerUtils nugetUtils, IPackageManagerUtils rubygemUtils) + public PackageDetailsFactory(ILogger log, IRecorder recorder, IPackageManagerUtils mavenUtils, IPackageManagerUtils nugetUtils, IPackageManagerUtils rubygemUtils) { this.log = log ?? throw new ArgumentNullException(nameof(log)); this.recorder = recorder ?? throw new ArgumentNullException(nameof(recorder)); @@ -105,7 +105,7 @@ private List GetPackageDetailsLocations(IEnumerable sc break; default: - log.Verbose($"File extension {Path.GetExtension(path)} is not supported for extracting supplier info."); + log.LogTrace($"File extension {Path.GetExtension(path)} is not supported for extracting supplier info."); break; } } @@ -113,7 +113,7 @@ private List GetPackageDetailsLocations(IEnumerable sc if (packageDetailsPaths.Count > 0) { - log.Information($"Found additional information for {packageDetailsDictionary.Count} components out of {packageDetailsPaths.Count} supported components."); + log.LogInformation($"Found additional information for {packageDetailsDictionary.Count} components out of {packageDetailsPaths.Count} supported components."); } recorder.AddToTotalNumberOfPackageDetailsEntries(packageDetailsDictionary.Count); diff --git a/src/Microsoft.Sbom.Api/Providers/EntityToJsonProviderBase.cs b/src/Microsoft.Sbom.Api/Providers/EntityToJsonProviderBase.cs index 0fd38e90..65782d18 100644 --- a/src/Microsoft.Sbom.Api/Providers/EntityToJsonProviderBase.cs +++ b/src/Microsoft.Sbom.Api/Providers/EntityToJsonProviderBase.cs @@ -5,11 +5,11 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Channels; +using Microsoft.Extensions.Logging; using Microsoft.Sbom.Api.Entities; using Microsoft.Sbom.Api.Executors; using Microsoft.Sbom.Common.Config; using Microsoft.Sbom.Extensions; -using Serilog; namespace Microsoft.Sbom.Api.Providers; @@ -29,9 +29,9 @@ public abstract class EntityToJsonProviderBase : ISourcesProvider /// public ChannelUtils ChannelUtils { get; } - public ILogger Log { get; } + public ILogger> Log { get; } - public EntityToJsonProviderBase(IConfiguration configuration, ChannelUtils channelUtils, ILogger logger) + public EntityToJsonProviderBase(IConfiguration configuration, ChannelUtils channelUtils, ILogger> logger) { Configuration = configuration ?? throw new ArgumentNullException(nameof(configuration)); ChannelUtils = channelUtils ?? throw new ArgumentNullException(nameof(channelUtils)); @@ -57,10 +57,10 @@ public EntityToJsonProviderBase(IConfiguration configuration, ChannelUtils chann var (sources, sourceErrors) = GetSourceChannel(); errors.Add(sourceErrors); - Log.Debug($"Splitting the workflow into {Configuration.Parallelism.Value} threads."); + Log.LogDebug($"Splitting the workflow into {Configuration.Parallelism.Value} threads."); var splitSourcesChannels = ChannelUtils.Split(sources, Configuration.Parallelism.Value); - Log.Debug("Running the generation workflow ..."); + Log.LogDebug("Running the generation workflow ..."); foreach (var sourceChannel in splitSourcesChannels) { diff --git a/src/Microsoft.Sbom.Api/Providers/ExternalDocumentReferenceProviders/CGExternalDocumentReferenceProvider.cs b/src/Microsoft.Sbom.Api/Providers/ExternalDocumentReferenceProviders/CGExternalDocumentReferenceProvider.cs index 6b30ce35..ff1b4fe4 100644 --- a/src/Microsoft.Sbom.Api/Providers/ExternalDocumentReferenceProviders/CGExternalDocumentReferenceProvider.cs +++ b/src/Microsoft.Sbom.Api/Providers/ExternalDocumentReferenceProviders/CGExternalDocumentReferenceProvider.cs @@ -6,14 +6,13 @@ using System.Linq; using System.Threading.Channels; using Microsoft.ComponentDetection.Contracts.BcdeModels; +using Microsoft.Extensions.Logging; using Microsoft.Sbom.Api.Converters; using Microsoft.Sbom.Api.Entities; -using Microsoft.Sbom.Api.Exceptions; using Microsoft.Sbom.Api.Executors; using Microsoft.Sbom.Api.Utils; using Microsoft.Sbom.Common.Config; using Microsoft.Sbom.Extensions; -using Serilog; namespace Microsoft.Sbom.Api.Providers.ExternalDocumentReferenceProviders; @@ -34,7 +33,7 @@ public class CGExternalDocumentReferenceProvider : EntityToJsonProviderBase logger, ComponentToExternalReferenceInfoConverter componentToExternalReferenceInfoConverter, ExternalDocumentReferenceWriter externalDocumentReferenceWriter, SBOMComponentsWalker sbomComponentsWalker, @@ -51,7 +50,7 @@ public override bool IsSupported(ProviderType providerType) { if (providerType == ProviderType.ExternalDocumentReference) { - Log.Debug($"Using the {nameof(CGExternalDocumentReferenceProvider)} provider for the external documents workflow."); + Log.LogDebug($"Using the {nameof(CGExternalDocumentReferenceProvider)} provider for the external documents workflow."); return true; } diff --git a/src/Microsoft.Sbom.Api/Providers/ExternalDocumentReferenceProviders/ExternalDocumentReferenceProvider.cs b/src/Microsoft.Sbom.Api/Providers/ExternalDocumentReferenceProviders/ExternalDocumentReferenceProvider.cs index 80d60cdb..811b61a5 100644 --- a/src/Microsoft.Sbom.Api/Providers/ExternalDocumentReferenceProviders/ExternalDocumentReferenceProvider.cs +++ b/src/Microsoft.Sbom.Api/Providers/ExternalDocumentReferenceProviders/ExternalDocumentReferenceProvider.cs @@ -5,12 +5,12 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Channels; +using Microsoft.Extensions.Logging; using Microsoft.Sbom.Api.Entities; using Microsoft.Sbom.Api.Executors; using Microsoft.Sbom.Api.Utils; using Microsoft.Sbom.Common.Config; using Microsoft.Sbom.Extensions; -using Serilog; namespace Microsoft.Sbom.Api.Providers.ExternalDocumentReferenceProviders; @@ -31,7 +31,7 @@ public class ExternalDocumentReferenceProvider : EntityToJsonProviderBase logger, FileListEnumerator listWalker, ISBOMReaderForExternalDocumentReference spdxSbomReaderForExternalDocumentReference, ExternalDocumentReferenceWriter externalDocumentReferenceWriter, @@ -48,7 +48,7 @@ public override bool IsSupported(ProviderType providerType) { if (providerType == ProviderType.ExternalDocumentReference && !string.IsNullOrWhiteSpace(Configuration.ExternalDocumentReferenceListFile?.Value)) { - Log.Debug($"Using the {nameof(ExternalDocumentReferenceProvider)} provider for the external documents workflow."); + Log.LogDebug($"Using the {nameof(ExternalDocumentReferenceProvider)} provider for the external documents workflow."); return true; } diff --git a/src/Microsoft.Sbom.Api/Providers/FilesProviders/CGScannedExternalDocumentReferenceFileProvider.cs b/src/Microsoft.Sbom.Api/Providers/FilesProviders/CGScannedExternalDocumentReferenceFileProvider.cs index 1d373376..9e083784 100644 --- a/src/Microsoft.Sbom.Api/Providers/FilesProviders/CGScannedExternalDocumentReferenceFileProvider.cs +++ b/src/Microsoft.Sbom.Api/Providers/FilesProviders/CGScannedExternalDocumentReferenceFileProvider.cs @@ -5,14 +5,13 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Channels; +using Microsoft.Extensions.Logging; using Microsoft.Sbom.Api.Converters; using Microsoft.Sbom.Api.Entities; -using Microsoft.Sbom.Api.Exceptions; using Microsoft.Sbom.Api.Executors; using Microsoft.Sbom.Api.Utils; using Microsoft.Sbom.Common.Config; using Microsoft.Sbom.Extensions; -using Serilog; namespace Microsoft.Sbom.Api.Providers.FilesProviders; @@ -33,7 +32,7 @@ public class CGScannedExternalDocumentReferenceFileProvider : PathBasedFileToJso public CGScannedExternalDocumentReferenceFileProvider( IConfiguration configuration, ChannelUtils channelUtils, - ILogger log, + ILogger log, FileHasher fileHasher, ManifestFolderFilterer fileFilterer, FileInfoWriter fileHashWriter, @@ -54,7 +53,7 @@ public override bool IsSupported(ProviderType providerType) { if (providerType == ProviderType.Files) { - Log.Debug($"Using the {nameof(CGScannedExternalDocumentReferenceFileProvider)} provider for the files workflow."); + Log.LogDebug($"Using the {nameof(CGScannedExternalDocumentReferenceFileProvider)} provider for the files workflow."); return true; } diff --git a/src/Microsoft.Sbom.Api/Providers/FilesProviders/DirectoryTraversingFileToJsonProvider.cs b/src/Microsoft.Sbom.Api/Providers/FilesProviders/DirectoryTraversingFileToJsonProvider.cs index fb347a73..ec2f9e61 100644 --- a/src/Microsoft.Sbom.Api/Providers/FilesProviders/DirectoryTraversingFileToJsonProvider.cs +++ b/src/Microsoft.Sbom.Api/Providers/FilesProviders/DirectoryTraversingFileToJsonProvider.cs @@ -4,12 +4,12 @@ using System; using System.Collections.Generic; using System.Threading.Channels; +using Microsoft.Extensions.Logging; using Microsoft.Sbom.Api.Entities; using Microsoft.Sbom.Api.Executors; using Microsoft.Sbom.Api.Utils; using Microsoft.Sbom.Common.Config; using Microsoft.Sbom.Extensions; -using Serilog; namespace Microsoft.Sbom.Api.Providers.FilesProviders; @@ -23,7 +23,7 @@ public class DirectoryTraversingFileToJsonProvider : PathBasedFileToJsonProvider public DirectoryTraversingFileToJsonProvider( IConfiguration configuration, ChannelUtils channelUtils, - ILogger log, + ILogger log, FileHasher fileHasher, ManifestFolderFilterer fileFilterer, FileInfoWriter fileHashWriter, @@ -42,7 +42,7 @@ public override bool IsSupported(ProviderType providerType) // Thus, this condition should be to check that all the remaining configurations for file inputs are null. if (string.IsNullOrWhiteSpace(Configuration.BuildListFile?.Value) && Configuration.FilesList?.Value == null) { - Log.Debug($"Using the {nameof(DirectoryTraversingFileToJsonProvider)} provider for the files workflow."); + Log.LogDebug($"Using the {nameof(DirectoryTraversingFileToJsonProvider)} provider for the files workflow."); return true; } } diff --git a/src/Microsoft.Sbom.Api/Providers/FilesProviders/ExternalDocumentReferenceFileProvider.cs b/src/Microsoft.Sbom.Api/Providers/FilesProviders/ExternalDocumentReferenceFileProvider.cs index bd4dae1b..36b8af6f 100644 --- a/src/Microsoft.Sbom.Api/Providers/FilesProviders/ExternalDocumentReferenceFileProvider.cs +++ b/src/Microsoft.Sbom.Api/Providers/FilesProviders/ExternalDocumentReferenceFileProvider.cs @@ -4,12 +4,12 @@ using System; using System.Collections.Generic; using System.Threading.Channels; +using Microsoft.Extensions.Logging; using Microsoft.Sbom.Api.Entities; using Microsoft.Sbom.Api.Executors; using Microsoft.Sbom.Api.Utils; using Microsoft.Sbom.Common.Config; using Microsoft.Sbom.Extensions; -using Serilog; namespace Microsoft.Sbom.Api.Providers.FilesProviders; @@ -24,7 +24,7 @@ public class ExternalDocumentReferenceFileProvider : PathBasedFileToJsonProvider public ExternalDocumentReferenceFileProvider( IConfiguration configuration, ChannelUtils channelUtils, - ILogger log, + ILogger log, FileHasher fileHasher, ManifestFolderFilterer fileFilterer, FileInfoWriter fileHashWriter, @@ -39,7 +39,7 @@ public override bool IsSupported(ProviderType providerType) { if (providerType == ProviderType.Files && !string.IsNullOrWhiteSpace(Configuration.ExternalDocumentReferenceListFile?.Value)) { - Log.Debug($"Using the {nameof(ExternalDocumentReferenceFileProvider)} provider for the files workflow."); + Log.LogDebug($"Using the {nameof(ExternalDocumentReferenceFileProvider)} provider for the files workflow."); return true; } diff --git a/src/Microsoft.Sbom.Api/Providers/FilesProviders/FileListBasedFileToJsonProvider.cs b/src/Microsoft.Sbom.Api/Providers/FilesProviders/FileListBasedFileToJsonProvider.cs index a8ffe8b7..08414150 100644 --- a/src/Microsoft.Sbom.Api/Providers/FilesProviders/FileListBasedFileToJsonProvider.cs +++ b/src/Microsoft.Sbom.Api/Providers/FilesProviders/FileListBasedFileToJsonProvider.cs @@ -4,12 +4,12 @@ using System; using System.Collections.Generic; using System.Threading.Channels; +using Microsoft.Extensions.Logging; using Microsoft.Sbom.Api.Entities; using Microsoft.Sbom.Api.Executors; using Microsoft.Sbom.Api.Utils; using Microsoft.Sbom.Common.Config; using Microsoft.Sbom.Extensions; -using Serilog; namespace Microsoft.Sbom.Api.Providers.FilesProviders; @@ -21,7 +21,7 @@ public class FileListBasedFileToJsonProvider : PathBasedFileToJsonProviderBase { private readonly FileListEnumerator listWalker; - public FileListBasedFileToJsonProvider(IConfiguration configuration, ChannelUtils channelUtils, ILogger log, FileHasher fileHasher, ManifestFolderFilterer fileFilterer, FileInfoWriter fileHashWriter, InternalSBOMFileInfoDeduplicator internalSBOMFileInfoDeduplicator, FileListEnumerator listWalker) + public FileListBasedFileToJsonProvider(IConfiguration configuration, ChannelUtils channelUtils, ILogger log, FileHasher fileHasher, ManifestFolderFilterer fileFilterer, FileInfoWriter fileHashWriter, InternalSBOMFileInfoDeduplicator internalSBOMFileInfoDeduplicator, FileListEnumerator listWalker) : base(configuration, channelUtils, log, fileHasher, fileFilterer, fileHashWriter, internalSBOMFileInfoDeduplicator) { this.listWalker = listWalker ?? throw new ArgumentNullException(nameof(listWalker)); @@ -34,7 +34,7 @@ public override bool IsSupported(ProviderType providerType) // Return true only if the BuildListFile parameter is provided. if (!string.IsNullOrWhiteSpace(Configuration.BuildListFile?.Value)) { - Log.Debug($"Using the {nameof(FileListBasedFileToJsonProvider)} provider for the files workflow."); + Log.LogDebug($"Using the {nameof(FileListBasedFileToJsonProvider)} provider for the files workflow."); return true; } } diff --git a/src/Microsoft.Sbom.Api/Providers/FilesProviders/FileToJsonProviderBase.cs b/src/Microsoft.Sbom.Api/Providers/FilesProviders/FileToJsonProviderBase.cs index 2bb51413..452beed0 100644 --- a/src/Microsoft.Sbom.Api/Providers/FilesProviders/FileToJsonProviderBase.cs +++ b/src/Microsoft.Sbom.Api/Providers/FilesProviders/FileToJsonProviderBase.cs @@ -5,11 +5,11 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Channels; +using Microsoft.Extensions.Logging; using Microsoft.Sbom.Api.Entities; using Microsoft.Sbom.Api.Executors; using Microsoft.Sbom.Common.Config; using Microsoft.Sbom.Extensions; -using Serilog; namespace Microsoft.Sbom.Api.Providers.FilesProviders; @@ -22,11 +22,11 @@ public abstract class FileToJsonProviderBase : ISourcesProvider { private readonly IConfiguration configuration; - private readonly ILogger log; + private readonly ILogger> log; private readonly ChannelUtils channelUtils; - public FileToJsonProviderBase(IConfiguration configuration, ILogger log, ChannelUtils channelUtils) + public FileToJsonProviderBase(IConfiguration configuration, ILogger> log, ChannelUtils channelUtils) { this.configuration = configuration ?? throw new ArgumentNullException(nameof(configuration)); this.log = log ?? throw new ArgumentNullException(nameof(log)); @@ -42,10 +42,10 @@ public FileToJsonProviderBase(IConfiguration configuration, ILogger log, Channel var (files, dirErrors) = GetFilesChannel(); errors.Add(dirErrors); - log.Debug($"Splitting the workflow into {configuration.Parallelism.Value} threads."); + log.LogDebug($"Splitting the workflow into {configuration.Parallelism.Value} threads."); var splitFilesChannels = channelUtils.Split(files, configuration.Parallelism.Value); - log.Debug("Running the files generation workflow ..."); + log.LogDebug("Running the files generation workflow ..."); foreach (var fileChannel in splitFilesChannels) { var (jsonDoc, convertErrors) = ConvertToJson(fileChannel, requiredConfigs); diff --git a/src/Microsoft.Sbom.Api/Providers/FilesProviders/PathBasedFileToJsonProviderBase.cs b/src/Microsoft.Sbom.Api/Providers/FilesProviders/PathBasedFileToJsonProviderBase.cs index 441745e5..7904908f 100644 --- a/src/Microsoft.Sbom.Api/Providers/FilesProviders/PathBasedFileToJsonProviderBase.cs +++ b/src/Microsoft.Sbom.Api/Providers/FilesProviders/PathBasedFileToJsonProviderBase.cs @@ -5,6 +5,7 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Channels; +using Microsoft.Extensions.Logging; using Microsoft.Sbom.Api.Entities; using Microsoft.Sbom.Api.Executors; using Microsoft.Sbom.Api.Utils; @@ -30,7 +31,7 @@ public abstract class PathBasedFileToJsonProviderBase : EntityToJsonProviderBase public PathBasedFileToJsonProviderBase( IConfiguration configuration, ChannelUtils channelUtils, - Serilog.ILogger log, + ILogger log, FileHasher fileHasher, ManifestFolderFilterer fileFilterer, FileInfoWriter fileHashWriter, diff --git a/src/Microsoft.Sbom.Api/Providers/FilesProviders/SBOMFileBasedFileToJsonProvider.cs b/src/Microsoft.Sbom.Api/Providers/FilesProviders/SBOMFileBasedFileToJsonProvider.cs index 2a455274..d71915c3 100644 --- a/src/Microsoft.Sbom.Api/Providers/FilesProviders/SBOMFileBasedFileToJsonProvider.cs +++ b/src/Microsoft.Sbom.Api/Providers/FilesProviders/SBOMFileBasedFileToJsonProvider.cs @@ -5,13 +5,13 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Channels; +using Microsoft.Extensions.Logging; using Microsoft.Sbom.Api.Entities; using Microsoft.Sbom.Api.Executors; using Microsoft.Sbom.Api.Utils; using Microsoft.Sbom.Common.Config; using Microsoft.Sbom.Contracts; using Microsoft.Sbom.Extensions; -using Serilog; namespace Microsoft.Sbom.Api.Providers.FilesProviders; @@ -29,7 +29,7 @@ public class SbomFileBasedFileToJsonProvider : EntityToJsonProviderBase logger, FileInfoWriter fileHashWriter, SbomFileToFileInfoConverter sbomFileToFileInfoConverter, InternalSBOMFileInfoDeduplicator fileInfo) @@ -51,7 +51,7 @@ public override bool IsSupported(ProviderType providerType) { if (Configuration.FilesList?.Value != null && string.IsNullOrWhiteSpace(Configuration.BuildListFile?.Value)) { - Log.Debug($"Using the {nameof(SbomFileBasedFileToJsonProvider)} provider for the files workflow."); + Log.LogDebug($"Using the {nameof(SbomFileBasedFileToJsonProvider)} provider for the files workflow."); return true; } } diff --git a/src/Microsoft.Sbom.Api/Providers/PackagesProviders/CGScannedPackagesProvider.cs b/src/Microsoft.Sbom.Api/Providers/PackagesProviders/CGScannedPackagesProvider.cs index c1512efd..89fb7068 100644 --- a/src/Microsoft.Sbom.Api/Providers/PackagesProviders/CGScannedPackagesProvider.cs +++ b/src/Microsoft.Sbom.Api/Providers/PackagesProviders/CGScannedPackagesProvider.cs @@ -6,12 +6,12 @@ using System.Linq; using System.Threading.Channels; using Microsoft.ComponentDetection.Contracts.BcdeModels; +using Microsoft.Extensions.Logging; using Microsoft.Sbom.Api.Entities; using Microsoft.Sbom.Api.Executors; using Microsoft.Sbom.Api.PackageDetails; using Microsoft.Sbom.Common.Config; using Microsoft.Sbom.Extensions; -using Serilog; namespace Microsoft.Sbom.Api.Providers.PackagesProviders; @@ -29,7 +29,7 @@ public class CGScannedPackagesProvider : CommonPackagesProvider logger, ISbomConfigProvider sbomConfigs, PackageInfoJsonWriter packageInfoJsonWriter, ComponentToPackageInfoConverter packageInfoConverter, @@ -50,7 +50,7 @@ public override bool IsSupported(ProviderType providerType) if (Configuration.PackagesList?.Value == null) { // If no other packages providers are present, use this one. - Log.Debug($"Using the {nameof(CGScannedPackagesProvider)} provider for the packages workflow."); + Log.LogDebug($"Using the {nameof(CGScannedPackagesProvider)} provider for the packages workflow."); return true; } } diff --git a/src/Microsoft.Sbom.Api/Providers/PackagesProviders/CommonPackagesProvider.cs b/src/Microsoft.Sbom.Api/Providers/PackagesProviders/CommonPackagesProvider.cs index ec9d3c9a..596bde85 100644 --- a/src/Microsoft.Sbom.Api/Providers/PackagesProviders/CommonPackagesProvider.cs +++ b/src/Microsoft.Sbom.Api/Providers/PackagesProviders/CommonPackagesProvider.cs @@ -5,6 +5,7 @@ using System.Collections.Generic; using System.Threading.Channels; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; using Microsoft.Sbom.Api.Entities; using Microsoft.Sbom.Api.Executors; using Microsoft.Sbom.Api.PackageDetails; @@ -12,7 +13,6 @@ using Microsoft.Sbom.Contracts; using Microsoft.Sbom.Extensions; using Microsoft.Sbom.Extensions.Entities; -using Serilog; namespace Microsoft.Sbom.Api.Providers.PackagesProviders; @@ -29,7 +29,7 @@ public abstract class CommonPackagesProvider : EntityToJsonProviderBase protected CommonPackagesProvider( IConfiguration configuration, ChannelUtils channelUtils, - ILogger logger, + ILogger> logger, ISbomConfigProvider sbomConfigs, PackageInfoJsonWriter packageInfoJsonWriter, IPackageDetailsFactory packageDetailsFactory, @@ -55,7 +55,7 @@ private Channel GetCommonPackages() if (sbomConfigs.TryGetMetadata(MetadataKey.ImageOS, out object imageOsObj) && sbomConfigs.TryGetMetadata(MetadataKey.ImageVersion, out object imageVersionObj)) { - Log.Debug($"Adding the image OS package to the packages list as a dependency."); + Log.LogDebug($"Adding the image OS package to the packages list as a dependency."); var name = $"Azure Pipelines Hosted Image {imageOsObj}"; await packageInfos.Writer.WriteAsync(new SbomPackage() { diff --git a/src/Microsoft.Sbom.Api/Providers/PackagesProviders/SBOMPackagesProvider.cs b/src/Microsoft.Sbom.Api/Providers/PackagesProviders/SBOMPackagesProvider.cs index c24fcef1..ec161ae1 100644 --- a/src/Microsoft.Sbom.Api/Providers/PackagesProviders/SBOMPackagesProvider.cs +++ b/src/Microsoft.Sbom.Api/Providers/PackagesProviders/SBOMPackagesProvider.cs @@ -4,13 +4,13 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Channels; +using Microsoft.Extensions.Logging; using Microsoft.Sbom.Api.Entities; using Microsoft.Sbom.Api.Executors; using Microsoft.Sbom.Api.PackageDetails; using Microsoft.Sbom.Common.Config; using Microsoft.Sbom.Contracts; using Microsoft.Sbom.Extensions; -using Serilog; namespace Microsoft.Sbom.Api.Providers.PackagesProviders; @@ -22,7 +22,7 @@ public class SBOMPackagesProvider : CommonPackagesProvider public SBOMPackagesProvider( IConfiguration configuration, ChannelUtils channelUtils, - ILogger logger, + ILogger logger, ISbomConfigProvider sbomConfigs, PackageInfoJsonWriter packageInfoJsonWriter, IPackageDetailsFactory packageDetailsFactory, @@ -37,7 +37,7 @@ public override bool IsSupported(ProviderType providerType) { if (Configuration.PackagesList?.Value != null) { - Log.Debug($"Using the {nameof(SBOMPackagesProvider)} provider for the packages workflow."); + Log.LogDebug($"Using the {nameof(SBOMPackagesProvider)} provider for the packages workflow."); return true; } } diff --git a/src/Microsoft.Sbom.Api/Utils/ComponentDetectorCachedExecutor.cs b/src/Microsoft.Sbom.Api/Utils/ComponentDetectorCachedExecutor.cs index 73dce9f2..d1ed7a4c 100644 --- a/src/Microsoft.Sbom.Api/Utils/ComponentDetectorCachedExecutor.cs +++ b/src/Microsoft.Sbom.Api/Utils/ComponentDetectorCachedExecutor.cs @@ -1,27 +1,27 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +namespace Microsoft.Sbom.Api.Utils; + using System; using System.Collections.Concurrent; using System.Threading.Tasks; using Microsoft.ComponentDetection.Contracts.BcdeModels; using Microsoft.ComponentDetection.Orchestrator.Commands; -using Serilog; +using Microsoft.Extensions.Logging; using Spectre.Console.Cli; -namespace Microsoft.Sbom.Api.Utils; - /// /// Wrapper class for a component detector that caches CD execution results with the same arguments. /// The main use case for it is to reuse scanned component results across different providers (e.g packages, external document refs). /// public class ComponentDetectorCachedExecutor { - private readonly ILogger log; + private readonly ILogger log; private readonly IComponentDetector detector; private ConcurrentDictionary results; - public ComponentDetectorCachedExecutor(ILogger log, IComponentDetector detector) + public ComponentDetectorCachedExecutor(ILogger log, IComponentDetector detector) { this.log = log ?? throw new ArgumentNullException(nameof(log)); this.detector = detector ?? throw new ArgumentNullException(nameof(detector)); @@ -45,7 +45,7 @@ public virtual async Task ScanAsync(ScanSettings args) if (results.ContainsKey(scanSettingsHash)) { - log.Debug("Using cached CD scan result for the call with the same arguments"); + log.LogDebug("Using cached CD scan result for the call with the same arguments"); return results[scanSettingsHash]; } diff --git a/src/Microsoft.Sbom.Api/Workflows/Helpers/ExternalDocumentReferenceGenerator.cs b/src/Microsoft.Sbom.Api/Workflows/Helpers/ExternalDocumentReferenceGenerator.cs index 997bf8ad..a712f5fe 100644 --- a/src/Microsoft.Sbom.Api/Workflows/Helpers/ExternalDocumentReferenceGenerator.cs +++ b/src/Microsoft.Sbom.Api/Workflows/Helpers/ExternalDocumentReferenceGenerator.cs @@ -5,13 +5,13 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; using Microsoft.Sbom.Api.Entities; using Microsoft.Sbom.Api.Manifest.Configuration; using Microsoft.Sbom.Api.Output.Telemetry; using Microsoft.Sbom.Api.Providers; using Microsoft.Sbom.Api.Utils; using Microsoft.Sbom.Extensions; -using Serilog; namespace Microsoft.Sbom.Api.Workflows.Helpers; @@ -20,7 +20,7 @@ namespace Microsoft.Sbom.Api.Workflows.Helpers; /// public class ExternalDocumentReferenceGenerator : IJsonArrayGenerator { - private readonly ILogger log; + private readonly ILogger log; private readonly ISbomConfigProvider sbomConfigs; @@ -29,7 +29,7 @@ public class ExternalDocumentReferenceGenerator : IJsonArrayGenerator log, ISbomConfigProvider sbomConfigs, IEnumerable sourcesProviders, IRecorder recorder) @@ -50,7 +50,7 @@ public async Task> GenerateAsync() .Where(s => s.IsSupported(ProviderType.ExternalDocumentReference)); if (!sourcesProviders.Any()) { - log.Debug($"No source providers found for {ProviderType.ExternalDocumentReference}"); + log.LogDebug($"No source providers found for {ProviderType.ExternalDocumentReference}"); return totalErrors; } diff --git a/src/Microsoft.Sbom.Api/Workflows/Helpers/FileArrayGenerator.cs b/src/Microsoft.Sbom.Api/Workflows/Helpers/FileArrayGenerator.cs index 7ea4754e..6f588c6f 100644 --- a/src/Microsoft.Sbom.Api/Workflows/Helpers/FileArrayGenerator.cs +++ b/src/Microsoft.Sbom.Api/Workflows/Helpers/FileArrayGenerator.cs @@ -5,12 +5,12 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; using Microsoft.Sbom.Api.Entities; using Microsoft.Sbom.Api.Output.Telemetry; using Microsoft.Sbom.Api.Providers; using Microsoft.Sbom.Api.Utils; using Microsoft.Sbom.Extensions; -using ILogger = Serilog.ILogger; namespace Microsoft.Sbom.Api.Workflows.Helpers; @@ -25,13 +25,13 @@ public class FileArrayGenerator : IJsonArrayGenerator private readonly IRecorder recorder; - private readonly ILogger logger; + private readonly ILogger logger; public FileArrayGenerator( ISbomConfigProvider sbomConfigs, IEnumerable sourcesProviders, IRecorder recorder, - ILogger logger) + ILogger logger) { this.sbomConfigs = sbomConfigs ?? throw new ArgumentNullException(nameof(sbomConfigs)); this.sourcesProviders = sourcesProviders ?? throw new ArgumentNullException(nameof(sourcesProviders)); @@ -66,7 +66,7 @@ public async Task> GenerateAsync() { config.JsonSerializer.StartJsonArray(filesArrayHeaderName); filesArraySupportingSBOMs.Add(config); - this.logger.Verbose("Started writing files array for {configFile}.", config.ManifestJsonFilePath); + this.logger.LogTrace("Started writing files array for {ConfigFile}.", config.ManifestJsonFilePath); } } diff --git a/src/Microsoft.Sbom.Api/Workflows/Helpers/FilesValidator.cs b/src/Microsoft.Sbom.Api/Workflows/Helpers/FilesValidator.cs index 87cc1cb9..190cea39 100644 --- a/src/Microsoft.Sbom.Api/Workflows/Helpers/FilesValidator.cs +++ b/src/Microsoft.Sbom.Api/Workflows/Helpers/FilesValidator.cs @@ -6,6 +6,7 @@ using System.Linq; using System.Threading.Channels; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; using Microsoft.Sbom.Api.Entities; using Microsoft.Sbom.Api.Executors; using Microsoft.Sbom.Api.Manifest.FileHashes; @@ -25,7 +26,7 @@ public class FilesValidator private readonly DirectoryWalker directoryWalker; private readonly IConfiguration configuration; private readonly ChannelUtils channelUtils = new(); - private readonly ILogger log; + private readonly ILogger log; private readonly FileHasher fileHasher; private readonly ManifestFolderFilterer fileFilterer; private readonly ConcurrentSha256HashValidator hashValidator; @@ -37,7 +38,7 @@ public class FilesValidator public FilesValidator( DirectoryWalker directoryWalker, IConfiguration configuration, - ILogger log, + ILogger log, FileHasher fileHasher, ManifestFolderFilterer fileFilterer, ConcurrentSha256HashValidator hashValidator, @@ -125,10 +126,10 @@ public FilesValidator( var (files, dirErrors) = directoryWalker.GetFilesRecursively(configuration.BuildDropPath.Value); errors.Add(dirErrors); - log.Debug($"Splitting the workflow into {configuration.Parallelism.Value} threads."); + log.LogDebug($"Splitting the workflow into {configuration.Parallelism.Value} threads."); var splitFilesChannels = channelUtils.Split(files, configuration.Parallelism.Value); - log.Debug("Waiting for the workflow to finish..."); + log.LogDebug("Waiting for the workflow to finish..."); foreach (var fileChannel in splitFilesChannels) { // Filter files @@ -157,10 +158,10 @@ public FilesValidator( var (sbomFiles, sbomFileErrors) = enumeratorChannel.Enumerate(() => files.Select(f => f.ToSbomFile())); errors.Add(sbomFileErrors); - log.Debug($"Splitting the workflow into {configuration.Parallelism.Value} threads."); + log.LogDebug($"Splitting the workflow into {configuration.Parallelism.Value} threads."); var splitFilesChannels = channelUtils.Split(sbomFiles, configuration.Parallelism.Value); - log.Debug("Waiting for the workflow to finish..."); + log.LogDebug("Waiting for the workflow to finish..."); foreach (var fileChannel in splitFilesChannels) { // Convert files to internal SBOM format. diff --git a/src/Microsoft.Sbom.Api/Workflows/Helpers/PackageArrayGenerator.cs b/src/Microsoft.Sbom.Api/Workflows/Helpers/PackageArrayGenerator.cs index 9d71dd86..caba7930 100644 --- a/src/Microsoft.Sbom.Api/Workflows/Helpers/PackageArrayGenerator.cs +++ b/src/Microsoft.Sbom.Api/Workflows/Helpers/PackageArrayGenerator.cs @@ -5,13 +5,12 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; using Microsoft.Sbom.Api.Entities; using Microsoft.Sbom.Api.Output.Telemetry; using Microsoft.Sbom.Api.Providers; using Microsoft.Sbom.Api.Utils; using Microsoft.Sbom.Extensions; -using Microsoft.Sbom.Extensions.Entities; -using Serilog; namespace Microsoft.Sbom.Api.Workflows.Helpers; @@ -20,7 +19,7 @@ namespace Microsoft.Sbom.Api.Workflows.Helpers; /// public class PackageArrayGenerator : IJsonArrayGenerator { - private readonly ILogger log; + private readonly ILogger log; private readonly ISbomConfigProvider sbomConfigs; @@ -29,7 +28,7 @@ public class PackageArrayGenerator : IJsonArrayGenerator private readonly IRecorder recorder; public PackageArrayGenerator( - ILogger log, + ILogger log, ISbomConfigProvider sbomConfigs, IEnumerable sourcesProviders, IRecorder recorder) @@ -74,10 +73,10 @@ public async Task> GenerateAsync() if (totalJsonDocumentsWritten == 0) { - log.Warning($"There were no packages detected during the generation workflow."); + log.LogWarning($"There were no packages detected during the generation workflow."); } - log.Debug($"Wrote {totalJsonDocumentsWritten} package elements in the SBOM."); + log.LogDebug($"Wrote {totalJsonDocumentsWritten} package elements in the SBOM."); // +1 is added to the totalJsonDocumentsWritten to account for the root package of the SBOM. recorder.RecordTotalNumberOfPackages(totalJsonDocumentsWritten + 1); diff --git a/src/Microsoft.Sbom.Api/Workflows/Helpers/RelationshipsArrayGenerator.cs b/src/Microsoft.Sbom.Api/Workflows/Helpers/RelationshipsArrayGenerator.cs index 74ac2cd5..bb29c788 100644 --- a/src/Microsoft.Sbom.Api/Workflows/Helpers/RelationshipsArrayGenerator.cs +++ b/src/Microsoft.Sbom.Api/Workflows/Helpers/RelationshipsArrayGenerator.cs @@ -5,13 +5,13 @@ using System.Text.Json; using System.Threading.Channels; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; using Microsoft.Sbom.Api.Entities; using Microsoft.Sbom.Api.Executors; using Microsoft.Sbom.Api.Output.Telemetry; using Microsoft.Sbom.Api.Utils; using Microsoft.Sbom.Extensions; using Microsoft.Sbom.Extensions.Entities; -using Serilog; namespace Microsoft.Sbom.Api.Workflows.Helpers; @@ -24,7 +24,7 @@ public class RelationshipsArrayGenerator : IJsonArrayGenerator log; private readonly ISbomConfigProvider sbomConfigs; @@ -33,7 +33,7 @@ public class RelationshipsArrayGenerator : IJsonArrayGenerator log, ISbomConfigProvider sbomConfigs, IRecorder recorder) { @@ -105,7 +105,7 @@ public async Task> GenerateAsync() sbomConfig.JsonSerializer.Write(jsonDoc); } - log.Debug($"Wrote {count} relationship elements in the SBOM."); + log.LogDebug($"Wrote {count} relationship elements in the SBOM."); // Write the end of the array. sbomConfig.JsonSerializer.EndJsonArray(); diff --git a/src/Microsoft.Sbom.Api/Workflows/SBOMGenerationWorkflow.cs b/src/Microsoft.Sbom.Api/Workflows/SBOMGenerationWorkflow.cs index 083107ec..c2732e6b 100644 --- a/src/Microsoft.Sbom.Api/Workflows/SBOMGenerationWorkflow.cs +++ b/src/Microsoft.Sbom.Api/Workflows/SBOMGenerationWorkflow.cs @@ -6,6 +6,7 @@ using System.IO; using System.Linq; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; using Microsoft.Sbom.Api.Entities; using Microsoft.Sbom.Api.Exceptions; using Microsoft.Sbom.Api.Hashing.Algorithms; @@ -16,7 +17,6 @@ using Microsoft.Sbom.Common.Config; using Microsoft.Sbom.Extensions; using PowerArgs; -using Serilog; using Constants = Microsoft.Sbom.Api.Utils.Constants; namespace Microsoft.Sbom.Api.Workflows; @@ -31,7 +31,7 @@ public class SbomGenerationWorkflow : IWorkflow private readonly IConfiguration configuration; - private readonly ILogger log; + private readonly ILogger log; private readonly IJsonArrayGenerator fileArrayGenerator; @@ -50,7 +50,7 @@ public class SbomGenerationWorkflow : IWorkflow public SbomGenerationWorkflow( IConfiguration configuration, IFileSystemUtils fileSystemUtils, - ILogger log, + ILogger log, IJsonArrayGenerator fileArrayGenerator, IJsonArrayGenerator packageArrayGenerator, IJsonArrayGenerator relationshipsArrayGenerator, @@ -80,9 +80,9 @@ public virtual async Task RunAsync() { try { - log.Debug("Starting SBOM generation workflow."); + log.LogDebug("Starting SBOM generation workflow."); - sbomDir = configuration.ManifestDirPath.Value; + sbomDir = "C:\\repos\\dropvalidator-cd4.0.6\\_manifest"; // Don't remove directory if path is provided by user, there could be other files in that directory if (configuration.ManifestDirPath.IsDefaultSource) @@ -91,7 +91,7 @@ public virtual async Task RunAsync() } else { - log.Warning("Manifest directory path was explicitly defined. Will not attempt to delete any existing _manifest directory."); + log.LogWarning("Manifest directory path was explicitly defined. Will not attempt to delete any existing _manifest directory."); } await using (sbomConfigs.StartJsonSerializationAsync()) @@ -127,8 +127,8 @@ public virtual async Task RunAsync() catch (Exception e) { recorder.RecordException(e); - log.Error("Encountered an error while generating the manifest."); - log.Error($"Error details: {e.Message}"); + log.LogError("Encountered an error while generating the manifest."); + log.LogError($"Error details: {e.Message}"); if (e is not ManifestFolderExistsException) { @@ -161,7 +161,7 @@ public virtual async Task RunAsync() } catch (Exception e) { - log.Warning($"Unable to delete the temp directory {fileSystemUtils.GetSbomToolTempPath()}", e); + log.LogWarning($"Unable to delete the temp directory {fileSystemUtils.GetSbomToolTempPath()}", e); } } } @@ -179,14 +179,14 @@ private void DeleteManifestFolder(string sbomDir) } else if (!fileSystemUtils.IsDirectoryEmpty(sbomDir)) { - log.Warning($"Manifest generation failed, however we were " + + log.LogWarning($"Manifest generation failed, however we were " + $"unable to delete the partially generated manifest.json file and the {sbomDir} directory because the directory was not empty."); } } } catch (Exception e) { - this.log.Warning( + this.log.LogWarning( $"Manifest generation failed, however we were " + $"unable to delete the partially generated manifest.json file and the {sbomDir} directory.", e); @@ -197,7 +197,7 @@ private void GenerateHashForManifestJson(string manifestJsonFilePath) { if (!fileSystemUtils.FileExists(manifestJsonFilePath)) { - log.Warning($"Failed to create manifest hash because the manifest json file does not exist."); + log.LogWarning($"Failed to create manifest hash because the manifest json file does not exist."); return; } @@ -237,7 +237,7 @@ private void RemoveExistingManifestDirectory() $"overwrite this folder."); } - log.Warning( + log.LogWarning( $"Deleting pre-existing folder {rootManifestFolderPath} as {Constants.DeleteManifestDirBoolVariableName}" + $" is 'true'."); fileSystemUtils.DeleteDir(rootManifestFolderPath, true); diff --git a/src/Microsoft.Sbom.Api/Workflows/SBOMParserBasedValidationWorkflow.cs b/src/Microsoft.Sbom.Api/Workflows/SBOMParserBasedValidationWorkflow.cs index fba6383b..70b25985 100644 --- a/src/Microsoft.Sbom.Api/Workflows/SBOMParserBasedValidationWorkflow.cs +++ b/src/Microsoft.Sbom.Api/Workflows/SBOMParserBasedValidationWorkflow.cs @@ -8,6 +8,7 @@ using System.Text.Json; using System.Text.Json.Serialization; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; using Microsoft.Sbom.Api.Entities; using Microsoft.Sbom.Api.Entities.Output; using Microsoft.Sbom.Api.Manifest; @@ -22,7 +23,6 @@ using Microsoft.Sbom.JsonAsynchronousNodeKit; using Microsoft.Sbom.Parser; using PowerArgs; -using Serilog; using Constants = Microsoft.Sbom.Api.Utils.Constants; namespace Microsoft.Sbom.Api.Workflows; @@ -35,7 +35,7 @@ public class SbomParserBasedValidationWorkflow : IWorkflow log; private readonly IManifestParserProvider manifestParserProvider; private readonly IConfiguration configuration; private readonly ISbomConfigProvider sbomConfigs; @@ -44,7 +44,7 @@ public class SbomParserBasedValidationWorkflow : IWorkflow log, IManifestParserProvider manifestParserProvider, IConfiguration configuration, ISbomConfigProvider sbomConfigs, FilesValidator filesValidator, ValidationResultGenerator validationResultGenerator, IOutputWriter outputWriter, IFileSystemUtils fileSystemUtils) { this.recorder = recorder ?? throw new ArgumentNullException(nameof(recorder)); this.signValidationProvider = signValidationProvider ?? throw new ArgumentNullException(nameof(signValidationProvider)); @@ -81,13 +81,13 @@ public async Task RunAsync() if (signValidator == null) { - log.Warning($"ValidateSignature switch is true, but couldn't find a sign validator for the current OS, skipping validation."); + log.LogWarning($"ValidateSignature switch is true, but couldn't find a sign validator for the current OS, skipping validation."); } else { if (!signValidator.Validate()) { - log.Error("Sign validation failed."); + log.LogError("Sign validation failed."); return false; } } @@ -134,7 +134,7 @@ public async Task RunAsync() }); } - log.Debug("Finished workflow, gathering results."); + log.LogDebug("Finished workflow, gathering results."); // Generate JSON output validationResultOutput = validationResultGenerator @@ -160,7 +160,7 @@ public async Task RunAsync() if (configuration.IgnoreMissing.Value) { - log.Warning("Not including missing files on disk as -IgnoreMissing switch is on."); + log.LogWarning("Not including missing files on disk as -IgnoreMissing switch is on."); validFailures = validFailures.Where(a => a.ErrorType != ErrorType.MissingFile); } @@ -169,8 +169,8 @@ public async Task RunAsync() catch (Exception e) { recorder.RecordException(e); - log.Error("Encountered an error while validating the drop."); - log.Error($"Error details: {e.Message}"); + log.LogError("Encountered an error while validating the drop."); + log.LogError($"Error details: {e.Message}"); return false; } finally diff --git a/src/Microsoft.Sbom.Common/Microsoft.Sbom.Common.csproj b/src/Microsoft.Sbom.Common/Microsoft.Sbom.Common.csproj index 878f6837..bd4b8bb5 100644 --- a/src/Microsoft.Sbom.Common/Microsoft.Sbom.Common.csproj +++ b/src/Microsoft.Sbom.Common/Microsoft.Sbom.Common.csproj @@ -9,6 +9,7 @@ + diff --git a/src/Microsoft.Sbom.Common/OSUtils.cs b/src/Microsoft.Sbom.Common/OSUtils.cs index f1d6d3c0..0dee6f3a 100644 --- a/src/Microsoft.Sbom.Common/OSUtils.cs +++ b/src/Microsoft.Sbom.Common/OSUtils.cs @@ -1,14 +1,14 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +namespace Microsoft.Sbom.Common; + using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; -using Serilog; - -namespace Microsoft.Sbom.Common; +using Microsoft.Extensions.Logging; public class OSUtils : IOSUtils { @@ -21,13 +21,13 @@ public class OSUtils : IOSUtils OSPlatform.Linux }; - private readonly ILogger logger; + private readonly ILogger logger; private readonly IEnvironmentWrapper environment; private Dictionary environmentVariables; - public OSUtils(ILogger logger, IEnvironmentWrapper environment) + public OSUtils(ILogger logger, IEnvironmentWrapper environment) { this.logger = logger ?? throw new ArgumentNullException(nameof(logger)); this.environment = environment ?? throw new ArgumentException(nameof(environment)); @@ -62,7 +62,7 @@ public string GetEnvironmentVariable(string variableName) catch (InvalidOperationException) { var firstEnvVarInstance = variableNameValues.First(); - logger.Warning($"There are duplicate environment variables in different case for {variableName}, the value used is {firstEnvVarInstance}"); + logger.LogWarning("There are duplicate environment variables in different case for {VariableName}, the value used is {FirstEnvVarInstance}", variableName, firstEnvVarInstance); return firstEnvVarInstance; } } diff --git a/src/Microsoft.Sbom.Common/ProcessExecutor.cs b/src/Microsoft.Sbom.Common/ProcessExecutor.cs index 2a32df68..3d759157 100644 --- a/src/Microsoft.Sbom.Common/ProcessExecutor.cs +++ b/src/Microsoft.Sbom.Common/ProcessExecutor.cs @@ -5,13 +5,13 @@ namespace Microsoft.Sbom.Common; using System; using System.Diagnostics; -using Serilog; +using Microsoft.Extensions.Logging; public class ProcessExecutor : IProcessExecutor { - private readonly ILogger logger; + private readonly ILogger logger; - public ProcessExecutor(ILogger logger) + public ProcessExecutor(ILogger logger) { this.logger = logger ?? throw new ArgumentNullException(nameof(logger)); } @@ -43,14 +43,14 @@ public ProcessExecutor(ILogger logger) // Check if process was successful or not. if (process.ExitCode != 0) { - logger.Error($"The process {fileName} with the arguments {arguments} exited with code {process.ExitCode}. StdErr: {process.StandardError.ReadToEnd()}"); + logger.LogError($"The process {fileName} with the arguments {arguments} exited with code {process.ExitCode}. StdErr: {process.StandardError.ReadToEnd()}"); return null; } if (!processExited) { process.Kill(); // If the process exceeds the timeout, kill it - logger.Error($"The process {fileName} with the arguments {arguments} timed out."); + logger.LogError($"The process {fileName} with the arguments {arguments} timed out."); return null; } diff --git a/src/Microsoft.Sbom.Extensions.DependencyInjection/ServiceCollectionExtensions.cs b/src/Microsoft.Sbom.Extensions.DependencyInjection/ServiceCollectionExtensions.cs index dad6ebb0..880a2fbe 100644 --- a/src/Microsoft.Sbom.Extensions.DependencyInjection/ServiceCollectionExtensions.cs +++ b/src/Microsoft.Sbom.Extensions.DependencyInjection/ServiceCollectionExtensions.cs @@ -2,34 +2,8 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Concurrent; -using Microsoft.ComponentDetection.Common; -using Microsoft.ComponentDetection.Contracts; -using Microsoft.ComponentDetection.Detectors.CocoaPods; -using Microsoft.ComponentDetection.Detectors.Conan; -using Microsoft.ComponentDetection.Detectors.Dockerfile; -using Microsoft.ComponentDetection.Detectors.Go; -using Microsoft.ComponentDetection.Detectors.Gradle; -using Microsoft.ComponentDetection.Detectors.Ivy; -using Microsoft.ComponentDetection.Detectors.Linux; -using Microsoft.ComponentDetection.Detectors.Maven; -using Microsoft.ComponentDetection.Detectors.Npm; -using Microsoft.ComponentDetection.Detectors.NuGet; -using Microsoft.ComponentDetection.Detectors.Pip; -using Microsoft.ComponentDetection.Detectors.Pnpm; -using Microsoft.ComponentDetection.Detectors.Poetry; -using Microsoft.ComponentDetection.Detectors.Ruby; -using Microsoft.ComponentDetection.Detectors.Rust; -using Microsoft.ComponentDetection.Detectors.Spdx; -using Microsoft.ComponentDetection.Detectors.Vcpkg; -using Microsoft.ComponentDetection.Detectors.Yarn; -using Microsoft.ComponentDetection.Detectors.Yarn.Parsers; -using Microsoft.ComponentDetection.Orchestrator; -using Microsoft.ComponentDetection.Orchestrator.Experiments; -using Microsoft.ComponentDetection.Orchestrator.Services; -using Microsoft.ComponentDetection.Orchestrator.Services.GraphTranslation; +using Microsoft.ComponentDetection.Orchestrator.Extensions; using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Http; -using Microsoft.Extensions.Logging; using Microsoft.Sbom.Api; using Microsoft.Sbom.Api.Config; using Microsoft.Sbom.Api.Config.Extensions; @@ -57,15 +31,8 @@ using Microsoft.Sbom.Contracts; using Microsoft.Sbom.Contracts.Interfaces; using Microsoft.Sbom.Extensions.Entities; -using Serilog; -using Serilog.Core; using Serilog.Events; -using Serilog.Extensions.Logging; -using Serilog.Filters; -using Serilog.Sinks.Map; using Constants = Microsoft.Sbom.Api.Utils.Constants; -using IComponentDetector = Microsoft.ComponentDetection.Contracts.IComponentDetector; -using ILogger = Serilog.ILogger; namespace Microsoft.Sbom.Extensions.DependencyInjection; @@ -87,30 +54,7 @@ public static IServiceCollection AddSbomConfiguration(this IServiceCollection se public static IServiceCollection AddSbomTool(this IServiceCollection services, LogEventLevel logLevel = LogEventLevel.Information) { services - .AddSingleton() .AddTransient(_ => FileSystemUtilsProvider.CreateInstance()) - .AddTransient(x => - { - logLevel = x.GetService()?.Verbosity?.Value ?? logLevel; - return Log.Logger = new LoggerConfiguration() - .MinimumLevel.ControlledBy(new LoggingLevelSwitch { MinimumLevel = logLevel }) - .Filter.ByExcluding(Matching.FromSource("System.Net.Http.HttpClient")) - .Enrich.With() - .Enrich.FromLogContext() - .WriteTo.Map( - LoggingEnricher.LogFilePathPropertyName, - (logFilePath, wt) => wt.Async(x => x.File($"{logFilePath}")), - 1) // sinkMapCountLimit - .WriteTo.Map( - LoggingEnricher.PrintStderrPropertyName, - (printLogsToStderr, wt) => wt.Logger(lc => lc - .WriteTo.Console(outputTemplate: Constants.LoggerTemplate, standardErrorFromLevel: printLogsToStderr ? LogEventLevel.Debug : null) - - // Don't write the detection times table from DetectorProcessingService to the console, only the log file - .Filter.ByExcluding(Matching.WithProperty("DetectionTimeLine", x => !string.IsNullOrEmpty(x)))), - 1) // sinkMapCountLimit - .CreateLogger(); - }) .AddTransient, SbomParserBasedValidationWorkflow>() .AddTransient, SbomGenerationWorkflow>() .AddTransient() @@ -142,7 +86,7 @@ public static IServiceCollection AddSbomTool(this IServiceCollection services, L .AddTransient() .AddTransient() .AddTransient() - .AddTransient() + .AddTransient() .AddTransient() .AddTransient() .AddTransient() @@ -212,102 +156,9 @@ public static IServiceCollection AddSbomTool(this IServiceCollection services, L return manifestData; }) - .ConfigureLoggingProviders() - .ConfigureComponentDetectors() - .ConfigureComponentDetectionSharedServices() - .ConfigureComponentDetectionCommandLineServices() + .AddComponentDetection() .AddHttpClient(); return services; } - - public static IServiceCollection ConfigureLoggingProviders(this IServiceCollection services) - { - var providers = new LoggerProviderCollection(); - services.AddSingleton(providers); - services.AddSingleton(sc => - { - var providerCollection = sc.GetService(); - var factory = new SerilogLoggerFactory(null, true, providerCollection); - - foreach (var provider in sc.GetServices()) - { - factory.AddProvider(provider); - } - - return factory; - }); - - return services; - } - - public static IServiceCollection ConfigureComponentDetectionCommandLineServices(this IServiceCollection services) - { - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - - return services; - } - - public static IServiceCollection ConfigureComponentDetectionSharedServices(this IServiceCollection services) - { - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - - return services; - } - - public static IServiceCollection ConfigureComponentDetectors(this IServiceCollection services) - { - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - - return services; - } } diff --git a/src/Microsoft.Sbom.Tool/Program.cs b/src/Microsoft.Sbom.Tool/Program.cs index 26442165..c352f525 100644 --- a/src/Microsoft.Sbom.Tool/Program.cs +++ b/src/Microsoft.Sbom.Tool/Program.cs @@ -1,20 +1,28 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +namespace Microsoft.Sbom.Tool; + using System; using System.Reflection; using System.Threading.Tasks; +using Microsoft.ComponentDetection.Orchestrator; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; using Microsoft.Sbom.Api; using Microsoft.Sbom.Api.Config; using Microsoft.Sbom.Api.Config.Args; using Microsoft.Sbom.Api.Config.Extensions; using Microsoft.Sbom.Api.Exceptions; +using Microsoft.Sbom.Common.Config; using Microsoft.Sbom.Extensions.DependencyInjection; using PowerArgs; - -namespace Microsoft.Sbom.Tool; +using Serilog; +using Serilog.Core; +using Serilog.Events; +using Serilog.Filters; +using Constants = Microsoft.Sbom.Api.Utils.Constants; internal class Program { @@ -55,10 +63,10 @@ await Host.CreateDefaultBuilder(args) services .AddTransient() .AddSingleton(typeof(IConfigurationBuilder<>), typeof(ConfigurationBuilder<>)) - .AddSingleton(x => + .AddSingleton(provider => { - var validationConfigurationBuilder = x.GetService>(); - var generationConfigurationBuilder = x.GetService>(); + var validationConfigurationBuilder = provider.GetService>(); + var generationConfigurationBuilder = provider.GetService>(); var inputConfiguration = result.ActionArgs switch { ValidationArgs v => validationConfigurationBuilder.GetConfiguration(v).GetAwaiter().GetResult(), @@ -66,11 +74,30 @@ await Host.CreateDefaultBuilder(args) _ => default }; - inputConfiguration.ToConfiguration(); - return inputConfiguration; + inputConfiguration?.ToConfiguration(); + return inputConfiguration; // Return the fetched input configuration }) - .AddSbomTool(); + .AddSbomTool() + .AddLogging(l => l.ClearProviders() // Clear logging providers coming from component-detection libraries + .AddSerilog(new LoggerConfiguration() + .MinimumLevel.ControlledBy(new LoggingLevelSwitch { MinimumLevel = LogEventLevel.Debug }) + .Enrich.With() + .Enrich.FromLogContext() + .WriteTo.Map( + LoggingEnricher.LogFilePathPropertyName, + (logFilePath, wt) => wt.Async(x => x.File($"{logFilePath}")), + 1) // sinkMapCountLimit + .WriteTo.Map( + LoggingEnricher.PrintStderrPropertyName, + (printLogsToStderr, wt) => wt.Logger(lc => lc + .WriteTo.Console(outputTemplate: Constants.LoggerTemplate, standardErrorFromLevel: printLogsToStderr ? LogEventLevel.Debug : null) + + // Don't write the detection times table from DetectorProcessingService to the console, only the log file + .Filter.ByExcluding(Matching.WithProperty("DetectionTimeLine", x => !string.IsNullOrEmpty(x)))) + .Filter.ByExcluding(Matching.FromSource("Microsoft.ComponentDetection.Orchestrator.Services.DetectorProcessingService")), + 1) // sinkMapCountLimit + .CreateLogger())); }) .RunConsoleAsync(x => x.SuppressStatusMessages = true); } diff --git a/test/Microsoft.Sbom.Api.Tests/Config/SBOMConfigTests.cs b/test/Microsoft.Sbom.Api.Tests/Config/SBOMConfigTests.cs index 1b122ee5..87248874 100644 --- a/test/Microsoft.Sbom.Api.Tests/Config/SBOMConfigTests.cs +++ b/test/Microsoft.Sbom.Api.Tests/Config/SBOMConfigTests.cs @@ -1,6 +1,7 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using Microsoft.Extensions.Logging; using Microsoft.Sbom.Api.Manifest.Configuration; using Microsoft.Sbom.Api.Metadata; using Microsoft.Sbom.Api.Output.Telemetry; @@ -9,7 +10,6 @@ using Microsoft.Sbom.Extensions; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; -using Serilog; namespace Microsoft.Sbom.Api.Tests.Config; @@ -18,7 +18,7 @@ public class SBOMConfigTests { private readonly Mock configHandler; private readonly Configuration config; - private readonly Mock logger; + private readonly Mock> logger; private readonly Mock recorder; private readonly LocalMetadataProvider localMetadataProvider; @@ -33,7 +33,7 @@ public SBOMConfigTests() NamespaceUriBase = new ConfigurationSetting("http://sbom.microsoft") }; - logger = new Mock(); + logger = new Mock>(); recorder = new Mock(); localMetadataProvider = new LocalMetadataProvider(config); } diff --git a/test/Microsoft.Sbom.Api.Tests/Converters/ComponentToExternalReferenceInfoConverterTests.cs b/test/Microsoft.Sbom.Api.Tests/Converters/ComponentToExternalReferenceInfoConverterTests.cs index 48f69209..e4857eee 100644 --- a/test/Microsoft.Sbom.Api.Tests/Converters/ComponentToExternalReferenceInfoConverterTests.cs +++ b/test/Microsoft.Sbom.Api.Tests/Converters/ComponentToExternalReferenceInfoConverterTests.cs @@ -8,18 +8,17 @@ using System.Threading.Tasks; using Microsoft.ComponentDetection.Contracts.BcdeModels; using Microsoft.ComponentDetection.Contracts.TypedComponent; +using Microsoft.Extensions.Logging; using Microsoft.Sbom.Api.Converters; -using Microsoft.Sbom.Api.Entities; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; -using Serilog; namespace Microsoft.Sbom.Api.Tests.Converters; [TestClass] public class ComponentToExternalReferenceInfoConverterTests { - private readonly Mock mockLogger = new Mock(); + private readonly Mock> mockLogger = new Mock>(); [TestMethod] public async Task When_ConvertingComponentToExternalDocRefInfo_WithCommonCase_ThenTestPass() diff --git a/test/Microsoft.Sbom.Api.Tests/Converters/ExternalReferenceInfoToPathConverterTest.cs b/test/Microsoft.Sbom.Api.Tests/Converters/ExternalReferenceInfoToPathConverterTest.cs index 4e061064..99a042b6 100644 --- a/test/Microsoft.Sbom.Api.Tests/Converters/ExternalReferenceInfoToPathConverterTest.cs +++ b/test/Microsoft.Sbom.Api.Tests/Converters/ExternalReferenceInfoToPathConverterTest.cs @@ -5,19 +5,18 @@ using System.Linq; using System.Threading.Channels; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; using Microsoft.Sbom.Api.Converters; -using Microsoft.Sbom.Api.Entities; using Microsoft.Sbom.Extensions.Entities; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; -using Serilog; namespace Microsoft.Sbom.Api.Tests.Converters; [TestClass] public class ExternalReferenceInfoToPathConverterTest { - private readonly Mock mockLogger = new Mock(); + private readonly Mock> mockLogger = new Mock>(); [TestMethod] public async Task When_ConvertingExternalDocRefInfoToPath_WithCommonCase_ThenTestPass() diff --git a/test/Microsoft.Sbom.Api.Tests/Executors/ComponentToPackageInfoConverterTests.cs b/test/Microsoft.Sbom.Api.Tests/Executors/ComponentToPackageInfoConverterTests.cs index 63ec764f..3136b689 100644 --- a/test/Microsoft.Sbom.Api.Tests/Executors/ComponentToPackageInfoConverterTests.cs +++ b/test/Microsoft.Sbom.Api.Tests/Executors/ComponentToPackageInfoConverterTests.cs @@ -18,17 +18,17 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using HashAlgorithmName = Microsoft.Sbom.Contracts.Enums.AlgorithmName; -using ILogger = Serilog.ILogger; using PackageInfo = Microsoft.Sbom.Contracts.SbomPackage; namespace Microsoft.Sbom.Api.Executors.Tests; +using Microsoft.Extensions.Logging; using Microsoft.Sbom.Adapters.ComponentDetection; [TestClass] public class ComponentToPackageInfoConverterTests { - private readonly Mock mockLogger = new Mock(); + private readonly Mock> mockLogger = new Mock>(); private readonly Mock mockConfiguration = new Mock(); private readonly ManifestGeneratorProvider manifestGeneratorProvider; diff --git a/test/Microsoft.Sbom.Api.Tests/Executors/DirectoryWalkerTests.cs b/test/Microsoft.Sbom.Api.Tests/Executors/DirectoryWalkerTests.cs index 7bff8061..141402f6 100644 --- a/test/Microsoft.Sbom.Api.Tests/Executors/DirectoryWalkerTests.cs +++ b/test/Microsoft.Sbom.Api.Tests/Executors/DirectoryWalkerTests.cs @@ -4,19 +4,19 @@ using System; using System.Collections.Generic; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; using Microsoft.Sbom.Api.Exceptions; using Microsoft.Sbom.Common; using Microsoft.Sbom.Common.Config; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; -using Serilog; namespace Microsoft.Sbom.Api.Executors.Tests; [TestClass] public class DirectoryWalkerTests { - private readonly Mock mockLogger = new Mock(); + private readonly Mock> mockLogger = new Mock>(); private readonly Mock mockConfiguration = new Mock(); [TestInitialize] diff --git a/test/Microsoft.Sbom.Api.Tests/Executors/ExternalDocumentReferenceWriterTest.cs b/test/Microsoft.Sbom.Api.Tests/Executors/ExternalDocumentReferenceWriterTest.cs index 35f8fde2..59947d35 100644 --- a/test/Microsoft.Sbom.Api.Tests/Executors/ExternalDocumentReferenceWriterTest.cs +++ b/test/Microsoft.Sbom.Api.Tests/Executors/ExternalDocumentReferenceWriterTest.cs @@ -2,9 +2,9 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; -using System.Text.Json; using System.Threading.Channels; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; using Microsoft.Sbom.Api.Executors; using Microsoft.Sbom.Api.Manifest; using Microsoft.Sbom.Api.Manifest.Configuration; @@ -18,7 +18,6 @@ using Microsoft.Sbom.Extensions.Entities; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; -using Serilog; using Constants = Microsoft.Sbom.Api.Utils.Constants; namespace Microsoft.Sbom.Api.Tests.Executors; @@ -26,7 +25,8 @@ namespace Microsoft.Sbom.Api.Tests.Executors; [TestClass] public class ExternalDocumentReferenceWriterTest { - private Mock mockLogger = new Mock(); + private Mock> mockLogger = new Mock>(); + private Mock> mockExternalDocumentReferenceWriterLogger = new Mock>(); private Mock recorderMock = new Mock(); private Mock fileSystemUtilsMock = new Mock(); @@ -71,7 +71,7 @@ public async Task PassExternalDocumentReferenceInfosChannel_ReturnsJsonDocWithSe externalDocumentReferenceInfosChannel.Writer.Complete(); - var externalDocumentReferenceWriter = new ExternalDocumentReferenceWriter(manifestGeneratorProvider, mockLogger.Object); + var externalDocumentReferenceWriter = new ExternalDocumentReferenceWriter(manifestGeneratorProvider, mockExternalDocumentReferenceWriterLogger.Object); var (results, errors) = externalDocumentReferenceWriter.Write(externalDocumentReferenceInfosChannel, new List { sbomConfig }); await foreach (var result in results.ReadAllAsync()) diff --git a/test/Microsoft.Sbom.Api.Tests/Executors/FileHasherTests.cs b/test/Microsoft.Sbom.Api.Tests/Executors/FileHasherTests.cs index 950c9a31..c76e2244 100644 --- a/test/Microsoft.Sbom.Api.Tests/Executors/FileHasherTests.cs +++ b/test/Microsoft.Sbom.Api.Tests/Executors/FileHasherTests.cs @@ -7,6 +7,7 @@ using System.Linq; using System.Threading.Channels; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; using Microsoft.Sbom.Api.Convertors; using Microsoft.Sbom.Api.Entities; using Microsoft.Sbom.Api.Exceptions; @@ -20,7 +21,6 @@ using Microsoft.Sbom.Extensions.Entities; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; -using Serilog; using Constants = Microsoft.Sbom.Api.Utils.Constants; namespace Microsoft.Sbom.Api.Executors.Tests; @@ -28,7 +28,7 @@ namespace Microsoft.Sbom.Api.Executors.Tests; [TestClass] public class FileHasherTests { - private readonly Mock mockLogger = new Mock(); + private readonly Mock> mockLogger = new Mock>(); private readonly Mock mockConfiguration = new Mock(); private readonly ConcurrentDictionary hashDict = new ConcurrentDictionary(); diff --git a/test/Microsoft.Sbom.Api.Tests/Executors/FileListEnumeratorTests.cs b/test/Microsoft.Sbom.Api.Tests/Executors/FileListEnumeratorTests.cs index e6c8a51c..e529265f 100644 --- a/test/Microsoft.Sbom.Api.Tests/Executors/FileListEnumeratorTests.cs +++ b/test/Microsoft.Sbom.Api.Tests/Executors/FileListEnumeratorTests.cs @@ -4,18 +4,18 @@ using System; using System.Collections.Generic; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; using Microsoft.Sbom.Api.Exceptions; using Microsoft.Sbom.Common; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; -using Serilog; namespace Microsoft.Sbom.Api.Executors.Tests; [TestClass] public class FileListEnumeratorTests { - private readonly Mock mockLogger = new Mock(); + private readonly Mock> mockLogger = new Mock>(); [TestMethod] public async Task ListWalkerTests_ValidListFile_SucceedsAsync() diff --git a/test/Microsoft.Sbom.Api.Tests/Executors/LicenseInformationFetcherTests.cs b/test/Microsoft.Sbom.Api.Tests/Executors/LicenseInformationFetcherTests.cs index a135a7be..00f47cde 100644 --- a/test/Microsoft.Sbom.Api.Tests/Executors/LicenseInformationFetcherTests.cs +++ b/test/Microsoft.Sbom.Api.Tests/Executors/LicenseInformationFetcherTests.cs @@ -4,18 +4,18 @@ using System.Collections.Generic; using Microsoft.ComponentDetection.Contracts.BcdeModels; using Microsoft.ComponentDetection.Contracts.TypedComponent; +using Microsoft.Extensions.Logging; using Microsoft.Sbom.Api.Output.Telemetry; using Microsoft.Sbom.Api.Tests; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; -using ILogger = Serilog.ILogger; namespace Microsoft.Sbom.Api.Executors.Tests; [TestClass] public class LicenseInformationFetcherTests { - private readonly Mock mockLogger = new Mock(); + private readonly Mock> mockLogger = new Mock>(); private readonly Mock mockRecorder = new Mock(); private readonly Mock mockLicenseInformationService = new Mock(); diff --git a/test/Microsoft.Sbom.Api.Tests/Executors/PackagesWalkerTests.cs b/test/Microsoft.Sbom.Api.Tests/Executors/PackagesWalkerTests.cs index f29b022a..0b53a36a 100644 --- a/test/Microsoft.Sbom.Api.Tests/Executors/PackagesWalkerTests.cs +++ b/test/Microsoft.Sbom.Api.Tests/Executors/PackagesWalkerTests.cs @@ -22,14 +22,17 @@ using Moq; using Serilog.Events; using IComponentDetector = Microsoft.Sbom.Api.Utils.IComponentDetector; -using ILogger = Serilog.ILogger; namespace Microsoft.Sbom.Api.Executors.Tests; +using Microsoft.Extensions.Logging; +using Microsoft.Sbom.Adapters.ComponentDetection; + [TestClass] public class PackagesWalkerTests { - private readonly Mock mockLogger = new Mock(); + private readonly Mock> mockLogger = new Mock>(); + private readonly Mock> mockComponentDetectorCachedExecutorLogger = new Mock>(); private readonly Mock mockConfiguration = new Mock(); private readonly Mock mockSbomConfigs = new Mock(); private readonly Mock mockFileSystemUtils = new Mock(); @@ -67,7 +70,7 @@ public async Task ScanSuccessTestAsync() scannedComponents.Add(scannedComponentOther); - var mockDetector = new Mock(new Mock().Object, new Mock().Object); + var mockDetector = new Mock(mockComponentDetectorCachedExecutorLogger.Object, new Mock().Object); var scanResult = new ScanResult { @@ -120,7 +123,7 @@ public async Task ScanCombinePackagesWithSameNameDifferentCase() scannedComponents.Add(scannedComponentOther); - var mockDetector = new Mock(new Mock().Object, new Mock().Object); + var mockDetector = new Mock(mockComponentDetectorCachedExecutorLogger.Object, new Mock().Object); var scanResult = new ScanResult { @@ -153,7 +156,7 @@ public async Task ScanCombinePackagesWithSameNameDifferentCase() [TestMethod] public void ScanWithNullOrEmptyPathSuccessTest() { - var mockDetector = new Mock(new Mock().Object, new Mock().Object); + var mockDetector = new Mock(mockComponentDetectorCachedExecutorLogger.Object, new Mock().Object); var walker = new PackagesWalker(mockLogger.Object, mockDetector.Object, mockConfiguration.Object, mockSbomConfigs.Object, mockFileSystemUtils.Object, mockPackageDetailsFactory.Object, mockLicenseInformationFetcher.Object); walker.GetComponents(null); @@ -165,7 +168,7 @@ public void ScanWithNullOrEmptyPathSuccessTest() [TestMethod] public async Task ScanFailureTestAsync() { - var mockDetector = new Mock(new Mock().Object, new Mock().Object); + var mockDetector = new Mock(mockComponentDetectorCachedExecutorLogger.Object, new Mock().Object); var scanResult = new ScanResult { @@ -213,7 +216,7 @@ public async Task ScanIgnoreSbomComponents() scannedComponents.Add(scannedComponentOther); - var mockDetector = new Mock(new Mock().Object, new Mock().Object); + var mockDetector = new Mock(mockComponentDetectorCachedExecutorLogger.Object, new Mock().Object); var scanResult = new ScanResult { diff --git a/test/Microsoft.Sbom.Api.Tests/Executors/SBOMComponentsWalkerTests.cs b/test/Microsoft.Sbom.Api.Tests/Executors/SBOMComponentsWalkerTests.cs index 5d776eba..ee2b226a 100644 --- a/test/Microsoft.Sbom.Api.Tests/Executors/SBOMComponentsWalkerTests.cs +++ b/test/Microsoft.Sbom.Api.Tests/Executors/SBOMComponentsWalkerTests.cs @@ -21,14 +21,17 @@ using Moq; using Serilog.Events; using IComponentDetector = Microsoft.Sbom.Api.Utils.IComponentDetector; -using ILogger = Serilog.ILogger; namespace Microsoft.Sbom.Api.Executors.Tests; +using Microsoft.Extensions.Logging; +using Microsoft.Sbom.Adapters.ComponentDetection; + [TestClass] public class SBOMComponentsWalkerTests { - private readonly Mock mockLogger = new Mock(); + private readonly Mock> mockLogger = new Mock>(); + private readonly Mock> mockComponentDetectorCachedExecutorLogger = new Mock>(); private readonly Mock mockConfiguration = new Mock(); private readonly Mock mockSbomConfigs = new Mock(); private readonly Mock mockFileSystem = new Mock(); @@ -60,7 +63,7 @@ public async Task GetComponents() scannedComponents.Add(scannedComponent); } - var mockDetector = new Mock(new Mock().Object, new Mock().Object); + var mockDetector = new Mock(mockComponentDetectorCachedExecutorLogger.Object, new Mock().Object); var scanResult = new ScanResult { @@ -105,7 +108,7 @@ public async Task GetComponentsWithFiltering() }; scannedComponents.Add(nonSbomComponent); - var mockDetector = new Mock(new Mock().Object, new Mock().Object); + var mockDetector = new Mock(mockComponentDetectorCachedExecutorLogger.Object, new Mock().Object); var scanResult = new ScanResult { diff --git a/test/Microsoft.Sbom.Api.Tests/Executors/SPDXSBOMReaderForExternalDocumentReferenceTests.cs b/test/Microsoft.Sbom.Api.Tests/Executors/SPDXSBOMReaderForExternalDocumentReferenceTests.cs index 7635412a..6c644dfe 100644 --- a/test/Microsoft.Sbom.Api.Tests/Executors/SPDXSBOMReaderForExternalDocumentReferenceTests.cs +++ b/test/Microsoft.Sbom.Api.Tests/Executors/SPDXSBOMReaderForExternalDocumentReferenceTests.cs @@ -5,6 +5,7 @@ using System.Linq; using System.Threading.Channels; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; using Microsoft.Sbom.Api.Executors; using Microsoft.Sbom.Api.Hashing; using Microsoft.Sbom.Api.Manifest; @@ -25,7 +26,7 @@ namespace Microsoft.Sbom.Api.Tests.Executors; public class SPDXSBOMReaderForExternalDocumentReferenceTests { private readonly Mock mockHashGenerator = new Mock(); - private readonly Mock mockLogger = new Mock(); + private readonly Mock> mockLogger = new Mock>(); private readonly ISbomConfigProvider sbomConfigs; private readonly Mock mockConfiguration = new Mock(); private readonly ManifestGeneratorProvider manifestGeneratorProvider; diff --git a/test/Microsoft.Sbom.Api.Tests/Filters/DownloadedRootPathFilterTests.cs b/test/Microsoft.Sbom.Api.Tests/Filters/DownloadedRootPathFilterTests.cs index 1c1a918c..018eb2b4 100644 --- a/test/Microsoft.Sbom.Api.Tests/Filters/DownloadedRootPathFilterTests.cs +++ b/test/Microsoft.Sbom.Api.Tests/Filters/DownloadedRootPathFilterTests.cs @@ -1,6 +1,7 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using Microsoft.Extensions.Logging; using Microsoft.Sbom.Common; using Microsoft.Sbom.Common.Config; using Microsoft.VisualStudio.TestTools.UnitTesting; @@ -12,7 +13,7 @@ namespace Microsoft.Sbom.Api.Filters.Tests; [TestClass] public class DownloadedRootPathFilterTests { - private readonly Mock logger = new Mock(); + private readonly Mock> logger = new Mock>(); [TestMethod] public void DownloadedRootPathFilterTest_NoFilterPath_Succeeds() diff --git a/test/Microsoft.Sbom.Api.Tests/PackageDetails/MavenUtilsTests.cs b/test/Microsoft.Sbom.Api.Tests/PackageDetails/MavenUtilsTests.cs index 131610a9..d8fd3359 100644 --- a/test/Microsoft.Sbom.Api.Tests/PackageDetails/MavenUtilsTests.cs +++ b/test/Microsoft.Sbom.Api.Tests/PackageDetails/MavenUtilsTests.cs @@ -7,12 +7,12 @@ using System.Text; using Microsoft.ComponentDetection.Contracts.BcdeModels; using Microsoft.ComponentDetection.Contracts.TypedComponent; +using Microsoft.Extensions.Logging; using Microsoft.Sbom.Api.Output.Telemetry; using Microsoft.Sbom.Api.PackageDetails; using Microsoft.Sbom.Common; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; -using Serilog; namespace Microsoft.Sbom.Api.Tests.PackageDetails; @@ -20,7 +20,7 @@ namespace Microsoft.Sbom.Api.Tests.PackageDetails; public class MavenUtilsTests { private readonly Mock mockFileSystemUtils = new Mock(); - private readonly Mock mockLogger = new Mock(); + private readonly Mock> mockLogger = new Mock>(); private readonly Mock mockRecorder = new Mock(); private static readonly string EnvHomePath = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "HOMEPATH" : "HOME"; diff --git a/test/Microsoft.Sbom.Api.Tests/PackageDetails/NugetUtilsTests.cs b/test/Microsoft.Sbom.Api.Tests/PackageDetails/NugetUtilsTests.cs index 1bc11af2..abce71d1 100644 --- a/test/Microsoft.Sbom.Api.Tests/PackageDetails/NugetUtilsTests.cs +++ b/test/Microsoft.Sbom.Api.Tests/PackageDetails/NugetUtilsTests.cs @@ -4,13 +4,13 @@ using System.Text; using Microsoft.ComponentDetection.Contracts.BcdeModels; using Microsoft.ComponentDetection.Contracts.TypedComponent; +using Microsoft.Extensions.Logging; using Microsoft.Sbom.Api.Output.Telemetry; using Microsoft.Sbom.Api.PackageDetails; using Microsoft.Sbom.Common; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using NuGet.Configuration; -using Serilog; namespace Microsoft.Sbom.Api.Tests.PackageDetails; @@ -18,7 +18,7 @@ namespace Microsoft.Sbom.Api.Tests.PackageDetails; public class NugetUtilsTests { private readonly Mock mockFileSystemUtils = new Mock(); - private readonly Mock mockLogger = new Mock(); + private readonly Mock> mockLogger = new Mock>(); private readonly Mock mockRecorder = new Mock(); private static readonly string NugetPackagesPath = SettingsUtility.GetGlobalPackagesFolder(new NullSettings()); diff --git a/test/Microsoft.Sbom.Api.Tests/PackageDetails/RubyGemsUtilsTests.cs b/test/Microsoft.Sbom.Api.Tests/PackageDetails/RubyGemsUtilsTests.cs index 80c39d7e..55d9254e 100644 --- a/test/Microsoft.Sbom.Api.Tests/PackageDetails/RubyGemsUtilsTests.cs +++ b/test/Microsoft.Sbom.Api.Tests/PackageDetails/RubyGemsUtilsTests.cs @@ -3,12 +3,12 @@ using Microsoft.ComponentDetection.Contracts.BcdeModels; using Microsoft.ComponentDetection.Contracts.TypedComponent; +using Microsoft.Extensions.Logging; using Microsoft.Sbom.Api.Output.Telemetry; using Microsoft.Sbom.Api.PackageDetails; using Microsoft.Sbom.Common; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; -using Serilog; namespace Microsoft.Sbom.Api.Tests.PackageDetails; @@ -16,7 +16,7 @@ namespace Microsoft.Sbom.Api.Tests.PackageDetails; public class RubyGemsUtilsTests { private readonly Mock mockFileSystemUtils = new Mock(); - private readonly Mock mockLogger = new Mock(); + private readonly Mock> mockLogger = new Mock>(); private readonly Mock mockRecorder = new Mock(); private readonly Mock mockProcessExecutor = new Mock(); diff --git a/test/Microsoft.Sbom.Api.Tests/Utils/ComponentDetectorCachedExecutorTest.cs b/test/Microsoft.Sbom.Api.Tests/Utils/ComponentDetectorCachedExecutorTest.cs index 2d05780a..becb9cf5 100644 --- a/test/Microsoft.Sbom.Api.Tests/Utils/ComponentDetectorCachedExecutorTest.cs +++ b/test/Microsoft.Sbom.Api.Tests/Utils/ComponentDetectorCachedExecutorTest.cs @@ -5,17 +5,17 @@ using System.Threading.Tasks; using Microsoft.ComponentDetection.Contracts.BcdeModels; using Microsoft.ComponentDetection.Orchestrator.Commands; +using Microsoft.Extensions.Logging; using Microsoft.Sbom.Api.Utils; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; -using Serilog; namespace Microsoft.Sbom.Api.Tests.Utils; [TestClass] public class ComponentDetectorCachedExecutorTest { - private readonly Mock logger = new Mock(); + private readonly Mock> logger = new Mock>(); private readonly Mock detector = new Mock(); [TestInitialize] diff --git a/test/Microsoft.Sbom.Api.Tests/Utils/OSUtilsTest.cs b/test/Microsoft.Sbom.Api.Tests/Utils/OSUtilsTest.cs index 1d8da95a..6e331f2d 100644 --- a/test/Microsoft.Sbom.Api.Tests/Utils/OSUtilsTest.cs +++ b/test/Microsoft.Sbom.Api.Tests/Utils/OSUtilsTest.cs @@ -1,19 +1,20 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using System; using System.Collections; using System.Collections.Generic; +using Microsoft.Extensions.Logging; using Microsoft.Sbom.Common; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; -using Serilog; namespace Microsoft.Sbom.Api.Tests.Utils; [TestClass] public class OSUtilsTest { - private readonly Mock logger = new Mock(); + private readonly Mock> logger = new Mock>(); private readonly Mock environment = new Mock(); @@ -61,7 +62,14 @@ public void GetEnvironmentVariable_DuplicateEnvVar() Assert.AreEqual("true", osUtils.GetEnvironmentVariable(Variable)); environment.VerifyAll(); - logger.Verify(o => o.Warning($"There are duplicate environment variables in different case for {Variable}, the value used is true"), Times.Once()); + logger.Verify( + logger => logger.Log( + It.Is(logLevel => logLevel == LogLevel.Warning), + It.Is(eventId => eventId.Id == 0), + It.Is((@object, @type) => @object.ToString() == $"There are duplicate environment variables in different case for {Variable}, the value used is true" && @type.Name == "FormattedLogValues"), + It.IsAny(), + It.IsAny>()), + Times.Once); } [TestMethod] diff --git a/test/Microsoft.Sbom.Api.Tests/Workflows/Helpers/RelationshipsArrayGeneratorTest.cs b/test/Microsoft.Sbom.Api.Tests/Workflows/Helpers/RelationshipsArrayGeneratorTest.cs index 43ed78d3..a023e80c 100644 --- a/test/Microsoft.Sbom.Api.Tests/Workflows/Helpers/RelationshipsArrayGeneratorTest.cs +++ b/test/Microsoft.Sbom.Api.Tests/Workflows/Helpers/RelationshipsArrayGeneratorTest.cs @@ -5,6 +5,7 @@ using System.IO; using System.Linq; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; using Microsoft.Sbom.Api.Executors; using Microsoft.Sbom.Api.Manifest; using Microsoft.Sbom.Api.Manifest.Configuration; @@ -17,7 +18,6 @@ using Microsoft.Sbom.Extensions.Entities; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; -using Serilog; using Constants = Microsoft.Sbom.Api.Utils.Constants; namespace Microsoft.Sbom.Api.Tests.Workflows.Helpers; @@ -30,8 +30,8 @@ public class RelationshipsArrayGeneratorTest private readonly Mock recorderMock = new Mock(); private readonly Mock sbomConfigsMock = new Mock(); private readonly Mock relationshipGeneratorMock = new Mock(new ManifestGeneratorProvider(null)); - private readonly Mock loggerMock = new Mock(); - private readonly Mock mockLogger = new Mock(); + private readonly Mock> mockRelationshipsArrayGeneratorLogger = new Mock>(); + private readonly Mock> mockMetadataBuilderLogger = new Mock>(); private readonly Mock fileSystemUtilsMock = new Mock(); private readonly ManifestGeneratorProvider manifestGeneratorProvider = new ManifestGeneratorProvider(new IManifestGenerator[] { new TestManifestGenerator() }); private ISbomPackageDetailsRecorder recorder; @@ -64,10 +64,10 @@ public void Setup() } }); relationshipGeneratorMock.CallBase = true; - relationshipsArrayGenerator = new RelationshipsArrayGenerator(relationshipGeneratorMock.Object, new ChannelUtils(), loggerMock.Object, sbomConfigsMock.Object, recorderMock.Object); + relationshipsArrayGenerator = new RelationshipsArrayGenerator(relationshipGeneratorMock.Object, new ChannelUtils(), mockRelationshipsArrayGeneratorLogger.Object, sbomConfigsMock.Object, recorderMock.Object); manifestGeneratorProvider.Init(); metadataBuilder = new MetadataBuilder( - mockLogger.Object, + mockMetadataBuilderLogger.Object, manifestGeneratorProvider, Constants.TestManifestInfo, recorderMock.Object); diff --git a/test/Microsoft.Sbom.Api.Tests/Workflows/ManifestGenerationWorkflowTests.cs b/test/Microsoft.Sbom.Api.Tests/Workflows/ManifestGenerationWorkflowTests.cs index cbae545d..35d99a1d 100644 --- a/test/Microsoft.Sbom.Api.Tests/Workflows/ManifestGenerationWorkflowTests.cs +++ b/test/Microsoft.Sbom.Api.Tests/Workflows/ManifestGenerationWorkflowTests.cs @@ -11,6 +11,7 @@ using Microsoft.ComponentDetection.Contracts.BcdeModels; using Microsoft.ComponentDetection.Contracts.TypedComponent; using Microsoft.ComponentDetection.Orchestrator.Commands; +using Microsoft.Extensions.Logging; using Microsoft.Sbom.Api.Convertors; using Microsoft.Sbom.Api.Entities; using Microsoft.Sbom.Api.Exceptions; @@ -39,11 +40,9 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using Newtonsoft.Json.Linq; -using Serilog.Events; using Checksum = Microsoft.Sbom.Contracts.Checksum; using Constants = Microsoft.Sbom.Api.Utils.Constants; using IComponentDetector = Microsoft.Sbom.Api.Utils.IComponentDetector; -using ILogger = Serilog.ILogger; namespace Microsoft.Sbom.Api.Workflows.Tests; @@ -54,12 +53,30 @@ public class ManifestGenerationWorkflowTests private readonly Mock fileSystemMock = new Mock(); private readonly Mock configurationMock = new Mock(); - private readonly Mock mockLogger = new Mock(); + private readonly Mock> mockSbomConfigProividerLogger = new Mock>(); + private readonly Mock> mockMetadataBuilderLogger = new Mock>(); + private readonly Mock> mockDirectoryTraversingFileToJsonProviderLogger = new Mock>(); + private readonly Mock> mockFileHasherLogger = new Mock>(); + private readonly Mock> mockSbomGenerationWorkflowLogger = new Mock>(); + private readonly Mock> mockManifestFolderFiltererLogger = new Mock>(); + private readonly Mock> mockFileInfoWriterLogger = new Mock>(); + private readonly Mock> mockPackagesWalkerLogger = new Mock>(); + private readonly Mock> mockPackageArrayGeneratorLogger = new Mock>(); + private readonly Mock> mockFileListBasedFileToJsonProviderLogger = new Mock>(); + private readonly Mock> mockFileArrayGeneratorLogger = new Mock>(); + private readonly Mock> mockDirectoryWalkerLogger = new Mock>(); + private readonly Mock> mockPackageInfoJsonWriterLogger = new Mock>(); + private readonly Mock> mockFileListEnumeratorLogger = new Mock>(); + private readonly Mock> mockExternalDocumentReferenceProviderLogger = new Mock>(); + private readonly Mock> mockExternalDocumentReferenceWriterLogger = new Mock>(); + private readonly Mock> mockCGScannedPackagesProviderLogger = new Mock>(); + private readonly Mock> mockExternalDocumentReferenceGeneratorLogger = new Mock>(); + private static readonly Mock> MockComponentDetectorCachedExecutorLogger = new Mock>(); private readonly Mock hashCodeGeneratorMock = new Mock(); private readonly Mock mockOSUtils = new Mock(); private readonly Mock mockConfigHandler = new Mock(); private readonly Mock mockMetadataProvider = new Mock(); - private readonly Mock mockDetector = new Mock(new Mock().Object, new Mock().Object); + private readonly Mock mockDetector = new Mock(MockComponentDetectorCachedExecutorLogger.Object, new Mock().Object); private readonly Mock> relationshipArrayGenerator = new Mock>(); private readonly Mock packageInfoConverterMock = new Mock(); private readonly Mock sBOMReaderForExternalDocumentReferenceMock = new Mock(); @@ -86,7 +103,7 @@ public async Task ManifestGenerationWorkflowTests_Succeeds(bool deleteExistingMa manifestGeneratorProvider.Init(); var metadataBuilder = new MetadataBuilder( - mockLogger.Object, + mockMetadataBuilderLogger.Object, manifestGeneratorProvider, Constants.TestManifestInfo, recorderMock.Object); @@ -111,7 +128,7 @@ public async Task ManifestGenerationWorkflowTests_Succeeds(bool deleteExistingMa var sbomConfigs = new SbomConfigProvider( new IManifestConfigHandler[] { mockConfigHandler.Object }, new IMetadataProvider[] { mockMetadataProvider.Object }, - mockLogger.Object, + mockSbomConfigProividerLogger.Object, recorderMock.Object); using var manifestStream = new MemoryStream(); @@ -236,63 +253,63 @@ await externalDocumentReferenceChannel.Writer.WriteAsync(new ExternalDocumentRef var directoryTraversingProvider = new DirectoryTraversingFileToJsonProvider( configurationMock.Object, new ChannelUtils(), - mockLogger.Object, + mockDirectoryTraversingFileToJsonProviderLogger.Object, new FileHasher( hashCodeGeneratorMock.Object, new SbomToolManifestPathConverter(configurationMock.Object, mockOSUtils.Object, fileSystemMock.Object, fileSystemUtilsExtensionMock.Object), - mockLogger.Object, + mockFileHasherLogger.Object, configurationMock.Object, sbomConfigs, manifestGeneratorProvider, new FileTypeUtils()), - new ManifestFolderFilterer(manifestFilterMock, mockLogger.Object), + new ManifestFolderFilterer(manifestFilterMock, mockManifestFolderFiltererLogger.Object), new FileInfoWriter( manifestGeneratorProvider, - mockLogger.Object), + mockFileInfoWriterLogger.Object), new InternalSBOMFileInfoDeduplicator(), - new DirectoryWalker(fileSystemMock.Object, mockLogger.Object, configurationMock.Object)); + new DirectoryWalker(fileSystemMock.Object, mockDirectoryWalkerLogger.Object, configurationMock.Object)); var fileListBasedProvider = new FileListBasedFileToJsonProvider( configurationMock.Object, new ChannelUtils(), - mockLogger.Object, + mockFileListBasedFileToJsonProviderLogger.Object, new FileHasher( hashCodeGeneratorMock.Object, new SbomToolManifestPathConverter(configurationMock.Object, mockOSUtils.Object, fileSystemMock.Object, fileSystemUtilsExtensionMock.Object), - mockLogger.Object, + mockFileHasherLogger.Object, configurationMock.Object, sbomConfigs, manifestGeneratorProvider, new FileTypeUtils()), - new ManifestFolderFilterer(manifestFilterMock, mockLogger.Object), + new ManifestFolderFilterer(manifestFilterMock, mockManifestFolderFiltererLogger.Object), new FileInfoWriter( manifestGeneratorProvider, - mockLogger.Object), + mockFileInfoWriterLogger.Object), new InternalSBOMFileInfoDeduplicator(), - new FileListEnumerator(fileSystemMock.Object, mockLogger.Object)); + new FileListEnumerator(fileSystemMock.Object, mockFileListEnumeratorLogger.Object)); var cgPackagesProvider = new CGScannedPackagesProvider( configurationMock.Object, new ChannelUtils(), - mockLogger.Object, + mockCGScannedPackagesProviderLogger.Object, sbomConfigs, new PackageInfoJsonWriter( manifestGeneratorProvider, - mockLogger.Object), + mockPackageInfoJsonWriterLogger.Object), packageInfoConverterMock.Object, - new PackagesWalker(mockLogger.Object, mockDetector.Object, configurationMock.Object, sbomConfigs, fileSystemMock.Object, mockPackageDetailsFactory.Object, licenseInformationFetcherMock.Object), + new PackagesWalker(mockPackagesWalkerLogger.Object, mockDetector.Object, configurationMock.Object, sbomConfigs, fileSystemMock.Object, mockPackageDetailsFactory.Object, licenseInformationFetcherMock.Object), mockPackageDetailsFactory.Object, licenseInformationFetcherMock.Object); var externalDocumentReferenceProvider = new ExternalDocumentReferenceProvider( configurationMock.Object, new ChannelUtils(), - mockLogger.Object, - new FileListEnumerator(fileSystemMock.Object, mockLogger.Object), + mockExternalDocumentReferenceProviderLogger.Object, + new FileListEnumerator(fileSystemMock.Object, mockFileListEnumeratorLogger.Object), sBOMReaderForExternalDocumentReferenceMock.Object, new ExternalDocumentReferenceWriter( manifestGeneratorProvider, - mockLogger.Object), + mockExternalDocumentReferenceWriterLogger.Object), new ExternalReferenceDeduplicator()); var sourcesProvider = new List @@ -303,11 +320,11 @@ await externalDocumentReferenceChannel.Writer.WriteAsync(new ExternalDocumentRef { externalDocumentReferenceProvider } }; - var fileArrayGenerator = new FileArrayGenerator(sbomConfigs, sourcesProvider, recorderMock.Object, mockLogger.Object); + var fileArrayGenerator = new FileArrayGenerator(sbomConfigs, sourcesProvider, recorderMock.Object, mockFileArrayGeneratorLogger.Object); - var packageArrayGenerator = new PackageArrayGenerator(mockLogger.Object, sbomConfigs, sourcesProvider, recorderMock.Object); + var packageArrayGenerator = new PackageArrayGenerator(mockPackageArrayGeneratorLogger.Object, sbomConfigs, sourcesProvider, recorderMock.Object); - var externalDocumentReferenceGenerator = new ExternalDocumentReferenceGenerator(mockLogger.Object, sbomConfigs, sourcesProvider, recorderMock.Object); + var externalDocumentReferenceGenerator = new ExternalDocumentReferenceGenerator(mockExternalDocumentReferenceGeneratorLogger.Object, sbomConfigs, sourcesProvider, recorderMock.Object); relationshipArrayGenerator .Setup(r => r.GenerateAsync()) @@ -316,7 +333,7 @@ await externalDocumentReferenceChannel.Writer.WriteAsync(new ExternalDocumentRef var workflow = new SbomGenerationWorkflow( configurationMock.Object, fileSystemMock.Object, - mockLogger.Object, + mockSbomGenerationWorkflowLogger.Object, fileArrayGenerator, packageArrayGenerator, relationshipArrayGenerator.Object, @@ -346,7 +363,7 @@ await externalDocumentReferenceChannel.Writer.WriteAsync(new ExternalDocumentRef configurationMock.VerifyAll(); fileSystemMock.VerifyAll(); hashCodeGeneratorMock.VerifyAll(); - mockLogger.VerifyAll(); + mockSbomGenerationWorkflowLogger.VerifyAll(); fileSystemMock.Verify(x => x.FileExists(jsonFilePath), Times.Once); fileSystemMock.Verify(x => x.WriteAllText($"{jsonFilePath}.sha256", It.IsAny()), Times.Once); } @@ -366,7 +383,7 @@ public async Task ManifestGenerationWorkflowTests_SBOMDirExists_Throws() var workflow = new SbomGenerationWorkflow( configurationMock.Object, fileSystemMock.Object, - mockLogger.Object, + mockSbomGenerationWorkflowLogger.Object, new Mock>().Object, new Mock>().Object, new Mock>().Object, @@ -398,7 +415,7 @@ public async Task ManifestGenerationWorkflowTests_SBOMDir_NotDefault_NotDeleted( var workflow = new SbomGenerationWorkflow( configurationMock.Object, fileSystemMock.Object, - mockLogger.Object, + mockSbomGenerationWorkflowLogger.Object, fileArrayGeneratorMock.Object, new Mock>().Object, new Mock>().Object, diff --git a/test/Microsoft.Sbom.Api.Tests/Workflows/SbomParserBasedValidationWorkflowTests.cs b/test/Microsoft.Sbom.Api.Tests/Workflows/SbomParserBasedValidationWorkflowTests.cs index 67bd33ec..a4cdb6b9 100644 --- a/test/Microsoft.Sbom.Api.Tests/Workflows/SbomParserBasedValidationWorkflowTests.cs +++ b/test/Microsoft.Sbom.Api.Tests/Workflows/SbomParserBasedValidationWorkflowTests.cs @@ -5,6 +5,7 @@ using System.IO; using System.Linq; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; using Microsoft.Sbom.Api.Convertors; using Microsoft.Sbom.Api.Entities.Output; using Microsoft.Sbom.Api.Executors; @@ -31,7 +32,6 @@ using Microsoft.Sbom.Utils; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; -using Serilog; using Constants = Microsoft.Sbom.Api.Utils.Constants; using ErrorType = Microsoft.Sbom.Api.Entities.ErrorType; using SpdxChecksum = Microsoft.Sbom.Parsers.Spdx22SbomParser.Entities.Checksum; @@ -43,7 +43,14 @@ namespace Microsoft.Sbom.Workflows; [TestClass] public class SbomParserBasedValidationWorkflowTests : ValidationWorkflowTestsBase { - private readonly Mock mockLogger = new(); + private readonly Mock> mockDirectoryWalkerLogger = new Mock>(); + private readonly Mock> mockManifestFolderFiltererLogger = new Mock>(); + private readonly Mock> mockFileHasherLogger = new Mock>(); + private readonly Mock> mockDownloadedRootPathFilterLogger = new Mock>(); + private readonly Mock> mockFilesValidatorLogger = new Mock>(); + private readonly Mock> mockSbomParserBasedValidationWorkflowLogger = new Mock>(); + private readonly Mock> mockEnumeratorChannelLogger = new Mock>(); + private readonly Mock> mockFileFiltererLogger = new Mock>(); private readonly Mock mockOSUtils = new(); private readonly Mock fileSystemUtilsExtensionMock = new(); private readonly Mock signValidatorMock = new(); @@ -120,7 +127,7 @@ public async Task SbomParserBasedValidationWorkflowTests_ReturnsSuccessAndValida var validationResultGenerator = new ValidationResultGenerator(configurationMock.Object); - var directoryWalker = new DirectoryWalker(fileSystemMock.Object, mockLogger.Object, configurationMock.Object); + var directoryWalker = new DirectoryWalker(fileSystemMock.Object, mockDirectoryWalkerLogger.Object, configurationMock.Object); hashCodeGeneratorMock.Setup(h => h.GenerateHashes( It.IsAny(), @@ -138,7 +145,7 @@ public async Task SbomParserBasedValidationWorkflowTests_ReturnsSuccessAndValida var fileHasher = new FileHasher( hashCodeGeneratorMock.Object, new SbomToolManifestPathConverter(configurationMock.Object, mockOSUtils.Object, fileSystemMock.Object, fileSystemUtilsExtensionMock.Object), - mockLogger.Object, + mockFileHasherLogger.Object, configurationMock.Object, new Mock().Object, new ManifestGeneratorProvider(null), @@ -146,20 +153,20 @@ public async Task SbomParserBasedValidationWorkflowTests_ReturnsSuccessAndValida var manifestFilterMock = new ManifestFolderFilter(configurationMock.Object, mockOSUtils.Object); manifestFilterMock.Init(); - var fileFilterer = new ManifestFolderFilterer(manifestFilterMock, mockLogger.Object); + var fileFilterer = new ManifestFolderFilterer(manifestFilterMock, mockManifestFolderFiltererLogger.Object); - var rootFileFilterMock = new DownloadedRootPathFilter(configurationMock.Object, fileSystemMock.Object, mockLogger.Object); + var rootFileFilterMock = new DownloadedRootPathFilter(configurationMock.Object, fileSystemMock.Object, mockDownloadedRootPathFilterLogger.Object); rootFileFilterMock.Init(); var hashValidator = new ConcurrentSha256HashValidator(FileHashesDictionarySingleton.Instance); - var enumeratorChannel = new EnumeratorChannel(mockLogger.Object); + var enumeratorChannel = new EnumeratorChannel(mockEnumeratorChannelLogger.Object); var fileConverter = new SbomFileToFileInfoConverter(new FileTypeUtils()); - var spdxFileFilterer = new FileFilterer(rootFileFilterMock, mockLogger.Object, configurationMock.Object, fileSystemMock.Object); + var spdxFileFilterer = new FileFilterer(rootFileFilterMock, mockFileFiltererLogger.Object, configurationMock.Object, fileSystemMock.Object); var filesValidator = new FilesValidator( directoryWalker, configurationMock.Object, - mockLogger.Object, + mockFilesValidatorLogger.Object, fileHasher, fileFilterer, hashValidator, @@ -171,7 +178,7 @@ public async Task SbomParserBasedValidationWorkflowTests_ReturnsSuccessAndValida var validator = new SbomParserBasedValidationWorkflow( recorder.Object, signValidationProviderMock.Object, - mockLogger.Object, + mockSbomParserBasedValidationWorkflowLogger.Object, manifestParserProvider.Object, configurationMock.Object, sbomConfigs.Object, @@ -255,7 +262,7 @@ public async Task SbomParserBasedValidationWorkflowTests_ReturnsSuccessAndValida var validationResultGenerator = new ValidationResultGenerator(configurationMock.Object); - var directoryWalker = new DirectoryWalker(fileSystemMock.Object, mockLogger.Object, configurationMock.Object); + var directoryWalker = new DirectoryWalker(fileSystemMock.Object, mockDirectoryWalkerLogger.Object, configurationMock.Object); hashCodeGeneratorMock.Setup(h => h.GenerateHashes( It.IsAny(), @@ -278,7 +285,7 @@ public async Task SbomParserBasedValidationWorkflowTests_ReturnsSuccessAndValida var fileHasher = new FileHasher( hashCodeGeneratorMock.Object, new SbomToolManifestPathConverter(configurationMock.Object, mockOSUtils.Object, fileSystemMock.Object, fileSystemUtilsExtensionMock.Object), - mockLogger.Object, + mockFileHasherLogger.Object, configurationMock.Object, new Mock().Object, new ManifestGeneratorProvider(null), @@ -286,20 +293,20 @@ public async Task SbomParserBasedValidationWorkflowTests_ReturnsSuccessAndValida var manifestFilterMock = new ManifestFolderFilter(configurationMock.Object, mockOSUtils.Object); manifestFilterMock.Init(); - var fileFilterer = new ManifestFolderFilterer(manifestFilterMock, mockLogger.Object); + var fileFilterer = new ManifestFolderFilterer(manifestFilterMock, mockManifestFolderFiltererLogger.Object); - var rootFileFilterMock = new DownloadedRootPathFilter(configurationMock.Object, fileSystemMock.Object, mockLogger.Object); + var rootFileFilterMock = new DownloadedRootPathFilter(configurationMock.Object, fileSystemMock.Object, mockDownloadedRootPathFilterLogger.Object); rootFileFilterMock.Init(); var hashValidator = new ConcurrentSha256HashValidator(FileHashesDictionarySingleton.Instance); - var enumeratorChannel = new EnumeratorChannel(mockLogger.Object); + var enumeratorChannel = new EnumeratorChannel(mockEnumeratorChannelLogger.Object); var fileConverter = new SbomFileToFileInfoConverter(new FileTypeUtils()); - var spdxFileFilterer = new FileFilterer(rootFileFilterMock, mockLogger.Object, configurationMock.Object, fileSystemMock.Object); + var spdxFileFilterer = new FileFilterer(rootFileFilterMock, mockFileFiltererLogger.Object, configurationMock.Object, fileSystemMock.Object); var filesValidator = new FilesValidator( directoryWalker, configurationMock.Object, - mockLogger.Object, + mockFilesValidatorLogger.Object, fileHasher, fileFilterer, hashValidator, @@ -311,7 +318,7 @@ public async Task SbomParserBasedValidationWorkflowTests_ReturnsSuccessAndValida var validator = new SbomParserBasedValidationWorkflow( recorder.Object, signValidationProviderMock.Object, - mockLogger.Object, + mockSbomParserBasedValidationWorkflowLogger.Object, manifestParserProvider.Object, configurationMock.Object, sbomConfigs.Object,