diff --git a/src/c#/DrivelutionTest/Core/DriverUpdaterFactoryTests.cs b/src/c#/DrivelutionTest/Core/DriverUpdaterFactoryTests.cs index eecd821c..0ae1c236 100644 --- a/src/c#/DrivelutionTest/Core/DriverUpdaterFactoryTests.cs +++ b/src/c#/DrivelutionTest/Core/DriverUpdaterFactoryTests.cs @@ -1,8 +1,6 @@ using GeneralUpdate.Drivelution.Core; using GeneralUpdate.Drivelution.Abstractions; using GeneralUpdate.Drivelution.Abstractions.Configuration; -using Serilog; -using Serilog.Core; namespace DrivelutionTest.Core; @@ -26,26 +24,6 @@ public void Create_WithoutParameters_ReturnsNonNullInstance() Assert.IsAssignableFrom(updater); } - /// - /// Tests that Create method accepts custom logger. - /// - [Fact] - public void Create_WithCustomLogger_ReturnsInstance() - { - // Arrange - var logger = new LoggerConfiguration() - .MinimumLevel.Debug() - .WriteTo.Console() - .CreateLogger(); - - // Act - var updater = DrivelutionFactory.Create(logger); - - // Assert - Assert.NotNull(updater); - Assert.IsAssignableFrom(updater); - } - /// /// Tests that Create method accepts custom options. /// @@ -55,12 +33,11 @@ public void Create_WithCustomOptions_ReturnsInstance() // Arrange var options = new DrivelutionOptions { - LogLevel = "Debug", - LogFilePath = "./logs/test.log" + DefaultBackupPath = "./backups" }; // Act - var updater = DrivelutionFactory.Create(null, options); + var updater = DrivelutionFactory.Create(options); // Assert Assert.NotNull(updater); @@ -98,7 +75,7 @@ public void IsPlatformSupported_ReturnsBooleanValue() /// Tests that CreateValidator returns a non-null instance. /// [Fact] - public void CreateValidator_WithoutLogger_ReturnsNonNullInstance() + public void CreateValidator_WithoutParameters_ReturnsNonNullInstance() { // Skip on MacOS and Unknown platforms var platform = DrivelutionFactory.GetCurrentPlatform(); @@ -119,7 +96,7 @@ public void CreateValidator_WithoutLogger_ReturnsNonNullInstance() /// Tests that CreateBackup returns a non-null instance. /// [Fact] - public void CreateBackup_WithoutLogger_ReturnsNonNullInstance() + public void CreateBackup_WithoutParameters_ReturnsNonNullInstance() { // Skip on MacOS and Unknown platforms var platform = DrivelutionFactory.GetCurrentPlatform(); @@ -136,58 +113,6 @@ public void CreateBackup_WithoutLogger_ReturnsNonNullInstance() Assert.IsAssignableFrom(backup); } - /// - /// Tests that CreateValidator with custom logger works correctly. - /// - [Fact] - public void CreateValidator_WithCustomLogger_ReturnsInstance() - { - // Skip on MacOS and Unknown platforms - var platform = DrivelutionFactory.GetCurrentPlatform(); - if (platform == "MacOS" || platform == "Unknown") - { - return; - } - - // Arrange - var logger = new LoggerConfiguration() - .MinimumLevel.Debug() - .WriteTo.Console() - .CreateLogger(); - - // Act - var validator = DrivelutionFactory.CreateValidator(logger); - - // Assert - Assert.NotNull(validator); - } - - /// - /// Tests that CreateBackup with custom logger works correctly. - /// - [Fact] - public void CreateBackup_WithCustomLogger_ReturnsInstance() - { - // Skip on MacOS and Unknown platforms - var platform = DrivelutionFactory.GetCurrentPlatform(); - if (platform == "MacOS" || platform == "Unknown") - { - return; - } - - // Arrange - var logger = new LoggerConfiguration() - .MinimumLevel.Debug() - .WriteTo.Console() - .CreateLogger(); - - // Act - var backup = DrivelutionFactory.CreateBackup(logger); - - // Assert - Assert.NotNull(backup); - } - /// /// Tests that Create throws PlatformNotSupportedException on unsupported platforms. /// This test documents expected behavior but cannot be easily tested on supported platforms. diff --git a/src/c#/DrivelutionTest/DrivelutionTest.csproj b/src/c#/DrivelutionTest/DrivelutionTest.csproj index 7c3fec32..c869734a 100644 --- a/src/c#/DrivelutionTest/DrivelutionTest.csproj +++ b/src/c#/DrivelutionTest/DrivelutionTest.csproj @@ -1,7 +1,7 @@ - net8.0 + net10.0 enable enable diff --git a/src/c#/DrivelutionTest/GeneralDrivelutionTests.cs b/src/c#/DrivelutionTest/GeneralDrivelutionTests.cs index 87973a42..f9a26f7d 100644 --- a/src/c#/DrivelutionTest/GeneralDrivelutionTests.cs +++ b/src/c#/DrivelutionTest/GeneralDrivelutionTests.cs @@ -1,7 +1,6 @@ using GeneralUpdate.Drivelution; using GeneralUpdate.Drivelution.Abstractions.Models; using GeneralUpdate.Drivelution.Abstractions.Configuration; -using Serilog; namespace DrivelutionTest; @@ -33,8 +32,7 @@ public void Create_WithOptions_ReturnsNonNullInstance() // Arrange var options = new DrivelutionOptions { - LogLevel = "Information", - LogFilePath = "./logs/test.log" + DefaultBackupPath = "./backups" }; // Act @@ -44,48 +42,6 @@ public void Create_WithOptions_ReturnsNonNullInstance() Assert.NotNull(updater); } - /// - /// Tests that Create method with custom logger returns a non-null instance. - /// - [Fact] - public void Create_WithCustomLogger_ReturnsNonNullInstance() - { - // Arrange - var logger = new LoggerConfiguration() - .MinimumLevel.Debug() - .WriteTo.Console() - .CreateLogger(); - - // Act - var updater = GeneralDrivelution.Create(logger); - - // Assert - Assert.NotNull(updater); - } - - /// - /// Tests that Create method with custom logger and options returns instance. - /// - [Fact] - public void Create_WithCustomLoggerAndOptions_ReturnsInstance() - { - // Arrange - var logger = new LoggerConfiguration() - .MinimumLevel.Debug() - .WriteTo.Console() - .CreateLogger(); - var options = new DrivelutionOptions - { - LogLevel = "Debug" - }; - - // Act - var updater = GeneralDrivelution.Create(logger, options); - - // Assert - Assert.NotNull(updater); - } - /// /// Tests that GetPlatformInfo returns valid platform information. /// diff --git a/src/c#/GeneralUpdate.Core/GeneralUpdate.Core.csproj b/src/c#/GeneralUpdate.Core/GeneralUpdate.Core.csproj index 0a61943a..612e68e2 100644 --- a/src/c#/GeneralUpdate.Core/GeneralUpdate.Core.csproj +++ b/src/c#/GeneralUpdate.Core/GeneralUpdate.Core.csproj @@ -22,7 +22,10 @@ public upgrade,update true - netstandard2.0;net8.0 + netstandard2.0;net10.0 + + + enable @@ -90,8 +93,39 @@ - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/c#/GeneralUpdate.Core/Pipeline/DrivelutionMiddleware.cs b/src/c#/GeneralUpdate.Core/Pipeline/DrivelutionMiddleware.cs index cfcb4fac..93037dcb 100644 --- a/src/c#/GeneralUpdate.Core/Pipeline/DrivelutionMiddleware.cs +++ b/src/c#/GeneralUpdate.Core/Pipeline/DrivelutionMiddleware.cs @@ -1,7 +1,6 @@ -#if NET8_0_OR_GREATER +#if NET10_0_OR_GREATER using System; using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Threading.Tasks; @@ -17,8 +16,6 @@ namespace GeneralUpdate.Core.Pipeline; /// public class DrivelutionMiddleware : IMiddleware { - [RequiresUnreferencedCode("Driver update process includes signature validation that may require runtime reflection on some platforms")] - [RequiresDynamicCode("Driver update process includes signature validation that may require runtime code generation on some platforms")] public async Task InvokeAsync(PipelineContext context) { try diff --git a/src/c#/GeneralUpdate.Core/Strategys/LinuxStrategy.cs b/src/c#/GeneralUpdate.Core/Strategys/LinuxStrategy.cs index 751453e1..d326d8de 100644 --- a/src/c#/GeneralUpdate.Core/Strategys/LinuxStrategy.cs +++ b/src/c#/GeneralUpdate.Core/Strategys/LinuxStrategy.cs @@ -33,7 +33,7 @@ protected override PipelineBuilder BuildPipeline(PipelineContext context) .UseMiddlewareIf(_configinfo.PatchEnabled) .UseMiddleware() .UseMiddleware(); -#if NET8_0_OR_GREATER +#if NET10_0_OR_GREATER builder.UseMiddlewareIf(_configinfo.DriveEnabled == true); #endif return builder; diff --git a/src/c#/GeneralUpdate.Core/Strategys/WindowsStrategy.cs b/src/c#/GeneralUpdate.Core/Strategys/WindowsStrategy.cs index 0169a5bf..ab839f8a 100644 --- a/src/c#/GeneralUpdate.Core/Strategys/WindowsStrategy.cs +++ b/src/c#/GeneralUpdate.Core/Strategys/WindowsStrategy.cs @@ -35,7 +35,7 @@ protected override PipelineBuilder BuildPipeline(PipelineContext context) .UseMiddlewareIf(_configinfo.PatchEnabled) .UseMiddleware() .UseMiddleware(); -#if NET8_0_OR_GREATER +#if NET10_0_OR_GREATER builder.UseMiddlewareIf(_configinfo.DriveEnabled == true); #endif return builder; diff --git a/src/c#/GeneralUpdate.Drivelution/Abstractions/Configuration/DriverUpdateOptions.cs b/src/c#/GeneralUpdate.Drivelution/Abstractions/Configuration/DriverUpdateOptions.cs index b450a267..2ac883f9 100644 --- a/src/c#/GeneralUpdate.Drivelution/Abstractions/Configuration/DriverUpdateOptions.cs +++ b/src/c#/GeneralUpdate.Drivelution/Abstractions/Configuration/DriverUpdateOptions.cs @@ -12,29 +12,7 @@ public class DrivelutionOptions /// public string DefaultBackupPath { get; set; } = "./DriverBackups"; - /// - /// 日志级别(Debug/Info/Warn/Error/Fatal) - /// Log level (Debug/Info/Warn/Error/Fatal) - /// - public string LogLevel { get; set; } = "Info"; - - /// - /// 日志文件路径 - /// Log file path - /// - public string LogFilePath { get; set; } = "./Logs/drivelution-.log"; - /// - /// 是否启用控制台日志 - /// Enable console logging - /// - public bool EnableConsoleLogging { get; set; } = true; - - /// - /// 是否启用文件日志 - /// Enable file logging - /// - public bool EnableFileLogging { get; set; } = true; /// /// 默认重试次数 diff --git a/src/c#/GeneralUpdate.Drivelution/Abstractions/Events/DrivelutionLogger.cs b/src/c#/GeneralUpdate.Drivelution/Abstractions/Events/DrivelutionLogger.cs new file mode 100644 index 00000000..dac4330a --- /dev/null +++ b/src/c#/GeneralUpdate.Drivelution/Abstractions/Events/DrivelutionLogger.cs @@ -0,0 +1,63 @@ +namespace GeneralUpdate.Drivelution.Abstractions.Events; + +/// +/// Default implementation of IDrivelutionLogger that raises events +/// +public class DrivelutionLogger : IDrivelutionLogger +{ + /// + public event EventHandler? LogMessage; + + /// + public void Debug(string message, Exception? exception = null, params object[] args) + { + RaiseLogEvent(LogLevel.Debug, message, exception, args); + } + + /// + public void Information(string message, Exception? exception = null, params object[] args) + { + RaiseLogEvent(LogLevel.Information, message, exception, args); + } + + /// + public void Warning(string message, Exception? exception = null, params object[] args) + { + RaiseLogEvent(LogLevel.Warning, message, exception, args); + } + + /// + public void Error(string message, Exception? exception = null, params object[] args) + { + RaiseLogEvent(LogLevel.Error, message, exception, args); + } + + /// + public void Fatal(string message, Exception? exception = null, params object[] args) + { + RaiseLogEvent(LogLevel.Fatal, message, exception, args); + } + + private void RaiseLogEvent(LogLevel level, string message, Exception? exception, params object[] args) + { + try + { + // Format message if args provided + var formattedMessage = args.Length > 0 ? string.Format(message, args) : message; + + var eventArgs = new LogEventArgs + { + Level = level, + Message = formattedMessage, + Exception = exception, + Timestamp = DateTime.UtcNow + }; + + LogMessage?.Invoke(this, eventArgs); + } + catch + { + // Silently ignore exceptions in logging to prevent cascading failures + } + } +} diff --git a/src/c#/GeneralUpdate.Drivelution/Abstractions/Events/IDrivelutionLogger.cs b/src/c#/GeneralUpdate.Drivelution/Abstractions/Events/IDrivelutionLogger.cs new file mode 100644 index 00000000..34688032 --- /dev/null +++ b/src/c#/GeneralUpdate.Drivelution/Abstractions/Events/IDrivelutionLogger.cs @@ -0,0 +1,38 @@ +namespace GeneralUpdate.Drivelution.Abstractions.Events; + +/// +/// Logger interface for Drivelution operations +/// Provides event-based logging mechanism to replace Serilog +/// +public interface IDrivelutionLogger +{ + /// + /// Event raised when a log message is generated + /// + event EventHandler? LogMessage; + + /// + /// Logs a debug message + /// + void Debug(string message, Exception? exception = null, params object[] args); + + /// + /// Logs an information message + /// + void Information(string message, Exception? exception = null, params object[] args); + + /// + /// Logs a warning message + /// + void Warning(string message, Exception? exception = null, params object[] args); + + /// + /// Logs an error message + /// + void Error(string message, Exception? exception = null, params object[] args); + + /// + /// Logs a fatal message + /// + void Fatal(string message, Exception? exception = null, params object[] args); +} diff --git a/src/c#/GeneralUpdate.Drivelution/Abstractions/Events/LogEventArgs.cs b/src/c#/GeneralUpdate.Drivelution/Abstractions/Events/LogEventArgs.cs new file mode 100644 index 00000000..c154d208 --- /dev/null +++ b/src/c#/GeneralUpdate.Drivelution/Abstractions/Events/LogEventArgs.cs @@ -0,0 +1,44 @@ +namespace GeneralUpdate.Drivelution.Abstractions.Events; + +/// +/// Event arguments for log messages from Drivelution operations +/// +public class LogEventArgs : EventArgs +{ + /// + /// Log level + /// + public LogLevel Level { get; set; } + + /// + /// Log message + /// + public string Message { get; set; } = string.Empty; + + /// + /// Exception if any + /// + public Exception? Exception { get; set; } + + /// + /// Timestamp of the log + /// + public DateTime Timestamp { get; set; } = DateTime.UtcNow; + + /// + /// Additional context data + /// + public Dictionary? Context { get; set; } +} + +/// +/// Log level enumeration +/// +public enum LogLevel +{ + Debug, + Information, + Warning, + Error, + Fatal +} diff --git a/src/c#/GeneralUpdate.Drivelution/Abstractions/IDriverValidator.cs b/src/c#/GeneralUpdate.Drivelution/Abstractions/IDriverValidator.cs index 6e8e84b2..d8c798dc 100644 --- a/src/c#/GeneralUpdate.Drivelution/Abstractions/IDriverValidator.cs +++ b/src/c#/GeneralUpdate.Drivelution/Abstractions/IDriverValidator.cs @@ -1,4 +1,3 @@ -using System.Diagnostics.CodeAnalysis; using GeneralUpdate.Drivelution.Abstractions.Models; namespace GeneralUpdate.Drivelution.Abstractions; @@ -28,12 +27,6 @@ public interface IDriverValidator /// 信任的发布者列表 / Trusted publishers list /// 取消令牌 / Cancellation token /// 验证是否通过 / Validation result - /// - /// Note: On Windows, this may require reflection for X509Certificate validation. - /// Platform-specific implementations should add appropriate AOT compatibility attributes. - /// - [RequiresUnreferencedCode("Signature validation may require runtime reflection on some platforms")] - [RequiresDynamicCode("Signature validation may require runtime code generation on some platforms")] Task ValidateSignatureAsync(string filePath, IEnumerable trustedPublishers, CancellationToken cancellationToken = default); /// diff --git a/src/c#/GeneralUpdate.Drivelution/Abstractions/IGeneralDrivelution.cs b/src/c#/GeneralUpdate.Drivelution/Abstractions/IGeneralDrivelution.cs index 093e0360..f3d95162 100644 --- a/src/c#/GeneralUpdate.Drivelution/Abstractions/IGeneralDrivelution.cs +++ b/src/c#/GeneralUpdate.Drivelution/Abstractions/IGeneralDrivelution.cs @@ -1,4 +1,3 @@ -using System.Diagnostics.CodeAnalysis; using GeneralUpdate.Drivelution.Abstractions.Models; namespace GeneralUpdate.Drivelution.Abstractions; @@ -15,11 +14,6 @@ public interface IGeneralDrivelution /// Update strategy /// Cancellation token /// Update result - /// - /// Note: Update process may include signature validation that requires reflection on some platforms. - /// - [RequiresUnreferencedCode("Update process may include signature validation that requires runtime reflection on some platforms")] - [RequiresDynamicCode("Update process may include signature validation that requires runtime code generation on some platforms")] Task UpdateAsync(DriverInfo driverInfo, UpdateStrategy strategy, CancellationToken cancellationToken = default); /// @@ -28,11 +22,6 @@ public interface IGeneralDrivelution /// Driver information /// Cancellation token /// Validation result - /// - /// Note: Includes signature validation that may require reflection on some platforms. - /// - [RequiresUnreferencedCode("Validation includes signature validation that may require runtime reflection on some platforms")] - [RequiresDynamicCode("Validation includes signature validation that may require runtime code generation on some platforms")] Task ValidateAsync(DriverInfo driverInfo, CancellationToken cancellationToken = default); /// diff --git a/src/c#/GeneralUpdate.Drivelution/Core/DriverUpdaterFactory.cs b/src/c#/GeneralUpdate.Drivelution/Core/DriverUpdaterFactory.cs index 10a2e4af..7fb9a998 100644 --- a/src/c#/GeneralUpdate.Drivelution/Core/DriverUpdaterFactory.cs +++ b/src/c#/GeneralUpdate.Drivelution/Core/DriverUpdaterFactory.cs @@ -1,10 +1,10 @@ using System.Runtime.InteropServices; +using GeneralUpdate.Common.Shared; using GeneralUpdate.Drivelution.Abstractions; using GeneralUpdate.Drivelution.Abstractions.Configuration; using GeneralUpdate.Drivelution.Windows.Implementation; using GeneralUpdate.Drivelution.Linux.Implementation; using GeneralUpdate.Drivelution.MacOS.Implementation; -using Serilog; namespace GeneralUpdate.Drivelution.Core; @@ -18,33 +18,29 @@ public static class DrivelutionFactory /// 创建适合当前平台的驱动更新器 /// Creates a driver updater suitable for the current platform /// - /// 日志记录器 / Logger /// 配置选项(可选)/ Configuration options (optional) /// 平台特定的驱动更新器实现 / Platform-specific driver updater implementation /// 当前平台不支持时抛出 / Thrown when current platform is not supported - public static IGeneralDrivelution Create(ILogger? logger = null, DrivelutionOptions? options = null) + public static IGeneralDrivelution Create(DrivelutionOptions? options = null) { - // Use default logger if not provided - logger ??= CreateDefaultLogger(options); - // Detect platform and create appropriate implementation if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { - logger.Information("Detected Windows platform, creating WindowsGeneralDrivelution"); - var validator = new WindowsDriverValidator(logger); - var backup = new WindowsDriverBackup(logger); - return new WindowsGeneralDrivelution(logger, validator, backup); + GeneralTracer.Info("Detected Windows platform, creating WindowsGeneralDrivelution"); + var validator = new WindowsDriverValidator(); + var backup = new WindowsDriverBackup(); + return new WindowsGeneralDrivelution(validator, backup); } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { - logger.Information("Detected Linux platform, creating LinuxGeneralDrivelution"); - var validator = new LinuxDriverValidator(logger); - var backup = new LinuxDriverBackup(logger); - return new LinuxGeneralDrivelution(logger, validator, backup); + GeneralTracer.Info("Detected Linux platform, creating LinuxGeneralDrivelution"); + var validator = new LinuxDriverValidator(); + var backup = new LinuxDriverBackup(); + return new LinuxGeneralDrivelution(validator, backup); } else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { - logger.Warning("MacOS platform detected but not yet implemented"); + GeneralTracer.Warn("MacOS platform detected but not yet implemented"); throw new PlatformNotSupportedException( "MacOS driver update is not yet implemented. " + "This is a placeholder for future MacOS support. " + @@ -53,7 +49,7 @@ public static IGeneralDrivelution Create(ILogger? logger = null, DrivelutionOpti else { var osDescription = RuntimeInformation.OSDescription; - logger.Error("Unsupported platform detected: {Platform}", osDescription); + GeneralTracer.Error($"Unsupported platform detected: {osDescription}"); throw new PlatformNotSupportedException( $"Current platform '{osDescription}' is not supported. " + "Supported platforms: Windows (8+), Linux (Ubuntu 18.04+, CentOS 7+, Debian 10+)"); @@ -64,19 +60,16 @@ public static IGeneralDrivelution Create(ILogger? logger = null, DrivelutionOpti /// 创建适合当前平台的驱动验证器 /// Creates a driver validator suitable for the current platform /// - /// 日志记录器 / Logger /// 平台特定的驱动验证器实现 / Platform-specific driver validator implementation - public static IDriverValidator CreateValidator(ILogger? logger = null) + public static IDriverValidator CreateValidator() { - logger ??= CreateDefaultLogger(); - if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { - return new WindowsDriverValidator(logger); + return new WindowsDriverValidator(); } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { - return new LinuxDriverValidator(logger); + return new LinuxDriverValidator(); } else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { @@ -92,19 +85,16 @@ public static IDriverValidator CreateValidator(ILogger? logger = null) /// 创建适合当前平台的驱动备份管理器 /// Creates a driver backup manager suitable for the current platform /// - /// 日志记录器 / Logger /// 平台特定的驱动备份实现 / Platform-specific driver backup implementation - public static IDriverBackup CreateBackup(ILogger? logger = null) + public static IDriverBackup CreateBackup() { - logger ??= CreateDefaultLogger(); - if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { - return new WindowsDriverBackup(logger); + return new WindowsDriverBackup(); } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { - return new LinuxDriverBackup(logger); + return new LinuxDriverBackup(); } else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { @@ -144,20 +134,4 @@ public static bool IsPlatformSupported() RuntimeInformation.IsOSPlatform(OSPlatform.Linux); // MacOS is planned but not yet implemented } - - /// - /// 创建默认日志记录器 - /// Creates a default logger - /// - private static ILogger CreateDefaultLogger(DrivelutionOptions? options = null) - { - if (options != null) - { - return Logging.LoggerConfigurator.ConfigureLogger(options); - } - else - { - return Logging.LoggerConfigurator.CreateDefaultLogger(); - } - } } diff --git a/src/c#/GeneralUpdate.Drivelution/Core/Logging/LoggerConfigurator.cs b/src/c#/GeneralUpdate.Drivelution/Core/Logging/LoggerConfigurator.cs index 5a488595..19ab718d 100644 --- a/src/c#/GeneralUpdate.Drivelution/Core/Logging/LoggerConfigurator.cs +++ b/src/c#/GeneralUpdate.Drivelution/Core/Logging/LoggerConfigurator.cs @@ -1,6 +1,5 @@ -using Serilog; -using Serilog.Events; using GeneralUpdate.Drivelution.Abstractions.Configuration; +using GeneralUpdate.Drivelution.Abstractions.Events; namespace GeneralUpdate.Drivelution.Core.Logging; @@ -16,64 +15,10 @@ public static class LoggerConfigurator /// /// 驱动更新配置选项 / Driver update configuration options /// 配置好的日志器 / Configured logger - public static ILogger ConfigureLogger(DrivelutionOptions options) + public static IDrivelutionLogger ConfigureLogger(DrivelutionOptions? options = null) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } - - var loggerConfig = new LoggerConfiguration(); - - // Set log level - var logLevel = ParseLogLevel(options.LogLevel); - loggerConfig.MinimumLevel.Is(logLevel); - - // Configure console sink - if (options.EnableConsoleLogging) - { - loggerConfig.WriteTo.Console( - outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}"); - } - - // Configure file sink - if (options.EnableFileLogging) - { - var logPath = string.IsNullOrWhiteSpace(options.LogFilePath) - ? "./Logs/drivelution-.log" - : options.LogFilePath; - - loggerConfig.WriteTo.File( - logPath, - rollingInterval: RollingInterval.Day, - outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff} {Level:u3}] {Message:lj}{NewLine}{Exception}", - retainedFileCountLimit: 30, - fileSizeLimitBytes: 10 * 1024 * 1024); // 10MB per file - } - - // Enrich with context information - loggerConfig.Enrich.FromLogContext(); - - return loggerConfig.CreateLogger(); - } - - /// - /// 解析日志级别 - /// Parses log level - /// - /// 日志级别字符串 / Log level string - /// 日志事件级别 / Log event level - private static LogEventLevel ParseLogLevel(string logLevel) - { - return logLevel?.ToUpperInvariant() switch - { - "DEBUG" or "VERBOSE" => LogEventLevel.Debug, - "INFO" or "INFORMATION" => LogEventLevel.Information, - "WARN" or "WARNING" => LogEventLevel.Warning, - "ERROR" => LogEventLevel.Error, - "FATAL" or "CRITICAL" => LogEventLevel.Fatal, - _ => LogEventLevel.Information - }; + // Return a new logger instance that raises events instead of writing to files + return new DrivelutionLogger(); } /// @@ -81,18 +26,8 @@ private static LogEventLevel ParseLogLevel(string logLevel) /// Creates default logger /// /// 默认配置的日志器 / Logger with default configuration - public static ILogger CreateDefaultLogger() + public static IDrivelutionLogger CreateDefaultLogger() { - return new LoggerConfiguration() - .MinimumLevel.Information() - .WriteTo.Console( - outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}") - .WriteTo.File( - "./Logs/drivelution-.log", - rollingInterval: RollingInterval.Day, - outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff} {Level:u3}] {Message:lj}{NewLine}{Exception}", - retainedFileCountLimit: 30) - .Enrich.FromLogContext() - .CreateLogger(); + return new DrivelutionLogger(); } } diff --git a/src/c#/GeneralUpdate.Drivelution/GeneralDrivelution.cs b/src/c#/GeneralUpdate.Drivelution/GeneralDrivelution.cs index bcdb417b..4db4c8e0 100644 --- a/src/c#/GeneralUpdate.Drivelution/GeneralDrivelution.cs +++ b/src/c#/GeneralUpdate.Drivelution/GeneralDrivelution.cs @@ -1,9 +1,7 @@ using GeneralUpdate.Drivelution.Abstractions; using GeneralUpdate.Drivelution.Abstractions.Configuration; using GeneralUpdate.Drivelution.Abstractions.Models; -using GeneralUpdate.Drivelution.Core.Logging; using GeneralUpdate.Drivelution.Core.Utilities; -using Serilog; namespace GeneralUpdate.Drivelution; @@ -18,7 +16,7 @@ namespace GeneralUpdate.Drivelution; /// var result = await updater.UpdateAsync(driverInfo, strategy); /// /// // With configuration -/// var options = new DrivelutionOptions { LogLevel = "Info" }; +/// var options = new DrivelutionOptions { }; /// var updater = GeneralDrivelution.Create(options); /// var result = await updater.UpdateAsync(driverInfo, strategy); /// @@ -33,22 +31,7 @@ public static class GeneralDrivelution /// Thrown when platform is not supported public static IGeneralDrivelution Create(DrivelutionOptions? options = null) { - var logger = options != null - ? LoggerConfigurator.ConfigureLogger(options) - : LoggerConfigurator.CreateDefaultLogger(); - - return Core.DrivelutionFactory.Create(logger, options); - } - - /// - /// Creates a driver updater instance (with custom logger) - /// - /// Custom logger - /// Configuration options (optional) - /// Platform-adapted driver updater - public static IGeneralDrivelution Create(ILogger logger, DrivelutionOptions? options = null) - { - return Core.DrivelutionFactory.Create(logger, options); + return Core.DrivelutionFactory.Create(options); } /// diff --git a/src/c#/GeneralUpdate.Drivelution/GeneralUpdate.Drivelution.csproj b/src/c#/GeneralUpdate.Drivelution/GeneralUpdate.Drivelution.csproj index a89c36c0..e0ed518d 100644 --- a/src/c#/GeneralUpdate.Drivelution/GeneralUpdate.Drivelution.csproj +++ b/src/c#/GeneralUpdate.Drivelution/GeneralUpdate.Drivelution.csproj @@ -1,7 +1,7 @@  - net8.0 + net10.0 enable enable @@ -12,10 +12,11 @@ full + - - - + + + diff --git a/src/c#/GeneralUpdate.Drivelution/Linux/Implementation/LinuxDriverBackup.cs b/src/c#/GeneralUpdate.Drivelution/Linux/Implementation/LinuxDriverBackup.cs index 9cb1c698..0fda85e8 100644 --- a/src/c#/GeneralUpdate.Drivelution/Linux/Implementation/LinuxDriverBackup.cs +++ b/src/c#/GeneralUpdate.Drivelution/Linux/Implementation/LinuxDriverBackup.cs @@ -1,7 +1,7 @@ using System.Runtime.Versioning; +using GeneralUpdate.Common.Shared; using GeneralUpdate.Drivelution.Abstractions; using GeneralUpdate.Drivelution.Abstractions.Exceptions; -using Serilog; namespace GeneralUpdate.Drivelution.Linux.Implementation; @@ -12,11 +12,8 @@ namespace GeneralUpdate.Drivelution.Linux.Implementation; [SupportedOSPlatform("linux")] public class LinuxDriverBackup : IDriverBackup { - private readonly ILogger _logger; - - public LinuxDriverBackup(ILogger logger) + public LinuxDriverBackup() { - _logger = logger ?? throw new ArgumentNullException(nameof(logger)); } /// @@ -51,12 +48,12 @@ public async Task BackupAsync( await sourceStream.CopyToAsync(destinationStream, cancellationToken); } - _logger.Information("Backup completed: {BackupPath}", backupPathWithTimestamp); + GeneralTracer.Info($"Backup completed: {backupPathWithTimestamp}"); return true; } catch (Exception ex) { - _logger.Error(ex, "Failed to backup driver"); + GeneralTracer.Error("Failed to backup driver", ex); throw new DriverBackupException($"Failed to backup driver: {ex.Message}", ex); } } @@ -91,12 +88,12 @@ public async Task RestoreAsync( await sourceStream.CopyToAsync(destinationStream, cancellationToken); } - _logger.Information("Restore completed"); + GeneralTracer.Info("Restore completed"); return true; } catch (Exception ex) { - _logger.Error(ex, "Failed to restore driver"); + GeneralTracer.Error("Failed to restore driver", ex); throw new DriverRollbackException($"Failed to restore driver: {ex.Message}", ex); } } @@ -119,7 +116,7 @@ public async Task DeleteBackupAsync( } catch (Exception ex) { - _logger.Error(ex, "Failed to delete backup"); + GeneralTracer.Error("Failed to delete backup", ex); return false; } }, cancellationToken); diff --git a/src/c#/GeneralUpdate.Drivelution/Linux/Implementation/LinuxDriverValidator.cs b/src/c#/GeneralUpdate.Drivelution/Linux/Implementation/LinuxDriverValidator.cs index b2f27996..aed8cc49 100644 --- a/src/c#/GeneralUpdate.Drivelution/Linux/Implementation/LinuxDriverValidator.cs +++ b/src/c#/GeneralUpdate.Drivelution/Linux/Implementation/LinuxDriverValidator.cs @@ -1,10 +1,9 @@ -using System.Diagnostics.CodeAnalysis; using System.Runtime.Versioning; +using GeneralUpdate.Common.Shared; using GeneralUpdate.Drivelution.Abstractions; using GeneralUpdate.Drivelution.Abstractions.Models; using GeneralUpdate.Drivelution.Core.Utilities; using GeneralUpdate.Drivelution.Linux.Helpers; -using Serilog; namespace GeneralUpdate.Drivelution.Linux.Implementation; @@ -15,11 +14,8 @@ namespace GeneralUpdate.Drivelution.Linux.Implementation; [SupportedOSPlatform("linux")] public class LinuxDriverValidator : IDriverValidator { - private readonly ILogger _logger; - - public LinuxDriverValidator(ILogger logger) + public LinuxDriverValidator() { - _logger = logger ?? throw new ArgumentNullException(nameof(logger)); } /// @@ -33,8 +29,6 @@ public async Task ValidateIntegrityAsync( } /// - [RequiresUnreferencedCode("Signature validation may require runtime reflection on some platforms")] - [RequiresDynamicCode("Signature validation may require runtime code generation on some platforms")] public async Task ValidateSignatureAsync( string filePath, IEnumerable trustedPublishers, @@ -52,7 +46,7 @@ public async Task ValidateSignatureAsync( return await LinuxSignatureHelper.ValidateGpgSignatureAsync(filePath, signaturePath, trustedPublishers); } - _logger.Warning("No signature file found for: {FilePath}", filePath); + GeneralTracer.Warn($"No signature file found for: {filePath}"); return !trustedPublishers.Any(); // If no trusted publishers specified, accept unsigned } diff --git a/src/c#/GeneralUpdate.Drivelution/Linux/Implementation/LinuxGeneralDrivelution.cs b/src/c#/GeneralUpdate.Drivelution/Linux/Implementation/LinuxGeneralDrivelution.cs index fa6f5058..7c9a3188 100644 --- a/src/c#/GeneralUpdate.Drivelution/Linux/Implementation/LinuxGeneralDrivelution.cs +++ b/src/c#/GeneralUpdate.Drivelution/Linux/Implementation/LinuxGeneralDrivelution.cs @@ -1,11 +1,10 @@ using System.Runtime.Versioning; -using System.Diagnostics.CodeAnalysis; +using GeneralUpdate.Common.Shared; using GeneralUpdate.Drivelution.Abstractions; using GeneralUpdate.Drivelution.Abstractions.Exceptions; using GeneralUpdate.Drivelution.Abstractions.Models; using GeneralUpdate.Drivelution.Core.Utilities; using GeneralUpdate.Drivelution.Linux.Helpers; -using Serilog; namespace GeneralUpdate.Drivelution.Linux.Implementation; @@ -16,20 +15,16 @@ namespace GeneralUpdate.Drivelution.Linux.Implementation; [SupportedOSPlatform("linux")] public class LinuxGeneralDrivelution : IGeneralDrivelution { - private readonly ILogger _logger; private readonly IDriverValidator _validator; private readonly IDriverBackup _backup; - public LinuxGeneralDrivelution(ILogger logger, IDriverValidator validator, IDriverBackup backup) + public LinuxGeneralDrivelution(IDriverValidator validator, IDriverBackup backup) { - _logger = logger ?? throw new ArgumentNullException(nameof(logger)); _validator = validator ?? throw new ArgumentNullException(nameof(validator)); _backup = backup ?? throw new ArgumentNullException(nameof(backup)); } /// - [RequiresUnreferencedCode("Update process may include signature validation that requires runtime reflection on some platforms")] - [RequiresDynamicCode("Update process may include signature validation that requires runtime code generation on some platforms")] public async Task UpdateAsync( DriverInfo driverInfo, UpdateStrategy strategy, @@ -43,8 +38,7 @@ public async Task UpdateAsync( try { - _logger.Information("Starting driver update for: {DriverName} v{Version}", - driverInfo.Name, driverInfo.Version); + GeneralTracer.Info($"Starting driver update for: {driverInfo.Name} v{driverInfo.Version}"); // Permission check await LinuxPermissionHelper.EnsureSudoAsync(); @@ -77,7 +71,7 @@ public async Task UpdateAsync( } catch (Exception ex) { - _logger.Error(ex, "Driver update failed"); + GeneralTracer.Error("Driver update failed", ex); result.Success = false; result.Status = UpdateStatus.Failed; result.Error = new ErrorInfo @@ -131,11 +125,11 @@ public async Task RollbackAsync(string backupPath, CancellationToken cance { try { - _logger.Information("Rolling back driver from backup: {BackupPath}", backupPath); + GeneralTracer.Info($"Rolling back driver from backup: {backupPath}"); if (!Directory.Exists(backupPath)) { - _logger.Error("Backup directory not found: {BackupPath}", backupPath); + GeneralTracer.Error($"Backup directory not found: {backupPath}"); return false; } @@ -144,7 +138,7 @@ public async Task RollbackAsync(string backupPath, CancellationToken cance if (!koFiles.Any()) { - _logger.Warning("No kernel module backups found in: {BackupPath}", backupPath); + GeneralTracer.Warn($"No kernel module backups found in: {backupPath}"); return false; } @@ -152,7 +146,7 @@ public async Task RollbackAsync(string backupPath, CancellationToken cance { try { - _logger.Information("Attempting to restore kernel module: {Module}", koFile); + GeneralTracer.Info($"Attempting to restore kernel module: {koFile}"); // Copy back to /lib/modules or appropriate location var moduleName = Path.GetFileNameWithoutExtension(koFile); @@ -161,11 +155,11 @@ public async Task RollbackAsync(string backupPath, CancellationToken cance await ExecuteCommandAsync("modprobe", $"-r {moduleName}", cancellationToken); // Try to reload the backed-up module (if system supports it) - _logger.Information("Restored module: {Module}", moduleName); + GeneralTracer.Info($"Restored module: {moduleName}"); } catch (Exception ex) { - _logger.Warning(ex, "Failed to restore module: {Module}", koFile); + GeneralTracer.Warn($"Failed to restore module: {koFile} - {ex.Message}"); } } @@ -173,14 +167,14 @@ public async Task RollbackAsync(string backupPath, CancellationToken cance } catch (Exception ex) { - _logger.Error(ex, "Failed to rollback driver"); + GeneralTracer.Error("Failed to rollback driver", ex); return false; } } private async Task ExecuteDriverInstallationAsync(DriverInfo driverInfo, CancellationToken cancellationToken) { - _logger.Information("Installing Linux driver: {DriverPath}", driverInfo.FilePath); + GeneralTracer.Info($"Installing Linux driver: {driverInfo.FilePath}"); var filePath = driverInfo.FilePath; var extension = Path.GetExtension(filePath).ToLowerInvariant(); @@ -205,16 +199,16 @@ private async Task ExecuteDriverInstallationAsync(DriverInfo driverInfo, Cancell } else { - _logger.Warning("Unknown driver format: {Extension}. Attempting generic installation.", extension); + GeneralTracer.Warn($"Unknown driver format: {extension}. Attempting generic installation."); // Try to detect and install generically await InstallKernelModuleAsync(filePath, cancellationToken); } - _logger.Information("Driver installation completed successfully"); + GeneralTracer.Info("Driver installation completed successfully"); } catch (Exception ex) { - _logger.Error(ex, "Failed to install Linux driver"); + GeneralTracer.Error("Failed to install Linux driver", ex); throw new DriverInstallationException( $"Failed to install Linux driver: {ex.Message}", ex); } @@ -222,39 +216,39 @@ private async Task ExecuteDriverInstallationAsync(DriverInfo driverInfo, Cancell private async Task InstallKernelModuleAsync(string modulePath, CancellationToken cancellationToken) { - _logger.Information("Installing kernel module: {ModulePath}", modulePath); + GeneralTracer.Info($"Installing kernel module: {modulePath}"); var moduleName = Path.GetFileNameWithoutExtension(modulePath); try { // Try to use insmod (direct installation) - _logger.Information("Attempting to load module using insmod"); + GeneralTracer.Info("Attempting to load module using insmod"); await ExecuteCommandAsync("insmod", modulePath, cancellationToken); - _logger.Information("Module loaded successfully using insmod"); + GeneralTracer.Info("Module loaded successfully using insmod"); } catch { try { // Fallback to modprobe if insmod fails - _logger.Information("Attempting to load module using modprobe"); + GeneralTracer.Info("Attempting to load module using modprobe"); // Copy to modules directory first (may require permissions) var kernelVersion = await GetKernelVersionAsync(cancellationToken); var targetDir = $"/lib/modules/{kernelVersion}/extra"; - _logger.Information("Target module directory: {TargetDir}", targetDir); + GeneralTracer.Info($"Target module directory: {targetDir}"); // Note: This would typically require root permissions // In a real scenario, you'd use sudo or elevated permissions await ExecuteCommandAsync("modprobe", moduleName, cancellationToken); - _logger.Information("Module loaded successfully using modprobe"); + GeneralTracer.Info("Module loaded successfully using modprobe"); } catch (Exception ex) { - _logger.Error(ex, "Failed to load kernel module"); + GeneralTracer.Error("Failed to load kernel module", ex); throw; } } @@ -262,24 +256,24 @@ private async Task InstallKernelModuleAsync(string modulePath, CancellationToken private async Task InstallDebPackageAsync(string packagePath, CancellationToken cancellationToken) { - _logger.Information("Installing Debian package: {PackagePath}", packagePath); + GeneralTracer.Info($"Installing Debian package: {packagePath}"); try { // Use dpkg to install the package await ExecuteCommandAsync("dpkg", $"-i {packagePath}", cancellationToken); - _logger.Information("Debian package installed successfully"); + GeneralTracer.Info("Debian package installed successfully"); } catch (Exception ex) { - _logger.Error(ex, "Failed to install Debian package"); + GeneralTracer.Error("Failed to install Debian package", ex); throw; } } private async Task InstallRpmPackageAsync(string packagePath, CancellationToken cancellationToken) { - _logger.Information("Installing RPM package: {PackagePath}", packagePath); + GeneralTracer.Info($"Installing RPM package: {packagePath}"); try { @@ -294,11 +288,11 @@ private async Task InstallRpmPackageAsync(string packagePath, CancellationToken await ExecuteCommandAsync("dnf", $"install -y {packagePath}", cancellationToken); } - _logger.Information("RPM package installed successfully"); + GeneralTracer.Info("RPM package installed successfully"); } catch (Exception ex) { - _logger.Error(ex, "Failed to install RPM package"); + GeneralTracer.Error("Failed to install RPM package", ex); throw; } } @@ -341,8 +335,7 @@ private async Task ExecuteCommandAsync(string command, string arguments, if (process.ExitCode != 0) { - _logger.Warning("Command {Command} {Arguments} exited with code {ExitCode}. Error: {Error}", - command, arguments, process.ExitCode, error); + GeneralTracer.Warn($"Command {command} {arguments} exited with code {process.ExitCode}. Error: {error}"); throw new InvalidOperationException($"Command failed with exit code {process.ExitCode}: {error}"); } @@ -370,11 +363,11 @@ public async Task> GetDriversFromDirectoryAsync( try { - _logger.Information("Reading driver information from directory: {DirectoryPath}", directoryPath); + GeneralTracer.Info($"Reading driver information from directory: {directoryPath}"); if (!Directory.Exists(directoryPath)) { - _logger.Warning("Directory not found: {DirectoryPath}", directoryPath); + GeneralTracer.Warn($"Directory not found: {directoryPath}"); return driverInfoList; } @@ -390,7 +383,7 @@ public async Task> GetDriversFromDirectoryAsync( driverFiles = driverFiles.Concat(debFiles).Concat(rpmFiles).ToArray(); } - _logger.Information("Found {Count} driver files matching pattern: {Pattern}", driverFiles.Length, pattern); + GeneralTracer.Info($"Found {driverFiles.Length} driver files matching pattern: {pattern}"); foreach (var filePath in driverFiles) { @@ -403,20 +396,20 @@ public async Task> GetDriversFromDirectoryAsync( if (driverInfo != null) { driverInfoList.Add(driverInfo); - _logger.Information("Parsed driver: {DriverName} v{Version}", driverInfo.Name, driverInfo.Version); + GeneralTracer.Info($"Parsed driver: {driverInfo.Name} v{driverInfo.Version}"); } } catch (Exception ex) { - _logger.Warning(ex, "Failed to parse driver file: {FilePath}", filePath); + GeneralTracer.Warn($"Failed to parse driver file: {filePath} - {ex.Message}"); } } - _logger.Information("Successfully loaded {Count} driver(s) from directory", driverInfoList.Count); + GeneralTracer.Info($"Successfully loaded {driverInfoList.Count} driver(s) from directory"); } catch (Exception ex) { - _logger.Error(ex, "Error reading drivers from directory: {DirectoryPath}", directoryPath); + GeneralTracer.Error($"Error reading drivers from directory: {directoryPath}", ex); } return driverInfoList; @@ -463,7 +456,7 @@ public async Task> GetDriversFromDirectoryAsync( } catch (Exception ex) { - _logger.Warning(ex, "Failed to parse driver file: {FilePath}", filePath); + GeneralTracer.Warn($"Failed to parse driver file: {filePath} - {ex.Message}"); return null; } } @@ -508,7 +501,7 @@ private async Task ParseKernelModuleAsync(string koPath, DriverInfo driverInfo, } catch (Exception ex) { - _logger.Debug(ex, "Could not get module info for: {KoPath}", koPath); + GeneralTracer.Debug($"Could not get module info for: {koPath} - {ex.Message}"); driverInfo.Version = "1.0.0"; } } @@ -547,7 +540,7 @@ private async Task ParseDebPackageAsync(string debPath, DriverInfo driverInfo, C } catch (Exception ex) { - _logger.Debug(ex, "Could not get package info for: {DebPath}", debPath); + GeneralTracer.Debug($"Could not get package info for: {debPath} - {ex.Message}"); driverInfo.Version = "1.0.0"; } } @@ -594,7 +587,7 @@ private async Task ParseRpmPackageAsync(string rpmPath, DriverInfo driverInfo, C } catch (Exception ex) { - _logger.Debug(ex, "Could not get package info for: {RpmPath}", rpmPath); + GeneralTracer.Debug($"Could not get package info for: {rpmPath} - {ex.Message}"); driverInfo.Version = "1.0.0"; } } diff --git a/src/c#/GeneralUpdate.Drivelution/MacOS/Implementation/MacOsGeneralDrivelution.cs b/src/c#/GeneralUpdate.Drivelution/MacOS/Implementation/MacOsGeneralDrivelution.cs index 2cfd84a6..d23a345d 100644 --- a/src/c#/GeneralUpdate.Drivelution/MacOS/Implementation/MacOsGeneralDrivelution.cs +++ b/src/c#/GeneralUpdate.Drivelution/MacOS/Implementation/MacOsGeneralDrivelution.cs @@ -1,4 +1,3 @@ -using System.Diagnostics.CodeAnalysis; using System.Runtime.Versioning; using GeneralUpdate.Drivelution.Abstractions; using GeneralUpdate.Drivelution.Abstractions.Models; @@ -24,8 +23,6 @@ namespace GeneralUpdate.Drivelution.MacOS.Implementation; public class MacOsGeneralDrivelution : IGeneralDrivelution { /// - [RequiresUnreferencedCode("Update process may include signature validation that requires runtime reflection on some platforms")] - [RequiresDynamicCode("Update process may include signature validation that requires runtime code generation on some platforms")] public Task UpdateAsync( DriverInfo driverInfo, UpdateStrategy strategy, @@ -37,8 +34,6 @@ public Task UpdateAsync( } /// - [RequiresUnreferencedCode("Validation includes signature validation that may require runtime reflection on some platforms")] - [RequiresDynamicCode("Validation includes signature validation that may require runtime code generation on some platforms")] public Task ValidateAsync( DriverInfo driverInfo, CancellationToken cancellationToken = default) @@ -96,8 +91,6 @@ public Task ValidateIntegrityAsync( } /// - [RequiresUnreferencedCode("Signature validation may require runtime reflection on some platforms")] - [RequiresDynamicCode("Signature validation may require runtime code generation on some platforms")] public Task ValidateSignatureAsync( string filePath, IEnumerable trustedPublishers, diff --git a/src/c#/GeneralUpdate.Drivelution/Windows/Helpers/WindowsSignatureHelper.cs b/src/c#/GeneralUpdate.Drivelution/Windows/Helpers/WindowsSignatureHelper.cs index 655dd1ea..60747c09 100644 --- a/src/c#/GeneralUpdate.Drivelution/Windows/Helpers/WindowsSignatureHelper.cs +++ b/src/c#/GeneralUpdate.Drivelution/Windows/Helpers/WindowsSignatureHelper.cs @@ -1,7 +1,6 @@ using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security.Cryptography.X509Certificates; -using System.Diagnostics.CodeAnalysis; using GeneralUpdate.Drivelution.Abstractions.Exceptions; namespace GeneralUpdate.Drivelution.Windows.Helpers; @@ -20,8 +19,6 @@ public static class WindowsSignatureHelper /// 文件路径 / File path /// 信任的发布者列表 / Trusted publishers list /// 是否验证通过 / Whether validation succeeded - [RequiresUnreferencedCode("X509Certificate validation may require runtime reflection")] - [RequiresDynamicCode("X509Certificate validation may require runtime code generation")] public static async Task ValidateAuthenticodeSignatureAsync(string filePath, IEnumerable trustedPublishers) { return await Task.Run(() => ValidateAuthenticodeSignature(filePath, trustedPublishers)); @@ -34,8 +31,6 @@ public static async Task ValidateAuthenticodeSignatureAsync(string filePat /// 文件路径 / File path /// 信任的发布者列表 / Trusted publishers list /// 是否验证通过 / Whether validation succeeded - [RequiresUnreferencedCode("X509Certificate validation may require runtime reflection")] - [RequiresDynamicCode("X509Certificate validation may require runtime code generation")] public static bool ValidateAuthenticodeSignature(string filePath, IEnumerable trustedPublishers) { if (!File.Exists(filePath)) @@ -118,8 +113,6 @@ public static bool ValidateAuthenticodeSignature(string filePath, IEnumerable /// 文件路径 / File path /// 是否已签名 / Whether signed - [RequiresUnreferencedCode("X509Certificate validation may require runtime reflection")] - [RequiresDynamicCode("X509Certificate validation may require runtime code generation")] public static bool IsFileSigned(string filePath) { if (!File.Exists(filePath)) diff --git a/src/c#/GeneralUpdate.Drivelution/Windows/Implementation/WindowsDriverBackup.cs b/src/c#/GeneralUpdate.Drivelution/Windows/Implementation/WindowsDriverBackup.cs index ffb53f59..40f88f42 100644 --- a/src/c#/GeneralUpdate.Drivelution/Windows/Implementation/WindowsDriverBackup.cs +++ b/src/c#/GeneralUpdate.Drivelution/Windows/Implementation/WindowsDriverBackup.cs @@ -1,7 +1,7 @@ using System.Runtime.Versioning; +using GeneralUpdate.Common.Shared; using GeneralUpdate.Drivelution.Abstractions; using GeneralUpdate.Drivelution.Abstractions.Exceptions; -using Serilog; namespace GeneralUpdate.Drivelution.Windows.Implementation; @@ -12,11 +12,8 @@ namespace GeneralUpdate.Drivelution.Windows.Implementation; [SupportedOSPlatform("windows")] public class WindowsDriverBackup : IDriverBackup { - private readonly ILogger _logger; - - public WindowsDriverBackup(ILogger logger) + public WindowsDriverBackup() { - _logger = logger ?? throw new ArgumentNullException(nameof(logger)); } /// @@ -25,7 +22,7 @@ public async Task BackupAsync( string backupPath, CancellationToken cancellationToken = default) { - _logger.Information("Backing up driver from {SourcePath} to {BackupPath}", sourcePath, backupPath); + GeneralTracer.Info($"Backing up driver from {sourcePath} to {backupPath}"); try { @@ -39,7 +36,7 @@ public async Task BackupAsync( if (!string.IsNullOrEmpty(backupDir) && !Directory.Exists(backupDir)) { Directory.CreateDirectory(backupDir); - _logger.Information("Created backup directory: {BackupDir}", backupDir); + GeneralTracer.Info($"Created backup directory: {backupDir}"); } // Add timestamp to backup filename to avoid conflicts @@ -57,12 +54,12 @@ public async Task BackupAsync( await sourceStream.CopyToAsync(destinationStream, cancellationToken); } - _logger.Information("Driver backup completed successfully: {BackupPath}", backupPathWithTimestamp); + GeneralTracer.Info($"Driver backup completed successfully: {backupPathWithTimestamp}"); return true; } catch (Exception ex) { - _logger.Error(ex, "Failed to backup driver"); + GeneralTracer.Error("Failed to backup driver", ex); throw new DriverBackupException($"Failed to backup driver: {ex.Message}", ex); } } @@ -73,7 +70,7 @@ public async Task RestoreAsync( string targetPath, CancellationToken cancellationToken = default) { - _logger.Information("Restoring driver from {BackupPath} to {TargetPath}", backupPath, targetPath); + GeneralTracer.Info($"Restoring driver from {backupPath} to {targetPath}"); try { @@ -87,7 +84,7 @@ public async Task RestoreAsync( if (!string.IsNullOrEmpty(targetDir) && !Directory.Exists(targetDir)) { Directory.CreateDirectory(targetDir); - _logger.Information("Created target directory: {TargetDir}", targetDir); + GeneralTracer.Info($"Created target directory: {targetDir}"); } // Backup existing target file if it exists @@ -95,7 +92,7 @@ public async Task RestoreAsync( { var tempBackup = $"{targetPath}.old"; File.Move(targetPath, tempBackup, true); - _logger.Information("Moved existing file to temporary backup: {TempBackup}", tempBackup); + GeneralTracer.Info($"Moved existing file to temporary backup: {tempBackup}"); } // Copy backup file to target location @@ -105,12 +102,12 @@ public async Task RestoreAsync( await sourceStream.CopyToAsync(destinationStream, cancellationToken); } - _logger.Information("Driver restore completed successfully"); + GeneralTracer.Info("Driver restore completed successfully"); return true; } catch (Exception ex) { - _logger.Error(ex, "Failed to restore driver"); + GeneralTracer.Error("Failed to restore driver", ex); throw new DriverRollbackException($"Failed to restore driver: {ex.Message}", ex); } } @@ -120,7 +117,7 @@ public async Task DeleteBackupAsync( string backupPath, CancellationToken cancellationToken = default) { - _logger.Information("Deleting backup: {BackupPath}", backupPath); + GeneralTracer.Info($"Deleting backup: {backupPath}"); return await Task.Run(() => { @@ -129,18 +126,18 @@ public async Task DeleteBackupAsync( if (File.Exists(backupPath)) { File.Delete(backupPath); - _logger.Information("Backup deleted successfully"); + GeneralTracer.Info("Backup deleted successfully"); return true; } else { - _logger.Warning("Backup file not found: {BackupPath}", backupPath); + GeneralTracer.Warn($"Backup file not found: {backupPath}"); return false; } } catch (Exception ex) { - _logger.Error(ex, "Failed to delete backup"); + GeneralTracer.Error("Failed to delete backup", ex); return false; } }, cancellationToken); diff --git a/src/c#/GeneralUpdate.Drivelution/Windows/Implementation/WindowsDriverValidator.cs b/src/c#/GeneralUpdate.Drivelution/Windows/Implementation/WindowsDriverValidator.cs index c92af9b1..d3cff48c 100644 --- a/src/c#/GeneralUpdate.Drivelution/Windows/Implementation/WindowsDriverValidator.cs +++ b/src/c#/GeneralUpdate.Drivelution/Windows/Implementation/WindowsDriverValidator.cs @@ -1,11 +1,10 @@ -using System.Diagnostics.CodeAnalysis; using System.Runtime.Versioning; +using GeneralUpdate.Common.Shared; using GeneralUpdate.Drivelution.Abstractions; using GeneralUpdate.Drivelution.Abstractions.Exceptions; using GeneralUpdate.Drivelution.Abstractions.Models; using GeneralUpdate.Drivelution.Core.Utilities; using GeneralUpdate.Drivelution.Windows.Helpers; -using Serilog; namespace GeneralUpdate.Drivelution.Windows.Implementation; @@ -16,11 +15,8 @@ namespace GeneralUpdate.Drivelution.Windows.Implementation; [SupportedOSPlatform("windows")] public class WindowsDriverValidator : IDriverValidator { - private readonly ILogger _logger; - - public WindowsDriverValidator(ILogger logger) + public WindowsDriverValidator() { - _logger = logger ?? throw new ArgumentNullException(nameof(logger)); } /// @@ -30,7 +26,7 @@ public async Task ValidateIntegrityAsync( string hashAlgorithm = "SHA256", CancellationToken cancellationToken = default) { - _logger.Information("Validating file integrity: {FilePath}", filePath); + GeneralTracer.Info($"Validating file integrity: {filePath}"); try { @@ -38,18 +34,18 @@ public async Task ValidateIntegrityAsync( if (isValid) { - _logger.Information("File integrity validation succeeded"); + GeneralTracer.Info("File integrity validation succeeded"); } else { - _logger.Warning("File integrity validation failed - hash mismatch"); + GeneralTracer.Warn("File integrity validation failed - hash mismatch"); } return isValid; } catch (Exception ex) { - _logger.Error(ex, "File integrity validation failed with exception"); + GeneralTracer.Error("File integrity validation failed with exception", ex); throw new DriverValidationException( $"Failed to validate file integrity: {ex.Message}", "Integrity", @@ -58,14 +54,12 @@ public async Task ValidateIntegrityAsync( } /// - [RequiresUnreferencedCode("X509Certificate validation may require runtime reflection")] - [RequiresDynamicCode("X509Certificate validation may require runtime code generation")] public async Task ValidateSignatureAsync( string filePath, IEnumerable trustedPublishers, CancellationToken cancellationToken = default) { - _logger.Information("Validating driver signature: {FilePath}", filePath); + GeneralTracer.Info($"Validating driver signature: {filePath}"); try { @@ -73,18 +67,18 @@ public async Task ValidateSignatureAsync( if (isValid) { - _logger.Information("Driver signature validation succeeded"); + GeneralTracer.Info("Driver signature validation succeeded"); } else { - _logger.Warning("Driver signature validation failed"); + GeneralTracer.Warn("Driver signature validation failed"); } return isValid; } catch (Exception ex) { - _logger.Error(ex, "Driver signature validation failed with exception"); + GeneralTracer.Error("Driver signature validation failed with exception", ex); throw new DriverValidationException( $"Failed to validate driver signature: {ex.Message}", "Signature", @@ -97,7 +91,7 @@ public async Task ValidateCompatibilityAsync( DriverInfo driverInfo, CancellationToken cancellationToken = default) { - _logger.Information("Validating driver compatibility for: {DriverName}", driverInfo.Name); + GeneralTracer.Info($"Validating driver compatibility for: {driverInfo.Name}"); try { @@ -105,22 +99,21 @@ public async Task ValidateCompatibilityAsync( if (isCompatible) { - _logger.Information("Driver compatibility validation succeeded"); + GeneralTracer.Info("Driver compatibility validation succeeded"); } else { - _logger.Warning("Driver compatibility validation failed"); + GeneralTracer.Warn("Driver compatibility validation failed"); var report = CompatibilityChecker.GetCompatibilityReport(driverInfo); - _logger.Warning("Compatibility report: Current OS={CurrentOS}, Target OS={TargetOS}, " + - "Current Arch={CurrentArch}, Target Arch={TargetArch}", - report.CurrentOS, report.TargetOS, report.CurrentArchitecture, report.TargetArchitecture); + GeneralTracer.Warn($"Compatibility report: Current OS={report.CurrentOS}, Target OS={report.TargetOS}, " + + $"Current Arch={report.CurrentArchitecture}, Target Arch={report.TargetArchitecture}"); } return isCompatible; } catch (Exception ex) { - _logger.Error(ex, "Driver compatibility validation failed with exception"); + GeneralTracer.Error("Driver compatibility validation failed with exception", ex); throw new DriverValidationException( $"Failed to validate driver compatibility: {ex.Message}", "Compatibility", diff --git a/src/c#/GeneralUpdate.Drivelution/Windows/Implementation/WindowsGeneralDrivelution.cs b/src/c#/GeneralUpdate.Drivelution/Windows/Implementation/WindowsGeneralDrivelution.cs index df7ba8fe..bbcdc600 100644 --- a/src/c#/GeneralUpdate.Drivelution/Windows/Implementation/WindowsGeneralDrivelution.cs +++ b/src/c#/GeneralUpdate.Drivelution/Windows/Implementation/WindowsGeneralDrivelution.cs @@ -1,11 +1,11 @@ using System.Diagnostics; using System.Runtime.Versioning; +using GeneralUpdate.Common.Shared; using GeneralUpdate.Drivelution.Abstractions; using GeneralUpdate.Drivelution.Abstractions.Exceptions; using GeneralUpdate.Drivelution.Abstractions.Models; using GeneralUpdate.Drivelution.Core.Utilities; using GeneralUpdate.Drivelution.Windows.Helpers; -using Serilog; namespace GeneralUpdate.Drivelution.Windows.Implementation; @@ -16,13 +16,11 @@ namespace GeneralUpdate.Drivelution.Windows.Implementation; [SupportedOSPlatform("windows")] public class WindowsGeneralDrivelution : IGeneralDrivelution { - private readonly ILogger _logger; private readonly IDriverValidator _validator; private readonly IDriverBackup _backup; - public WindowsGeneralDrivelution(ILogger logger, IDriverValidator validator, IDriverBackup backup) + public WindowsGeneralDrivelution(IDriverValidator validator, IDriverBackup backup) { - _logger = logger ?? throw new ArgumentNullException(nameof(logger)); _validator = validator ?? throw new ArgumentNullException(nameof(validator)); _backup = backup ?? throw new ArgumentNullException(nameof(backup)); } @@ -41,13 +39,12 @@ public async Task UpdateAsync( try { - _logger.Information("Starting driver update for: {DriverName} v{Version}", - driverInfo.Name, driverInfo.Version); + GeneralTracer.Info($"Starting driver update for: {driverInfo.Name} v{driverInfo.Version}"); result.StepLogs.Add($"[{DateTime.Now:HH:mm:ss}] Starting driver update"); // Step 1: Permission check - _logger.Information("Checking permissions..."); + GeneralTracer.Info("Checking permissions..."); result.StepLogs.Add($"[{DateTime.Now:HH:mm:ss}] Checking permissions"); if (!WindowsPermissionHelper.IsAdministrator()) @@ -78,7 +75,7 @@ public async Task UpdateAsync( if (await BackupAsync(driverInfo, backupPath, cancellationToken)) { result.BackupPath = backupPath; - _logger.Information("Backup created at: {BackupPath}", backupPath); + GeneralTracer.Info($"Backup created at: {backupPath}"); } } @@ -95,16 +92,16 @@ public async Task UpdateAsync( bool verified = await VerifyDriverInstallationAsync(driverInfo, cancellationToken); if (!verified) { - _logger.Warning("Driver installation verification failed"); + GeneralTracer.Warn("Driver installation verification failed"); result.StepLogs.Add($"[{DateTime.Now:HH:mm:ss}] WARNING: Installation verification failed"); } - _logger.Information("Driver installation verification completed"); + GeneralTracer.Info("Driver installation verification completed"); // Step 6: Handle restart if needed if (RestartHelper.IsRestartRequired(strategy.RestartMode)) { result.StepLogs.Add($"[{DateTime.Now:HH:mm:ss}] System restart is required"); - _logger.Information("System restart is required for driver update"); + GeneralTracer.Info("System restart is required for driver update"); } result.Success = true; @@ -112,11 +109,11 @@ public async Task UpdateAsync( result.Message = "Driver update completed successfully"; result.StepLogs.Add($"[{DateTime.Now:HH:mm:ss}] Update completed successfully"); - _logger.Information("Driver update completed successfully"); + GeneralTracer.Info("Driver update completed successfully"); } catch (DriverPermissionException ex) { - _logger.Error(ex, "Permission denied during driver update"); + GeneralTracer.Error("Permission denied during driver update", ex); result.Success = false; result.Status = UpdateStatus.Failed; result.Error = CreateErrorInfo(ex, ErrorType.PermissionDenied, false); @@ -124,7 +121,7 @@ public async Task UpdateAsync( } catch (DriverValidationException ex) { - _logger.Error(ex, "Validation failed during driver update"); + GeneralTracer.Error("Validation failed during driver update", ex); result.Success = false; result.Status = UpdateStatus.Failed; result.Error = CreateErrorInfo(ex, ErrorType.HashValidationFailed, false); @@ -132,7 +129,7 @@ public async Task UpdateAsync( } catch (DriverInstallationException ex) { - _logger.Error(ex, "Installation failed during driver update"); + GeneralTracer.Error("Installation failed during driver update", ex); result.Success = false; result.Status = UpdateStatus.Failed; result.Error = CreateErrorInfo(ex, ErrorType.InstallationFailed, ex.CanRetry); @@ -152,7 +149,7 @@ public async Task UpdateAsync( } catch (Exception ex) { - _logger.Error(ex, "Unexpected error during driver update"); + GeneralTracer.Error("Unexpected error during driver update", ex); result.Success = false; result.Status = UpdateStatus.Failed; result.Error = CreateErrorInfo(ex, ErrorType.Unknown, false); @@ -161,8 +158,7 @@ public async Task UpdateAsync( finally { result.EndTime = DateTime.UtcNow; - _logger.Information("Driver update process ended. Duration: {Duration}ms, Success: {Success}", - result.DurationMs, result.Success); + GeneralTracer.Info($"Driver update process ended. Duration: {result.DurationMs}ms, Success: {result.Success}"); } return result; @@ -171,14 +167,14 @@ public async Task UpdateAsync( /// public async Task ValidateAsync(DriverInfo driverInfo, CancellationToken cancellationToken = default) { - _logger.Information("Validating driver: {DriverName}", driverInfo.Name); + GeneralTracer.Info($"Validating driver: {driverInfo.Name}"); try { // Validate file exists if (!File.Exists(driverInfo.FilePath)) { - _logger.Error("Driver file not found: {FilePath}", driverInfo.FilePath); + GeneralTracer.Error($"Driver file not found: {driverInfo.FilePath}"); return false; } @@ -217,7 +213,7 @@ public async Task ValidateAsync(DriverInfo driverInfo, CancellationToken c } catch (Exception ex) { - _logger.Error(ex, "Driver validation failed"); + GeneralTracer.Error("Driver validation failed", ex); return false; } } @@ -231,7 +227,7 @@ public async Task BackupAsync(DriverInfo driverInfo, string backupPath, Ca } catch (Exception ex) { - _logger.Error(ex, "Failed to backup driver"); + GeneralTracer.Error("Failed to backup driver", ex); return false; } } @@ -241,7 +237,7 @@ public async Task RollbackAsync(string backupPath, CancellationToken cance { try { - _logger.Information("Rolling back driver from backup: {BackupPath}", backupPath); + GeneralTracer.Info($"Rolling back driver from backup: {backupPath}"); // Implement rollback logic // This involves: @@ -250,7 +246,7 @@ public async Task RollbackAsync(string backupPath, CancellationToken cance if (!Directory.Exists(backupPath)) { - _logger.Error("Backup directory not found: {BackupPath}", backupPath); + GeneralTracer.Error($"Backup directory not found: {backupPath}"); return false; } @@ -258,11 +254,11 @@ public async Task RollbackAsync(string backupPath, CancellationToken cance var backupFiles = Directory.GetFiles(backupPath, "*.*", SearchOption.AllDirectories); if (!backupFiles.Any()) { - _logger.Warning("No backup files found in: {BackupPath}", backupPath); + GeneralTracer.Warn($"No backup files found in: {backupPath}"); return false; } - _logger.Information("Found {Count} backup files", backupFiles.Length); + GeneralTracer.Info($"Found {backupFiles.Length} backup files"); // For INF-based drivers, try to reinstall the backed up version var infFiles = backupFiles.Where(f => f.EndsWith(".inf", StringComparison.OrdinalIgnoreCase)).ToArray(); @@ -273,12 +269,12 @@ public async Task RollbackAsync(string backupPath, CancellationToken cance { try { - _logger.Information("Attempting to restore driver from: {InfFile}", infFile); + GeneralTracer.Info($"Attempting to restore driver from: {infFile}"); await InstallDriverUsingPnPUtilAsync(infFile, cancellationToken); } catch (Exception ex) { - _logger.Warning(ex, "Failed to restore driver from: {InfFile}", infFile); + GeneralTracer.Warn($"Failed to restore driver from: {infFile} - {ex.Message}"); } } } @@ -287,7 +283,7 @@ public async Task RollbackAsync(string backupPath, CancellationToken cance } catch (Exception ex) { - _logger.Error(ex, "Failed to rollback driver"); + GeneralTracer.Error("Failed to rollback driver", ex); throw new DriverRollbackException($"Failed to rollback driver: {ex.Message}", ex); } } @@ -301,7 +297,7 @@ private async Task ExecuteDriverInstallationAsync( UpdateStrategy strategy, CancellationToken cancellationToken) { - _logger.Information("Executing driver installation: {DriverPath}", driverInfo.FilePath); + GeneralTracer.Info($"Executing driver installation: {driverInfo.FilePath}"); try { @@ -317,7 +313,7 @@ private async Task ExecuteDriverInstallationAsync( } catch (Exception ex) { - _logger.Error(ex, "Driver installation failed"); + GeneralTracer.Error("Driver installation failed", ex); throw new DriverInstallationException($"Failed to install driver: {ex.Message}", ex); } } @@ -328,7 +324,7 @@ private async Task ExecuteDriverInstallationAsync( /// private async Task InstallDriverUsingPnPUtilAsync(string driverPath, CancellationToken cancellationToken) { - _logger.Information("Installing driver using PnPUtil: {DriverPath}", driverPath); + GeneralTracer.Info($"Installing driver using PnPUtil: {driverPath}"); var startInfo = new ProcessStartInfo { @@ -348,12 +344,11 @@ private async Task InstallDriverUsingPnPUtilAsync(string driverPath, Cancellatio await process.WaitForExitAsync(cancellationToken); - _logger.Information("PnPUtil output: {Output}", output); + GeneralTracer.Info($"PnPUtil output: {output}"); if (process.ExitCode != 0) { - _logger.Error("PnPUtil failed with exit code {ExitCode}. Error: {Error}", - process.ExitCode, error); + GeneralTracer.Error($"PnPUtil failed with exit code {process.ExitCode}. Error: {error}"); throw new DriverInstallationException( $"PnPUtil failed with exit code {process.ExitCode}: {error}"); } @@ -367,7 +362,7 @@ private async Task VerifyDriverInstallationAsync(DriverInfo driverInfo, Ca { try { - _logger.Information("Verifying driver installation for: {DriverPath}", driverInfo.FilePath); + GeneralTracer.Info($"Verifying driver installation for: {driverInfo.FilePath}"); // Use PnPUtil to enumerate installed drivers and check if our driver is present var processStartInfo = new ProcessStartInfo @@ -383,7 +378,7 @@ private async Task VerifyDriverInstallationAsync(DriverInfo driverInfo, Ca using var process = Process.Start(processStartInfo); if (process == null) { - _logger.Warning("Failed to start PnPUtil for verification"); + GeneralTracer.Warn("Failed to start PnPUtil for verification"); return false; } @@ -395,12 +390,12 @@ private async Task VerifyDriverInstallationAsync(DriverInfo driverInfo, Ca bool isInstalled = output.Contains(driverFileName, StringComparison.OrdinalIgnoreCase) || output.Contains(Path.GetFileNameWithoutExtension(driverInfo.FilePath), StringComparison.OrdinalIgnoreCase); - _logger.Information("Driver verification result: {IsInstalled}", isInstalled); + GeneralTracer.Info($"Driver verification result: {isInstalled}"); return isInstalled; } catch (Exception ex) { - _logger.Warning(ex, "Failed to verify driver installation"); + GeneralTracer.Warn($"Failed to verify driver installation - {ex.Message}"); // Return true to not block the update if verification fails return true; } @@ -425,7 +420,7 @@ private async Task TryRollbackAsync(string backupPath, CancellationToken c } catch (Exception ex) { - _logger.Error(ex, "Rollback failed"); + GeneralTracer.Error("Rollback failed", ex); return false; } } @@ -468,11 +463,11 @@ public async Task> GetDriversFromDirectoryAsync( try { - _logger.Information("Reading driver information from directory: {DirectoryPath}", directoryPath); + GeneralTracer.Info($"Reading driver information from directory: {directoryPath}"); if (!Directory.Exists(directoryPath)) { - _logger.Warning("Directory not found: {DirectoryPath}", directoryPath); + GeneralTracer.Warn($"Directory not found: {directoryPath}"); return driverInfoList; } @@ -480,7 +475,7 @@ public async Task> GetDriversFromDirectoryAsync( var pattern = searchPattern ?? "*.inf"; var driverFiles = Directory.GetFiles(directoryPath, pattern, SearchOption.AllDirectories); - _logger.Information("Found {Count} driver files matching pattern: {Pattern}", driverFiles.Length, pattern); + GeneralTracer.Info($"Found {driverFiles.Length} driver files matching pattern: {pattern}"); foreach (var filePath in driverFiles) { @@ -493,20 +488,20 @@ public async Task> GetDriversFromDirectoryAsync( if (driverInfo != null) { driverInfoList.Add(driverInfo); - _logger.Information("Parsed driver: {DriverName} v{Version}", driverInfo.Name, driverInfo.Version); + GeneralTracer.Info($"Parsed driver: {driverInfo.Name} v{driverInfo.Version}"); } } catch (Exception ex) { - _logger.Warning(ex, "Failed to parse driver file: {FilePath}", filePath); + GeneralTracer.Warn($"Failed to parse driver file: {filePath} - {ex.Message}"); } } - _logger.Information("Successfully loaded {Count} driver(s) from directory", driverInfoList.Count); + GeneralTracer.Info($"Successfully loaded {driverInfoList.Count} driver(s) from directory"); } catch (Exception ex) { - _logger.Error(ex, "Error reading drivers from directory: {DirectoryPath}", directoryPath); + GeneralTracer.Error($"Error reading drivers from directory: {directoryPath}", ex); } return driverInfoList; @@ -576,14 +571,14 @@ public async Task> GetDriversFromDirectoryAsync( } catch (Exception ex) { - _logger.Debug(ex, "Could not get signature for file: {FilePath}", filePath); + GeneralTracer.Debug($"Could not get signature for file: {filePath} - {ex.Message}"); } return driverInfo; } catch (Exception ex) { - _logger.Warning(ex, "Failed to parse driver file: {FilePath}", filePath); + GeneralTracer.Warn($"Failed to parse driver file: {filePath} - {ex.Message}"); return null; } } @@ -648,7 +643,7 @@ private async Task ParseInfFileAsync(string infPath, DriverInfo driverInfo, Canc } catch (Exception ex) { - _logger.Debug(ex, "Could not parse INF file: {InfPath}", infPath); + GeneralTracer.Debug($"Could not parse INF file: {infPath} - {ex.Message}"); } } }