diff --git a/src/Files.App/App.xaml.cs b/src/Files.App/App.xaml.cs index 7d63f5257fc7..75248cba6c3e 100644 --- a/src/Files.App/App.xaml.cs +++ b/src/Files.App/App.xaml.cs @@ -32,12 +32,14 @@ using Microsoft.AppCenter.Crashes; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; using Microsoft.UI.Windowing; using Microsoft.UI.Xaml; using Microsoft.UI.Xaml.Controls; using Microsoft.Windows.AppLifecycle; using System; using System.Diagnostics; +using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; @@ -46,8 +48,6 @@ using Windows.Storage; using Windows.UI.Notifications; -// To learn more about WinUI, the WinUI project structure, -// and more about our project templates, see: http://aka.ms/winui-project-info. namespace Files.App { @@ -72,7 +72,6 @@ public partial class App : Application public static FileTagsManager FileTagsManager { get; private set; } public static ILogger Logger { get; private set; } - private static readonly UniversalLogWriter logWriter = new UniversalLogWriter(); public static SecondaryTileHelper SecondaryTileHelper { get; private set; } = new SecondaryTileHelper(); public static string AppVersion = $"{Package.Current.Id.Version.Major}.{Package.Current.Id.Version.Minor}.{Package.Current.Id.Version.Build}.{Package.Current.Id.Version.Revision}"; @@ -86,9 +85,6 @@ public partial class App : Application /// public App() { - // Initialize logger - Logger = new Logger(logWriter); - UnhandledException += OnUnhandledException; TaskScheduler.UnobservedTaskException += OnUnobservedException; InitializeComponent(); @@ -119,7 +115,7 @@ private static Task StartAppCenter() } catch (Exception ex) { - Logger.Warn(ex, "AppCenter could not be started."); + App.Logger.LogWarning(ex, "AppCenter could not be started."); } return Task.CompletedTask; @@ -174,9 +170,7 @@ protected override void OnLaunched(LaunchActivatedEventArgs e) { var activatedEventArgs = Microsoft.Windows.AppLifecycle.AppInstance.GetCurrent().GetActivatedEventArgs(); - Task.Run(async () => await logWriter.InitializeAsync("debug.log")); - Logger.Info($"App launched. Launch args type: {activatedEventArgs.Data.GetType().Name}"); - + var logPath = Path.Combine(ApplicationData.Current.LocalFolder.Path, "debug.log"); //start tracking app usage if (activatedEventArgs.Data is Windows.ApplicationModel.Activation.IActivatedEventArgs iaea) SystemInformation.Instance.TrackAppUse(iaea); @@ -184,6 +178,11 @@ protected override void OnLaunched(LaunchActivatedEventArgs e) // Initialize MainWindow here EnsureWindowIsInitialized(); host = Host.CreateDefaultBuilder() + .ConfigureLogging(builder => + builder + .AddProvider(new FileLoggerProvider(logPath)) + .SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Information) + ) .ConfigureServices(services => services .AddSingleton() @@ -201,7 +200,6 @@ protected override void OnLaunched(LaunchActivatedEventArgs e) .AddSingleton() .AddSingleton() .AddSingleton() - .AddSingleton(Logger) .AddSingleton() .AddSingleton() .AddSingleton() @@ -235,10 +233,13 @@ protected override void OnLaunched(LaunchActivatedEventArgs e) .AddSingleton() ) .Build(); + Logger = host.Services.GetRequiredService>(); + App.Logger.LogInformation($"App launched. Launch args type: {activatedEventArgs.Data.GetType().Name}"); + Ioc.Default.ConfigureServices(host.Services); EnsureSettingsAndConfigurationAreBootstrapped(); - _ = InitializeAppComponentsAsync().ContinueWith(t => Logger.Warn(t.Exception, "Error during InitializeAppComponentsAsync()"), TaskContinuationOptions.OnlyOnFaulted); + _ = InitializeAppComponentsAsync().ContinueWith(t => Logger.LogWarning(t.Exception, "Error during InitializeAppComponentsAsync()"), TaskContinuationOptions.OnlyOnFaulted); _ = Window.InitializeApplication(activatedEventArgs.Data); } @@ -263,7 +264,7 @@ private void Window_Activated(object sender, WindowActivatedEventArgs args) public void OnActivated(AppActivationArguments activatedEventArgs) { - Logger.Info($"App activated. Activated args type: {activatedEventArgs.Data.GetType().Name}"); + App.Logger.LogInformation($"App activated. Activated args type: {activatedEventArgs.Data.GetType().Name}"); var data = activatedEventArgs.Data; // InitializeApplication accesses UI, needs to be called on UI thread _ = Window.DispatcherQueue.EnqueueAsync(() => Window.InitializeApplication(data)); @@ -391,7 +392,7 @@ private static void AppUnhandledException(Exception ex, bool shouldShowNotificat Debugger.Break(); // Please check "Output Window" for exception details (View -> Output Window) (CTRL + ALT + O) SaveSessionTabs(); - Logger.UnhandledError(ex, ex.Message); + App.Logger.LogError(ex, ex.Message); if (!ShowErrorNotification || !shouldShowNotification) return; diff --git a/src/Files.App/Files.App.csproj b/src/Files.App/Files.App.csproj index 59c8b0a1a8c0..81ddb34feae2 100644 --- a/src/Files.App/Files.App.csproj +++ b/src/Files.App/Files.App.csproj @@ -80,6 +80,7 @@ + diff --git a/src/Files.App/Filesystem/Archive/ArchiveCreator.cs b/src/Files.App/Filesystem/Archive/ArchiveCreator.cs index afae2d7581df..cb8201f86704 100644 --- a/src/Files.App/Filesystem/Archive/ArchiveCreator.cs +++ b/src/Files.App/Filesystem/Archive/ArchiveCreator.cs @@ -1,5 +1,6 @@ using CommunityToolkit.Mvvm.DependencyInjection; using Files.Shared; +using Microsoft.Extensions.Logging; using SevenZip; using System; using System.Collections.Generic; @@ -144,8 +145,8 @@ public async Task RunCreationAsync() } catch (Exception ex) { - var logger = Ioc.Default.GetService(); - logger?.Warn(ex, $"Error compressing folder: {archivePath}"); + var logger = Ioc.Default.GetRequiredService>(); + logger?.LogWarning(ex, $"Error compressing folder: {archivePath}"); return false; } diff --git a/src/Files.App/Filesystem/Cloud/CloudDrivesManager.cs b/src/Files.App/Filesystem/Cloud/CloudDrivesManager.cs index 08b14db10cd4..b7db74982556 100644 --- a/src/Files.App/Filesystem/Cloud/CloudDrivesManager.cs +++ b/src/Files.App/Filesystem/Cloud/CloudDrivesManager.cs @@ -4,6 +4,7 @@ using Files.App.Helpers; using Files.Shared; using Files.Shared.Cloud; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Collections.Specialized; @@ -15,7 +16,7 @@ namespace Files.App.Filesystem.Cloud { public class CloudDrivesManager { - private readonly ILogger logger = Ioc.Default.GetService(); + private readonly ILogger logger = Ioc.Default.GetRequiredService>(); private readonly ICloudDetector detector = Ioc.Default.GetService(); public EventHandler DataChanged; @@ -42,7 +43,7 @@ public async Task UpdateDrivesAsync() foreach (var provider in providers) { - logger?.Info($"Adding cloud provider \"{provider.Name}\" mapped to {provider.SyncFolder}"); + logger?.LogInformation($"Adding cloud provider \"{provider.Name}\" mapped to {provider.SyncFolder}"); var cloudProviderItem = new DriveItem { Text = provider.Name, @@ -56,7 +57,7 @@ public async Task UpdateDrivesAsync() } catch (Exception ex) { - logger?.Warn(ex, "Cloud provider local folder couldn't be found"); + logger?.LogWarning(ex, "Cloud provider local folder couldn't be found"); } cloudProviderItem.MenuOptions = new ContextMenuOptions diff --git a/src/Files.App/Filesystem/Drives.cs b/src/Files.App/Filesystem/Drives.cs index 1ed16077a5c9..980fe1a587e7 100644 --- a/src/Files.App/Filesystem/Drives.cs +++ b/src/Files.App/Filesystem/Drives.cs @@ -6,6 +6,7 @@ using Files.Backend.Services.SizeProvider; using Files.Shared; using Files.Shared.Enums; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Collections.Specialized; @@ -24,7 +25,7 @@ namespace Files.App.Filesystem { public class DrivesManager : ObservableObject { - private readonly ILogger logger = Ioc.Default.GetService(); + private readonly ILogger logger = Ioc.Default.GetRequiredService>(); private readonly ISizeProvider folderSizeProvider = Ioc.Default.GetService(); private bool isDriveEnumInProgress; @@ -204,7 +205,7 @@ private async void OnDeviceAdded(object? sender, Helpers.MMI.DeviceEventArgs e) var rootAdded = await FilesystemTasks.Wrap(() => StorageFolder.GetFolderFromPathAsync(e.DeviceId).AsTask()); if (!rootAdded) { - logger.Warn($"{rootAdded.ErrorCode}: Attempting to add the device, {e.DeviceId}," + logger.LogWarning($"{rootAdded.ErrorCode}: Attempting to add the device, {e.DeviceId}," + " failed at the StorageFolder initialization step. This device will be ignored."); return; } @@ -230,7 +231,7 @@ private async void OnDeviceAdded(object? sender, Helpers.MMI.DeviceEventArgs e) matchingDrive.DeviceID = e.DeviceId; return; } - logger.Info($"Drive added from fulltrust process: {driveItem.Path}, {driveItem.Type}"); + logger.LogInformation($"Drive added from fulltrust process: {driveItem.Path}, {driveItem.Type}"); drives.Add(driveItem); } @@ -260,7 +261,7 @@ private async void Watcher_Added(DeviceWatcher _, DeviceInformation info) } catch (Exception ex) when (ex is ArgumentException or UnauthorizedAccessException) { - logger.Warn($"{ex.GetType()}: Attempting to add the device, {info.Name}," + logger.LogWarning($"{ex.GetType()}: Attempting to add the device, {info.Name}," + $" failed at the StorageFolder initialization step. This device will be ignored. Device ID: {deviceId}"); return; } @@ -289,7 +290,7 @@ private async void Watcher_Added(DeviceWatcher _, DeviceInformation info) return; } - logger.Info($"Drive added: {driveItem.Path}, {driveItem.Type}"); + logger.LogInformation($"Drive added: {driveItem.Path}, {driveItem.Type}"); drives.Add(driveItem); } @@ -301,7 +302,7 @@ private async void Watcher_Added(DeviceWatcher _, DeviceInformation info) private void Watcher_Removed(DeviceWatcher sender, DeviceInformationUpdate args) { - logger.Info($"Drive removed: {args.Id}"); + logger.LogInformation($"Drive removed: {args.Id}"); lock (drives) { drives.RemoveAll(x => x.DeviceID == args.Id); @@ -332,13 +333,13 @@ private async Task GetDrivesAsync() if (res.ErrorCode is FileSystemStatusCode.Unauthorized) { unauthorizedAccessDetected = true; - logger.Warn($"{res.ErrorCode}: Attempting to add the device, {drive.Name}," + logger.LogWarning($"{res.ErrorCode}: Attempting to add the device, {drive.Name}," + " failed at the StorageFolder initialization step. This device will be ignored."); continue; } else if (!res) { - logger.Warn($"{res.ErrorCode}: Attempting to add the device, {drive.Name}," + logger.LogWarning($"{res.ErrorCode}: Attempting to add the device, {drive.Name}," + " failed at the StorageFolder initialization step. This device will be ignored."); continue; } @@ -355,7 +356,7 @@ private async Task GetDrivesAsync() continue; } - logger.Info($"Drive added: {driveItem.Path}, {driveItem.Type}"); + logger.LogInformation($"Drive added: {driveItem.Path}, {driveItem.Type}"); drives.Add(driveItem); } diff --git a/src/Files.App/Filesystem/FileTagsManager.cs b/src/Files.App/Filesystem/FileTagsManager.cs index a8f21a38e1c4..a3d5433f4bea 100644 --- a/src/Files.App/Filesystem/FileTagsManager.cs +++ b/src/Files.App/Filesystem/FileTagsManager.cs @@ -1,7 +1,7 @@ using CommunityToolkit.Mvvm.DependencyInjection; using Files.App.DataModels.NavigationControlItems; using Files.Backend.Services.Settings; -using Files.Shared; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Collections.Specialized; @@ -12,7 +12,7 @@ namespace Files.App.Filesystem { public class FileTagsManager { - private readonly ILogger logger = Ioc.Default.GetService(); + private readonly ILogger logger = Ioc.Default.GetRequiredService>(); private readonly IFileTagsSettingsService fileTagsSettingsService = Ioc.Default.GetService(); public EventHandler DataChanged; @@ -70,7 +70,7 @@ public Task UpdateFileTagsAsync() } catch (Exception ex) { - logger.Warn(ex, "Error loading tags section."); + logger.LogWarning(ex, "Error loading tags section."); } return Task.CompletedTask; diff --git a/src/Files.App/Filesystem/FilesystemOperations/Helpers/FilesystemHelpers.cs b/src/Files.App/Filesystem/FilesystemOperations/Helpers/FilesystemHelpers.cs index 2db1ae34ca0c..e254b566b6be 100644 --- a/src/Files.App/Filesystem/FilesystemOperations/Helpers/FilesystemHelpers.cs +++ b/src/Files.App/Filesystem/FilesystemOperations/Helpers/FilesystemHelpers.cs @@ -10,6 +10,7 @@ using Files.Shared.Enums; using Files.Shared.Extensions; using Files.Shared.Services; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Diagnostics; @@ -668,7 +669,7 @@ public static bool IsValidForFilename(string name) if (collisions.ContainsKey(incomingItems.ElementAt(item.index).SourcePath)) { // Something strange happened, log - App.Logger.Warn($"Duplicate key when resolving conflicts: {incomingItems.ElementAt(item.index).SourcePath}, {item.src.Name}\n" + + App.Logger.LogWarning($"Duplicate key when resolving conflicts: {incomingItems.ElementAt(item.index).SourcePath}, {item.src.Name}\n" + $"Source: {string.Join(", ", source.Select(x => string.IsNullOrEmpty(x.Path) ? x.Item.Name : x.Path))}"); } collisions.AddIfNotPresent(incomingItems.ElementAt(item.index).SourcePath, FileNameConflictResolveOptionType.GenerateNewName); @@ -753,7 +754,7 @@ public static async Task> GetDraggedStorageIte } catch (Exception ex) { - App.Logger.Warn(ex, ex.Message); + App.Logger.LogWarning(ex, ex.Message); return itemsList; } } diff --git a/src/Files.App/Filesystem/LibraryManager.cs b/src/Files.App/Filesystem/LibraryManager.cs index d69f2644aced..a20b3fa5cc7e 100644 --- a/src/Files.App/Filesystem/LibraryManager.cs +++ b/src/Files.App/Filesystem/LibraryManager.cs @@ -5,6 +5,7 @@ using Files.Shared; using Files.Shared.Enums; using Files.Shared.Extensions; +using Microsoft.Extensions.Logging; using Microsoft.UI.Xaml.Controls; using System; using System.Collections.Generic; @@ -110,7 +111,7 @@ public static async Task> ListUserLibraries() } catch (Exception e) { - App.Logger.Warn(e); + App.Logger.LogWarning(e, null); } return new(); @@ -170,7 +171,7 @@ public async Task CreateNewLibrary(string name) } catch (Exception e) { - App.Logger.Warn(e); + App.Logger.LogWarning(e, null); } return Task.FromResult(null); @@ -251,7 +252,7 @@ public async Task UpdateLibrary(string libraryPath, string } catch (Exception e) { - App.Logger.Warn(e); + App.Logger.LogWarning(e, null); } return Task.FromResult(null); @@ -402,7 +403,7 @@ private async void OnLibraryChanged(WatcherChangeTypes changeType, string oldPat var library = SafetyExtensions.IgnoreExceptions(() => new ShellLibrary2(Shell32.ShellUtil.GetShellItemForPath(newPath), true)); if (library is null) { - App.Logger.Warn($"Failed to open library after {changeType}: {newPath}"); + App.Logger.LogWarning($"Failed to open library after {changeType}: {newPath}"); return; } diff --git a/src/Files.App/Filesystem/RecentItems.cs b/src/Files.App/Filesystem/RecentItems.cs index 9ff00da38e7a..04ac6a2a1674 100644 --- a/src/Files.App/Filesystem/RecentItems.cs +++ b/src/Files.App/Filesystem/RecentItems.cs @@ -1,6 +1,7 @@ using Files.App.Helpers; using Files.App.Shell; using Files.Shared.Extensions; +using Microsoft.Extensions.Logging; using Microsoft.Win32; using System; using System.Collections.Generic; @@ -141,7 +142,7 @@ public async Task> ListRecentFoldersAsync() } catch (Exception ex) { - App.Logger.Warn(ex, ex.Message); + App.Logger.LogWarning(ex, ex.Message); } return null; @@ -169,7 +170,7 @@ public bool AddToRecentItems(string path) } catch (Exception ex) { - App.Logger.Warn(ex, ex.Message); + App.Logger.LogWarning(ex, ex.Message); return false; } } @@ -188,7 +189,7 @@ public bool ClearRecentItems() } catch (Exception ex) { - App.Logger.Warn(ex, ex.Message); + App.Logger.LogWarning(ex, ex.Message); return false; } } diff --git a/src/Files.App/Filesystem/Search/FolderSearch.cs b/src/Files.App/Filesystem/Search/FolderSearch.cs index 35964af5ef5a..b1e4a22727fd 100644 --- a/src/Files.App/Filesystem/Search/FolderSearch.cs +++ b/src/Files.App/Filesystem/Search/FolderSearch.cs @@ -5,6 +5,7 @@ using Files.App.Helpers; using Files.Backend.Services.Settings; using Files.Shared.Extensions; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Collections.ObjectModel; @@ -95,7 +96,7 @@ public Task SearchAsync(IList results, CancellationToken token) } catch (Exception e) { - App.Logger.Warn(e, "Search failure"); + App.Logger.LogWarning(e, "Search failure"); } return Task.CompletedTask; @@ -130,7 +131,7 @@ public async Task> SearchAsync() } catch (Exception e) { - App.Logger.Warn(e, "Search failure"); + App.Logger.LogWarning(e, "Search failure"); } return results; @@ -162,7 +163,7 @@ private async Task SearchAsync(BaseStorageFolder folder, IList resul } catch (Exception ex) { - App.Logger.Warn(ex, "Error creating ListedItem from StorageItem"); + App.Logger.LogWarning(ex, "Error creating ListedItem from StorageItem"); } if (results.Count == 32 || results.Count % 300 == 0 /*|| sampler.CheckNow()*/) @@ -242,7 +243,7 @@ private async Task SearchTagsAsync(string folder, IList results, Can } catch (Exception ex) { - App.Logger.Warn(ex, "Error creating ListedItem from StorageItem"); + App.Logger.LogWarning(ex, "Error creating ListedItem from StorageItem"); } } diff --git a/src/Files.App/Helpers/FileOperationsHelpers.cs b/src/Files.App/Helpers/FileOperationsHelpers.cs index 534fc24a029a..74605e55a84a 100644 --- a/src/Files.App/Helpers/FileOperationsHelpers.cs +++ b/src/Files.App/Helpers/FileOperationsHelpers.cs @@ -5,6 +5,7 @@ using Files.Shared; using Files.Shared.Enums; using Files.Shared.Extensions; +using Microsoft.Extensions.Logging; using Microsoft.Win32; using System; using System.Collections.Concurrent; @@ -564,7 +565,7 @@ public static void TryCancelOperation(string operationId) } catch (FileNotFoundException ex) // Could not parse shortcut { - App.Logger?.Warn(ex, ex.Message); + App.Logger?.LogWarning(ex, ex.Message); // Return a item containing the invalid target path return new ShellLinkItem { @@ -575,7 +576,7 @@ public static void TryCancelOperation(string operationId) catch (Exception ex) { // Could not parse shortcut - App.Logger.Warn(ex, ex.Message); + App.Logger.LogWarning(ex, ex.Message); return null; } } @@ -605,7 +606,7 @@ public static Task CreateOrUpdateLinkAsync(string linkSavePath, string tar catch (Exception ex) { // Could not create shortcut - App.Logger.Warn(ex, ex.Message); + App.Logger.LogWarning(ex, ex.Message); } return Task.FromResult(false); @@ -623,7 +624,7 @@ public static bool SetLinkIcon(string filePath, string iconFile, int iconIndex) catch (Exception ex) { // Could not create shortcut - App.Logger.Warn(ex, ex.Message); + App.Logger.LogWarning(ex, ex.Message); } return false; diff --git a/src/Files.App/Helpers/JumpListHelper.cs b/src/Files.App/Helpers/JumpListHelper.cs index 1fd1cd9e4bcd..d7e15a612dda 100644 --- a/src/Files.App/Helpers/JumpListHelper.cs +++ b/src/Files.App/Helpers/JumpListHelper.cs @@ -1,6 +1,7 @@ using CommunityToolkit.Mvvm.DependencyInjection; using Files.App.UserControls.Widgets; using Files.Shared.Services; +using Microsoft.Extensions.Logging; using System; using System.Threading.Tasks; @@ -21,7 +22,7 @@ public static async Task InitializeUpdatesAsync() } catch (Exception ex) { - App.Logger.Warn(ex, ex.Message); + App.Logger.LogWarning(ex, ex.Message); } } diff --git a/src/Files.App/Helpers/NativeWinApiHelper.cs b/src/Files.App/Helpers/NativeWinApiHelper.cs index 3812587cd0e5..032de2d0d1d9 100644 --- a/src/Files.App/Helpers/NativeWinApiHelper.cs +++ b/src/Files.App/Helpers/NativeWinApiHelper.cs @@ -1,4 +1,5 @@ using Files.App.Shell; +using Microsoft.Extensions.Logging; using System; using System.Runtime.InteropServices; using System.Text; @@ -224,7 +225,7 @@ public static bool IsRunningOnArm if (isRunningOnArm is null) { isRunningOnArm = IsArmProcessor(); - App.Logger.Info("Running on ARM: {0}", isRunningOnArm); + App.Logger.LogInformation("Running on ARM: {0}", isRunningOnArm); } return isRunningOnArm ?? false; } diff --git a/src/Files.App/Helpers/NavigationHelpers.cs b/src/Files.App/Helpers/NavigationHelpers.cs index 56886b68dac1..48681c59baf1 100644 --- a/src/Files.App/Helpers/NavigationHelpers.cs +++ b/src/Files.App/Helpers/NavigationHelpers.cs @@ -9,6 +9,7 @@ using Files.Backend.Services.Settings; using Files.Shared; using Files.Shared.Enums; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; @@ -109,7 +110,7 @@ public static async void OpenItemsWithExecutable(IShellPage associatedInstance, catch (Exception e) { // This is to try and figure out the root cause of AppCenter error #985932119u - App.Logger.Warn(e, e.Message); + App.Logger.LogWarning(e, e.Message); } } } diff --git a/src/Files.App/Helpers/PathNormalization.cs b/src/Files.App/Helpers/PathNormalization.cs index e9efb6e558ed..67cfaaa92424 100644 --- a/src/Files.App/Helpers/PathNormalization.cs +++ b/src/Files.App/Helpers/PathNormalization.cs @@ -1,3 +1,4 @@ +using Microsoft.Extensions.Logging; using System; using System.IO; @@ -46,7 +47,7 @@ public static string NormalizePath(string path) } catch (UriFormatException ex) { - App.Logger.Warn(ex, path); + App.Logger.LogWarning(ex, path); return path; } } diff --git a/src/Files.App/Helpers/QuickLookHelpers.cs b/src/Files.App/Helpers/QuickLookHelpers.cs index 9003ef7ea65c..d87ac4c471c1 100644 --- a/src/Files.App/Helpers/QuickLookHelpers.cs +++ b/src/Files.App/Helpers/QuickLookHelpers.cs @@ -1,3 +1,4 @@ +using Microsoft.Extensions.Logging; using System; using System.IO; using System.IO.Pipes; @@ -18,7 +19,10 @@ public static async Task ToggleQuickLook(string path, bool switchPreview = false bool isQuickLookAvailable = await DetectQuickLookAvailability(); if (isQuickLookAvailable == false) + { + App.Logger.LogInformation("QuickLook not detected"); return; + } string pipeName = $"QuickLook.App.Pipe.{WindowsIdentity.GetCurrent().User?.Value}"; string message = switchPreview ? pipeMessageSwitch : pipeMessageToggle; @@ -64,12 +68,11 @@ static async Task QuickLookServerAvailable() try { var result = await QuickLookServerAvailable(); - App.Logger.Info($"QuickLook detected: {result != 0}"); return result != 0; } catch (Exception ex) { - App.Logger.Info(ex, ex.Message); + App.Logger.LogInformation(ex, ex.Message); return false; } } diff --git a/src/Files.App/Helpers/UIFilesystemHelpers.cs b/src/Files.App/Helpers/UIFilesystemHelpers.cs index 7bcc970ded82..133e16961d71 100644 --- a/src/Files.App/Helpers/UIFilesystemHelpers.cs +++ b/src/Files.App/Helpers/UIFilesystemHelpers.cs @@ -12,6 +12,7 @@ using Files.Shared; using Files.Shared.Enums; using Files.Shared.Extensions; +using Microsoft.Extensions.Logging; using Microsoft.UI.Xaml.Controls; using System; using System.Collections.Concurrent; @@ -367,7 +368,7 @@ public static async Task CreateFolderWithSelectionAsync(IShellPage associatedIns } catch (Exception ex) { - App.Logger.Warn(ex); + App.Logger.LogWarning(ex, null); } } diff --git a/src/Files.App/Helpers/UniversalLogWriter.cs b/src/Files.App/Helpers/UniversalLogWriter.cs deleted file mode 100644 index 7aeb5d259a2c..000000000000 --- a/src/Files.App/Helpers/UniversalLogWriter.cs +++ /dev/null @@ -1,111 +0,0 @@ -using Files.Shared; -using System; -using System.Collections.Concurrent; -using System.Diagnostics; -using System.Text; -using System.Threading.Tasks; -using Windows.Storage; -using Windows.Storage.Streams; -using static Files.App.Helpers.NativeFileOperationsHelper; - -namespace Files.App.Helpers -{ - /// - /// UWP Implementation of ILogger - /// - public class UniversalLogWriter : ILogWriter - { - private StorageFile? logFile; - private bool initialized = false; - private readonly ConcurrentQueue logsBeforeInit = new(); - - public async Task InitializeAsync(string name) - { - if (!initialized) - { - initialized = true; - logFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(name, CreationCollisionOption.OpenIfExists); - - if (logsBeforeInit.Count > 0) - { - using var stream = await OpenFileWithRetryAsync(logFile, FileAccessMode.ReadWrite, StorageOpenOptions.AllowOnlyReaders); - if (stream is null) - return; - using var outputStream = stream.GetOutputStreamAt(stream.Size); - using var dataWriter = new DataWriter(outputStream); - while (logsBeforeInit.TryDequeue(out var text)) - { - dataWriter.WriteString("\n" + text); - } - await dataWriter.StoreAsync(); - await outputStream.FlushAsync(); - } - } - } - - public async Task WriteLineToLogAsync(string text) - { - if (logFile is null) - { - logsBeforeInit.Enqueue(text); - return; - } - using var stream = await OpenFileWithRetryAsync(logFile, FileAccessMode.ReadWrite, StorageOpenOptions.AllowOnlyReaders); - if (stream is null) - return; - using var outputStream = stream.GetOutputStreamAt(stream.Size); - using var dataWriter = new DataWriter(outputStream); - dataWriter.WriteString("\n" + text); - await dataWriter.StoreAsync(); - await outputStream.FlushAsync(); - - Debug.WriteLine($"Logged event: {text}"); - } - - public void WriteLineToLog(string text) - { - if (logFile is null) - { - logsBeforeInit.Enqueue(text); - return; - } - IntPtr hStream = CreateFileFromApp(logFile.Path, - GENERIC_WRITE, FILE_SHARE_READ, IntPtr.Zero, OPEN_EXISTING, (uint)File_Attributes.BackupSemantics, IntPtr.Zero); - if (hStream.ToInt64() == -1) - return; - byte[] buff = Encoding.UTF8.GetBytes("\n" + text); - int dwBytesWritten; - unsafe - { - fixed (byte* pBuff = buff) - { - SetFilePointer(hStream, 0, IntPtr.Zero, FILE_END); - WriteFile(hStream, pBuff, buff.Length, &dwBytesWritten, IntPtr.Zero); - } - } - CloseHandle(hStream); - - Debug.WriteLine($"Logged event: {text}"); - } - - private async Task OpenFileWithRetryAsync(IStorageFile2 file, FileAccessMode mode, StorageOpenOptions share, int maxRetries = 5) - { - for (int numTries = 0; numTries < maxRetries; numTries++) - { - IRandomAccessStream? fs = null; - try - { - fs = await file.OpenAsync(mode, share); - return fs; - } - catch (System.IO.IOException) - { - fs?.Dispose(); - await Task.Delay(50); - } - } - - return null; - } - } -} \ No newline at end of file diff --git a/src/Files.App/Helpers/ZipHelpers.cs b/src/Files.App/Helpers/ZipHelpers.cs index cf5ece765c12..165c8d0ab5b6 100644 --- a/src/Files.App/Helpers/ZipHelpers.cs +++ b/src/Files.App/Helpers/ZipHelpers.cs @@ -1,5 +1,6 @@ using Files.App.Filesystem; using Files.App.Filesystem.StorageItems; +using Microsoft.Extensions.Logging; using SevenZip; using System; using System.Collections.Generic; @@ -57,7 +58,7 @@ public static async Task ExtractArchive(BaseStorageFile archive, BaseStorageFold } catch (Exception ex) { - App.Logger.Warn(ex, $"Error transforming zip names into: {destinationFolder.Path}\n" + + App.Logger.LogWarning(ex, $"Error transforming zip names into: {destinationFolder.Path}\n" + $"Directories: {string.Join(", ", directoryEntries.Select(x => x.FileName))}\n" + $"Files: {string.Join(", ", fileEntries.Select(x => x.FileName))}"); return; @@ -111,7 +112,7 @@ public static async Task ExtractArchive(BaseStorageFile archive, BaseStorageFold } catch (Exception ex) { - App.Logger.Warn(ex, $"Error extracting file: {filePath}"); + App.Logger.LogWarning(ex, $"Error extracting file: {filePath}"); return; // TODO: handle error } } diff --git a/src/Files.App/ServicesImplementation/DialogService.cs b/src/Files.App/ServicesImplementation/DialogService.cs index 40cfce2fbd7b..f4d982c10d8a 100644 --- a/src/Files.App/ServicesImplementation/DialogService.cs +++ b/src/Files.App/ServicesImplementation/DialogService.cs @@ -5,6 +5,7 @@ using Files.Backend.ViewModels.Dialogs.AddItemDialog; using Files.Backend.ViewModels.Dialogs.FileSystemDialog; using Files.Shared.Enums; +using Microsoft.Extensions.Logging; using Microsoft.UI.Xaml.Controls; using System; using System.Collections.Generic; @@ -64,7 +65,7 @@ public Task ShowDialogAsync(TViewModel viewModel) } catch (Exception ex) { - App.Logger.Warn(ex, "Failed to show dialog"); + App.Logger.LogWarning(ex, "Failed to show dialog"); Debugger.Break(); } diff --git a/src/Files.App/ServicesImplementation/Settings/FileTagsSettingsService.cs b/src/Files.App/ServicesImplementation/Settings/FileTagsSettingsService.cs index b4f2b0ced393..758fb0769ec9 100644 --- a/src/Files.App/ServicesImplementation/Settings/FileTagsSettingsService.cs +++ b/src/Files.App/ServicesImplementation/Settings/FileTagsSettingsService.cs @@ -5,6 +5,7 @@ using Files.App.Serialization.Implementation; using Files.Backend.Services.Settings; using Files.Backend.ViewModels.FileTags; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.IO; @@ -59,7 +60,7 @@ public TagViewModel GetTagById(string uid) { if (FileTagList.Any(x => x.Uid is null)) { - App.Logger.Warn("Tags file is invalid, regenerate"); + App.Logger.LogWarning("Tags file is invalid, regenerate"); FileTagList = DefaultFileTags; } diff --git a/src/Files.App/ServicesImplementation/SideloadUpdateService.cs b/src/Files.App/ServicesImplementation/SideloadUpdateService.cs index 2305205b62fd..9ebd0e48b5f0 100644 --- a/src/Files.App/ServicesImplementation/SideloadUpdateService.cs +++ b/src/Files.App/ServicesImplementation/SideloadUpdateService.cs @@ -3,6 +3,7 @@ using CommunityToolkit.WinUI.Helpers; using Files.Backend.Services; using Files.Shared; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Diagnostics; @@ -36,7 +37,7 @@ public sealed class SideloadUpdateService : ObservableObject, IUpdateService, ID private const string TEMPORARY_UPDATE_PACKAGE_NAME = "UpdatePackage.msix"; - private ILogger? Logger { get; } = Ioc.Default.GetService(); + private ILogger? Logger { get; } = Ioc.Default.GetRequiredService>(); private string PackageName { get; } = Package.Current.Id.Name; @@ -115,7 +116,7 @@ public async Task CheckForUpdates() { try { - Logger?.Info($"SIDELOAD: Checking for updates..."); + Logger?.LogInformation($"SIDELOAD: Checking for updates..."); await using var stream = await _client.GetStreamAsync(_sideloadVersion[PackageName]); @@ -128,28 +129,28 @@ public async Task CheckForUpdates() var remoteVersion = new Version(appInstaller.Version); - Logger?.Info($"SIDELOAD: Current Package Name: {PackageName}"); - Logger?.Info($"SIDELOAD: Remote Package Name: {appInstaller.MainBundle.Name}"); - Logger?.Info($"SIDELOAD: Current Version: {PackageVersion}"); - Logger?.Info($"SIDELOAD: Remote Version: {remoteVersion}"); + Logger?.LogInformation($"SIDELOAD: Current Package Name: {PackageName}"); + Logger?.LogInformation($"SIDELOAD: Remote Package Name: {appInstaller.MainBundle.Name}"); + Logger?.LogInformation($"SIDELOAD: Current Version: {PackageVersion}"); + Logger?.LogInformation($"SIDELOAD: Remote Version: {remoteVersion}"); // Check details and version number if (appInstaller.MainBundle.Name.Equals(PackageName) && remoteVersion.CompareTo(PackageVersion) > 0) { - Logger?.Info("SIDELOAD: Update found."); - Logger?.Info("SIDELOAD: Starting background download."); + Logger?.LogInformation("SIDELOAD: Update found."); + Logger?.LogInformation("SIDELOAD: Starting background download."); DownloadUri = new Uri(appInstaller.MainBundle.Uri); await StartBackgroundDownload(); } else { - Logger?.Warn("SIDELOAD: Update not found."); + Logger?.LogWarning("SIDELOAD: Update not found."); IsUpdateAvailable = false; } } catch (Exception e) { - Logger?.Error(e, e.Message); + Logger?.LogError(e, e.Message); } } @@ -180,7 +181,7 @@ public async Task CheckAndUpdateFilesLauncherAsync() await srcExeFile.CopyAsync(destFolder, "FilesLauncher.exe", NameCollisionOption.ReplaceExisting); await srcHashFile.CopyAsync(destFolder, "FilesLauncher.exe.sha256", NameCollisionOption.ReplaceExisting); - App.Logger.Info("FilesLauncher updated."); + App.Logger.LogInformation("FilesLauncher updated."); } } @@ -211,13 +212,13 @@ private async Task StartBackgroundDownload() timer.Stop(); var timespan = timer.Elapsed; - Logger?.Info($"Download time taken: {timespan.Hours:00}:{timespan.Minutes:00}:{timespan.Seconds:00}"); + Logger?.LogInformation($"Download time taken: {timespan.Hours:00}:{timespan.Minutes:00}:{timespan.Seconds:00}"); IsUpdateAvailable = true; } catch (Exception e) { - Logger?.Error(e, e.Message); + Logger?.LogError(e, e.Message); } } @@ -235,7 +236,7 @@ private async Task ApplyPackageUpdate() { var restartStatus = RegisterApplicationRestart(null, 0); - Logger?.Info($"Register for restart: {restartStatus}"); + Logger?.LogInformation($"Register for restart: {restartStatus}"); await Task.Run(async () => { @@ -255,9 +256,9 @@ await Task.Run(async () => catch (Exception e) { if (result?.ExtendedErrorCode is not null) - Logger?.Info(result.ErrorText); + Logger?.LogInformation(result.ErrorText); - Logger?.Error(e, e.Message); + Logger?.LogError(e, e.Message); } finally { diff --git a/src/Files.App/ServicesImplementation/UpdateService.cs b/src/Files.App/ServicesImplementation/UpdateService.cs index 228a470a28d1..d6d590cf87ed 100644 --- a/src/Files.App/ServicesImplementation/UpdateService.cs +++ b/src/Files.App/ServicesImplementation/UpdateService.cs @@ -2,6 +2,7 @@ using CommunityToolkit.WinUI.Helpers; using Files.App.Extensions; using Files.Backend.Services; +using Microsoft.Extensions.Logging; using Microsoft.UI.Xaml.Controls; using System; using System.Collections.Generic; @@ -88,7 +89,7 @@ public async Task DownloadMandatoryUpdates() { if (await ShowDialogAsync()) { - App.Logger.Info("STORE: Downloading updates..."); + App.Logger.LogInformation("STORE: Downloading updates..."); OnUpdateInProgress(); await DownloadAndInstall(); OnUpdateCompleted(); @@ -98,13 +99,13 @@ public async Task DownloadMandatoryUpdates() public async Task CheckForUpdates() { - App.Logger.Info("STORE: Checking for updates..."); + App.Logger.LogInformation("STORE: Checking for updates..."); await GetUpdatePackages(); if (_updatePackages is not null && _updatePackages.Count > 0) { - App.Logger.Info("STORE: Update found."); + App.Logger.LogInformation("STORE: Update found."); IsUpdateAvailable = true; } } @@ -206,7 +207,7 @@ public async Task CheckAndUpdateFilesLauncherAsync() await srcExeFile.CopyAsync(destFolder, "FilesLauncher.exe", NameCollisionOption.ReplaceExisting); await srcHashFile.CopyAsync(destFolder, "FilesLauncher.exe.sha256", NameCollisionOption.ReplaceExisting); - App.Logger.Info("FilesLauncher updated."); + App.Logger.LogInformation("FilesLauncher updated."); } } diff --git a/src/Files.App/Shell/LaunchHelper.cs b/src/Files.App/Shell/LaunchHelper.cs index 5b3dca737a40..b4a4aebd7ebb 100644 --- a/src/Files.App/Shell/LaunchHelper.cs +++ b/src/Files.App/Shell/LaunchHelper.cs @@ -1,4 +1,5 @@ using Files.Backend.Helpers; +using Microsoft.Extensions.Logging; using System; using System.Collections; using System.ComponentModel; @@ -213,7 +214,7 @@ private static async Task HandleApplicationLaunch(string application, stri catch (Exception ex) { // Generic error, log - App.Logger.Warn(ex, $"Error launching: {application}"); + App.Logger.LogWarning(ex, $"Error launching: {application}"); return false; } } diff --git a/src/Files.App/Shell/Win32API.cs b/src/Files.App/Shell/Win32API.cs index 29f35e3eaf6d..999811f5f4b2 100644 --- a/src/Files.App/Shell/Win32API.cs +++ b/src/Files.App/Shell/Win32API.cs @@ -1,6 +1,7 @@ using Files.App.Helpers; using Files.Shared; using Files.Shared.Extensions; +using Microsoft.Extensions.Logging; using System; using System.Collections.Concurrent; using System.Collections.Generic; @@ -39,7 +40,7 @@ public static Task StartSTATask(Func func) catch (Exception ex) { taskCompletionSource.SetResult(); - App.Logger.Warn(ex, ex.Message); + App.Logger.LogWarning(ex, ex.Message); } finally { @@ -73,7 +74,7 @@ public static Task StartSTATask(Action action) catch (Exception ex) { taskCompletionSource.SetResult(); - App.Logger.Warn(ex, ex.Message); + App.Logger.LogWarning(ex, ex.Message); } finally { @@ -107,7 +108,7 @@ public static Task StartSTATask(Action action) catch (Exception ex) { taskCompletionSource.SetResult(default); - App.Logger.Warn(ex, ex.Message); + App.Logger.LogWarning(ex, ex.Message); //tcs.SetException(e); } finally @@ -141,7 +142,7 @@ public static Task StartSTATask(Action action) catch (Exception ex) { taskCompletionSource.SetResult(default); - App.Logger.Info(ex, ex.Message); + App.Logger.LogInformation(ex, ex.Message); //tcs.SetException(e); } finally diff --git a/src/Files.App/UserControls/Widgets/FileTagsWidget.xaml.cs b/src/Files.App/UserControls/Widgets/FileTagsWidget.xaml.cs index fb06adccd561..a1fc7ccfb91a 100644 --- a/src/Files.App/UserControls/Widgets/FileTagsWidget.xaml.cs +++ b/src/Files.App/UserControls/Widgets/FileTagsWidget.xaml.cs @@ -8,6 +8,7 @@ using Files.App.ViewModels.Widgets; using Files.Backend.Services.Settings; using Files.Shared.Extensions; +using Microsoft.Extensions.Logging; using Microsoft.UI.Xaml; using Microsoft.UI.Xaml.Controls; using Microsoft.UI.Xaml.Controls.Primitives; @@ -107,13 +108,13 @@ private async void FileTagItem_ItemClick(object sender, ItemClickEventArgs e) private async void Item_RightTapped(object sender, RightTappedRoutedEventArgs e) { - App.Logger.Warn("rightTapped"); + App.Logger.LogWarning("rightTapped"); var itemContextMenuFlyout = new CommandBarFlyout { Placement = FlyoutPlacementMode.Full }; itemContextMenuFlyout.Opening += (sender, e) => App.LastOpenedFlyout = sender as CommandBarFlyout; if (sender is not StackPanel tagsItemsStackPanel || tagsItemsStackPanel.DataContext is not FileTagsItemViewModel item) return; - App.Logger.Warn("Item path: " + item.Path + " widgetcarditem.path = " + (item as WidgetCardItem)?.Path); + App.Logger.LogWarning("Item path: " + item.Path + " widgetcarditem.path = " + (item as WidgetCardItem)?.Path); var menuItems = GetItemMenuItems(item, QuickAccessService.IsItemPinned(item.Path), item.IsFolder); var (_, secondaryElements) = ItemModelListToContextFlyoutHelper.GetAppBarItemsFromModel(menuItems); diff --git a/src/Files.App/UserControls/Widgets/RecentFilesWidget.xaml.cs b/src/Files.App/UserControls/Widgets/RecentFilesWidget.xaml.cs index b38d208b992b..a4a34f0444a9 100644 --- a/src/Files.App/UserControls/Widgets/RecentFilesWidget.xaml.cs +++ b/src/Files.App/UserControls/Widgets/RecentFilesWidget.xaml.cs @@ -7,6 +7,7 @@ using Files.App.ViewModels; using Files.App.ViewModels.Widgets; using Files.Shared.Extensions; +using Microsoft.Extensions.Logging; using Microsoft.UI.Xaml; using Microsoft.UI.Xaml.Controls; using Microsoft.UI.Xaml.Controls.Primitives; @@ -270,7 +271,7 @@ private async Task UpdateRecentsList(NotifyCollectionChangedEventArgs e) } catch (Exception ex) { - App.Logger.Info(ex, "Could not populate recent files"); + App.Logger.LogInformation(ex, "Could not populate recent files"); } finally { @@ -288,7 +289,7 @@ private bool AddItemToRecentList(RecentItem recentItem, int index = -1) { recentItemsCollection.Insert(index < 0 ? recentItemsCollection.Count : Math.Min(index, recentItemsCollection.Count), recentItem); _ = recentItem.LoadRecentItemIcon() - .ContinueWith(t => App.Logger.Warn(t.Exception), TaskContinuationOptions.OnlyOnFaulted); + .ContinueWith(t => App.Logger.LogWarning(t.Exception, null), TaskContinuationOptions.OnlyOnFaulted); return true; } return false; diff --git a/src/Files.App/ViewModels/Dialogs/ReorderSidebarItemsDialogViewModel.cs b/src/Files.App/ViewModels/Dialogs/ReorderSidebarItemsDialogViewModel.cs index 68bc5aeef1c6..cf4c94cc61a8 100644 --- a/src/Files.App/ViewModels/Dialogs/ReorderSidebarItemsDialogViewModel.cs +++ b/src/Files.App/ViewModels/Dialogs/ReorderSidebarItemsDialogViewModel.cs @@ -23,7 +23,7 @@ public class ReorderSidebarItemsDialogViewModel : ObservableObject public ReorderSidebarItemsDialogViewModel() { - //App.Logger.Warn(string.Join(", ", SidebarFavoriteItems.Select(x => x.Path))); + //App.Logger.LogWarning(string.Join(", ", SidebarFavoriteItems.Select(x => x.Path))); PrimaryButtonCommand = new RelayCommand(SaveChanges); } diff --git a/src/Files.App/ViewModels/ItemViewModel.cs b/src/Files.App/ViewModels/ItemViewModel.cs index cd7ec0c4c8a2..ed0d015217b2 100644 --- a/src/Files.App/ViewModels/ItemViewModel.cs +++ b/src/Files.App/ViewModels/ItemViewModel.cs @@ -23,6 +23,7 @@ using Files.Shared.Extensions; using Files.Shared.Services; using FluentFTP; +using Microsoft.Extensions.Logging; using Microsoft.UI.Xaml.Data; using Microsoft.UI.Xaml.Media; using Microsoft.UI.Xaml.Media.Imaging; @@ -682,7 +683,7 @@ void UpdateUI() } catch (Exception ex) { - App.Logger.Warn(ex, ex.Message); + App.Logger.LogWarning(ex, ex.Message); } } @@ -801,7 +802,7 @@ await dispatcherQueue.EnqueueAsync( } catch (Exception ex) { - App.Logger.Warn(ex, ex.Message); + App.Logger.LogWarning(ex, ex.Message); } finally { @@ -2008,7 +2009,7 @@ async Task HandleChangesOccurredAsync() } catch (Exception ex) { - App.Logger.Warn(ex, ex.Message); + App.Logger.LogWarning(ex, ex.Message); } if (anyEdits && sampler.CheckNow()) diff --git a/src/Files.App/ViewModels/Properties/CombinedProperties.cs b/src/Files.App/ViewModels/Properties/CombinedProperties.cs index e6b923790ee7..e5f40a92967b 100644 --- a/src/Files.App/ViewModels/Properties/CombinedProperties.cs +++ b/src/Files.App/ViewModels/Properties/CombinedProperties.cs @@ -1,6 +1,7 @@ using Files.App.Extensions; using Files.App.Filesystem; using Files.App.Helpers; +using Microsoft.Extensions.Logging; using Microsoft.UI.Dispatching; using System; using System.Collections.Generic; @@ -91,7 +92,7 @@ public override async void GetSpecialProperties() } catch (Exception ex) { - App.Logger.Warn(ex, ex.Message); + App.Logger.LogWarning(ex, ex.Message); } } } diff --git a/src/Files.App/ViewModels/Properties/DriveProperties.cs b/src/Files.App/ViewModels/Properties/DriveProperties.cs index 596488305f31..14f28b065e37 100644 --- a/src/Files.App/ViewModels/Properties/DriveProperties.cs +++ b/src/Files.App/ViewModels/Properties/DriveProperties.cs @@ -3,6 +3,7 @@ using Files.App.Filesystem; using Files.App.Filesystem.StorageItems; using Files.App.Helpers; +using Microsoft.Extensions.Logging; using System; using Windows.Storage.FileProperties; @@ -84,7 +85,7 @@ public async override void GetSpecialProperties() catch (Exception e) { ViewModel.LastSeparatorVisibility = false; - App.Logger.Warn(e, e.Message); + App.Logger.LogWarning(e, e.Message); } } } diff --git a/src/Files.App/ViewModels/Properties/FolderProperties.cs b/src/Files.App/ViewModels/Properties/FolderProperties.cs index 66052c24cec7..4f495ad06b26 100644 --- a/src/Files.App/ViewModels/Properties/FolderProperties.cs +++ b/src/Files.App/ViewModels/Properties/FolderProperties.cs @@ -6,6 +6,7 @@ using Files.App.Filesystem.StorageItems; using Files.App.Helpers; using Files.App.Shell; +using Microsoft.Extensions.Logging; using Microsoft.UI.Dispatching; using System; using System.IO; @@ -174,7 +175,7 @@ private async void GetFolderSize(string folderPath, CancellationToken token) } catch (Exception ex) { - App.Logger.Warn(ex, ex.Message); + App.Logger.LogWarning(ex, ex.Message); } ViewModel.ItemSizeProgressVisibility = false; diff --git a/src/Files.App/ViewModels/Properties/LibraryProperties.cs b/src/Files.App/ViewModels/Properties/LibraryProperties.cs index 262c3761d6d3..efd387f5dd0f 100644 --- a/src/Files.App/ViewModels/Properties/LibraryProperties.cs +++ b/src/Files.App/ViewModels/Properties/LibraryProperties.cs @@ -4,6 +4,7 @@ using Files.App.Filesystem.StorageItems; using Files.App.Helpers; using Files.Shared.Services.DateTimeFormatter; +using Microsoft.Extensions.Logging; using Microsoft.UI.Dispatching; using System; using System.Collections.Generic; @@ -91,7 +92,7 @@ public async override void GetSpecialProperties() } catch (Exception ex) { - App.Logger.Warn(ex, ex.Message); + App.Logger.LogWarning(ex, ex.Message); } } @@ -124,7 +125,7 @@ private async void GetLibrarySize(List storageFolders, Cancel } catch (Exception ex) { - App.Logger.Warn(ex, ex.Message); + App.Logger.LogWarning(ex, ex.Message); } ViewModel.ItemSizeProgressVisibility = false; diff --git a/src/Files.App/ViewModels/Settings/AdvancedViewModel.cs b/src/Files.App/ViewModels/Settings/AdvancedViewModel.cs index 0ac0ce5457f0..63ba905a1da9 100644 --- a/src/Files.App/ViewModels/Settings/AdvancedViewModel.cs +++ b/src/Files.App/ViewModels/Settings/AdvancedViewModel.cs @@ -8,6 +8,7 @@ using Files.App.Shell; using Files.Backend.Services.Settings; using Files.Shared.Extensions; +using Microsoft.Extensions.Logging; using Microsoft.Win32; using SevenZip; using System; @@ -197,7 +198,7 @@ private async Task ImportSettings() } catch (Exception ex) { - App.Logger.Warn(ex, "Error importing settings"); + App.Logger.LogWarning(ex, "Error importing settings"); UIHelpers.CloseAllDialogs(); await DialogDisplayHelper.ShowDialogAsync("SettingsImportErrorTitle".GetLocalizedResource(), "SettingsImportErrorDescription".GetLocalizedResource()); } @@ -245,7 +246,7 @@ private async Task ExportSettings() } catch (Exception ex) { - App.Logger.Warn(ex, "Error exporting settings"); + App.Logger.LogWarning(ex, "Error exporting settings"); } } } diff --git a/src/Files.App/ViewModels/Settings/PreferencesViewModel.cs b/src/Files.App/ViewModels/Settings/PreferencesViewModel.cs index 43756a196b94..edfb2725e28a 100644 --- a/src/Files.App/ViewModels/Settings/PreferencesViewModel.cs +++ b/src/Files.App/ViewModels/Settings/PreferencesViewModel.cs @@ -6,6 +6,7 @@ using Files.Backend.Services.Settings; using Files.Shared.Enums; using Files.Shared.Services.DateTimeFormatter; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Collections.ObjectModel; @@ -193,7 +194,7 @@ private Task PopulateRecentItems(MenuFlyoutSubItemViewModel menu) } catch (Exception ex) { - App.Logger.Info(ex, "Could not fetch recent items"); + App.Logger.LogInformation(ex, "Could not fetch recent items"); } // Update items source diff --git a/src/Files.Shared/Extensions/FileLoggerExtensions.cs b/src/Files.Shared/Extensions/FileLoggerExtensions.cs new file mode 100644 index 000000000000..803d4448db2b --- /dev/null +++ b/src/Files.Shared/Extensions/FileLoggerExtensions.cs @@ -0,0 +1,13 @@ +using Microsoft.Extensions.Logging; + +namespace Files.Shared.Extensions +{ + public static class FileLoggerExtensions + { + public static ILoggerFactory AddFile(this ILoggerFactory factory, string filePath) + { + factory.AddProvider(new FileLoggerProvider(filePath)); + return factory; + } + } +} diff --git a/src/Files.Shared/Extensions/SafetyExtensions.cs b/src/Files.Shared/Extensions/SafetyExtensions.cs index 608d00c8a4b5..80fffb6a60da 100644 --- a/src/Files.Shared/Extensions/SafetyExtensions.cs +++ b/src/Files.Shared/Extensions/SafetyExtensions.cs @@ -1,4 +1,5 @@ -using System; +using Microsoft.Extensions.Logging; +using System; using System.Threading.Tasks; namespace Files.Shared.Extensions @@ -15,7 +16,7 @@ public static bool IgnoreExceptions(Action action, ILogger? logger = null) } catch (Exception ex) { - logger?.Info(ex, ex.Message); + logger?.LogInformation(ex, ex.Message); return false; } } @@ -29,7 +30,7 @@ public static async Task IgnoreExceptions(Func action, ILogger? logg } catch (Exception ex) { - logger?.Info(ex, ex.Message); + logger?.LogInformation(ex, ex.Message); return false; } } @@ -42,7 +43,7 @@ public static async Task IgnoreExceptions(Func action, ILogger? logg } catch (Exception ex) { - logger?.Info(ex, ex.Message); + logger?.LogInformation(ex, ex.Message); return default; } } @@ -55,7 +56,7 @@ public static async Task IgnoreExceptions(Func action, ILogger? logg } catch (Exception ex) { - logger?.Info(ex, ex.Message); + logger?.LogInformation(ex, ex.Message); return default; } } diff --git a/src/Files.Shared/FileLogger.cs b/src/Files.Shared/FileLogger.cs new file mode 100644 index 000000000000..055732f558f6 --- /dev/null +++ b/src/Files.Shared/FileLogger.cs @@ -0,0 +1,46 @@ +using Microsoft.Extensions.Logging; +using System; +using System.Diagnostics; +using System.IO; +using System.Threading; + +namespace Files.Shared +{ + public class FileLogger : ILogger + { + private readonly SemaphoreSlim semaphoreSlim = new(1); + private readonly string filePath; + + public FileLogger(string filePath) + { + this.filePath = filePath; + } + + public IDisposable? BeginScope(TState state) where TState : notnull + { + return null; + } + + public bool IsEnabled(LogLevel logLevel) => true; + + public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) + { + if (formatter is not null) + { + semaphoreSlim.Wait(); + try + { + File.AppendAllText(filePath, $"{DateTime.Now:yyyy-MM-dd HH:mm:ss.ffff}|{logLevel}|{formatter(state, exception)}" + Environment.NewLine); + } + catch (Exception e) + { + Debug.WriteLine($"Writing to log file failed with the following exception:\n{e}"); + } + finally + { + semaphoreSlim.Release(); + } + } + } + } +} diff --git a/src/Files.Shared/FileLoggerProvider.cs b/src/Files.Shared/FileLoggerProvider.cs new file mode 100644 index 000000000000..9332294a8069 --- /dev/null +++ b/src/Files.Shared/FileLoggerProvider.cs @@ -0,0 +1,28 @@ +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Files.Shared +{ + public class FileLoggerProvider : ILoggerProvider + { + private readonly string path; + + public FileLoggerProvider(string path) + { + this.path = path; + } + + public ILogger CreateLogger(string categoryName) + { + return new FileLogger(path); + } + + public void Dispose() + { + } + } +} diff --git a/src/Files.Shared/Files.Shared.csproj b/src/Files.Shared/Files.Shared.csproj index ac5ea7438620..55fd7b7333d4 100644 --- a/src/Files.Shared/Files.Shared.csproj +++ b/src/Files.Shared/Files.Shared.csproj @@ -12,6 +12,7 @@ + diff --git a/src/Files.Shared/ILogWriter.cs b/src/Files.Shared/ILogWriter.cs deleted file mode 100644 index bf78396f5f55..000000000000 --- a/src/Files.Shared/ILogWriter.cs +++ /dev/null @@ -1,11 +0,0 @@ -using System.Threading.Tasks; - -namespace Files.Shared -{ - public interface ILogWriter - { - Task InitializeAsync(string name); - Task WriteLineToLogAsync(string text); - void WriteLineToLog(string text); - } -} diff --git a/src/Files.Shared/ILogger.cs b/src/Files.Shared/ILogger.cs deleted file mode 100644 index 73fc8f002267..000000000000 --- a/src/Files.Shared/ILogger.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System; -using System.Runtime.CompilerServices; - -namespace Files.Shared -{ - public interface ILogger - { - void Info(string error, [CallerMemberName] string caller = ""); - void Info(string info, object obj, [CallerMemberName] string caller = ""); - void Info(Exception ex, string error = "", [CallerMemberName] string caller = ""); - - void Warn(string error, [CallerMemberName] string caller = ""); - void Warn(Exception ex, string error = "", [CallerMemberName] string caller = ""); - - void Error(string error, [CallerMemberName] string caller = ""); - void Error(Exception ex, string error = "", [CallerMemberName] string caller = ""); - void UnhandledError(Exception ex, string error = "", [CallerMemberName] string caller = ""); - } -} diff --git a/src/Files.Shared/Logger.cs b/src/Files.Shared/Logger.cs deleted file mode 100644 index fec70cdb2fb0..000000000000 --- a/src/Files.Shared/Logger.cs +++ /dev/null @@ -1,69 +0,0 @@ -using System; -using System.Diagnostics; -using System.Runtime.CompilerServices; -using System.Threading; - -namespace Files.Shared -{ - public class Logger : ILogger - { - private readonly ILogWriter writer; - - private readonly SemaphoreSlim semaphoreSlim = new(1); - - public Logger(ILogWriter writer) => this.writer = writer; - - public void Info(string info, [CallerMemberName] string caller = "") - => LogAsync(type: "INFO", caller: caller, message: info); - public void Info(string info, object obj, [CallerMemberName] string caller = "") - => LogAsync(type: "INFO", caller: caller, message: string.Format(info, obj)); - public void Info(Exception ex, string info = "", [CallerMemberName] string caller = "") - => LogAsync(type: "INFO", caller: caller, message: $"{info}\n\t{ex}"); - - public void Warn(string warning, [CallerMemberName] string caller = "") - => LogAsync(type: "WARN", caller: caller, message: warning); - public void Warn(Exception ex, string warning = "", [CallerMemberName] string caller = "") - => LogAsync(type: "WARN", caller: caller, message: $"{warning}\n\t{ex}"); - - public void Error(string error, [CallerMemberName] string caller = "") - => LogAsync(type: "ERROR", caller: caller, message: error); - public void Error(Exception ex, string error = "", [CallerMemberName] string caller = "") - => LogAsync(type: "ERROR", caller: caller, message: $"{error}\n\t{ex}"); - public void UnhandledError(Exception ex, string error = "", [CallerMemberName] string caller = "") - => LogSync(type: "ERROR", caller: caller, message: $"{error}\n\t{ex}"); - - private void LogSync(string type, string caller, string message) - { - semaphoreSlim.Wait(); - try - { - writer.WriteLineToLog($"{DateTime.Now:yyyy-MM-dd HH:mm:ss.ffff}|{type}|{caller}|{message}"); - } - catch (Exception e) - { - Debug.WriteLine($"Writing to log file failed with the following exception:\n{e}"); - } - finally - { - semaphoreSlim.Release(); - } - } - - private async void LogAsync(string type, string caller, string message, int attemptNumber = 0) - { - await semaphoreSlim.WaitAsync(); - try - { - await writer.WriteLineToLogAsync($"{DateTime.Now:yyyy-MM-dd HH:mm:ss.ffff}|{type}|{caller}|{message}"); - } - catch (Exception e) - { - Debug.WriteLine($"Writing to log file failed with the following exception:\n{e}"); - } - finally - { - semaphoreSlim.Release(); - } - } - } -}