Skip to content

Commit 20ebfe3

Browse files
authored
Feature: New Logging provider (#11937)
1 parent aec3c54 commit 20ebfe3

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

43 files changed

+228
-315
lines changed

src/Files.App/App.xaml.cs

Lines changed: 15 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -32,12 +32,14 @@
3232
using Microsoft.AppCenter.Crashes;
3333
using Microsoft.Extensions.DependencyInjection;
3434
using Microsoft.Extensions.Hosting;
35+
using Microsoft.Extensions.Logging;
3536
using Microsoft.UI.Windowing;
3637
using Microsoft.UI.Xaml;
3738
using Microsoft.UI.Xaml.Controls;
3839
using Microsoft.Windows.AppLifecycle;
3940
using System;
4041
using System.Diagnostics;
42+
using System.IO;
4143
using System.Linq;
4244
using System.Text;
4345
using System.Threading.Tasks;
@@ -46,8 +48,6 @@
4648
using Windows.Storage;
4749
using Windows.UI.Notifications;
4850

49-
// To learn more about WinUI, the WinUI project structure,
50-
// and more about our project templates, see: http://aka.ms/winui-project-info.
5151

5252
namespace Files.App
5353
{
@@ -72,7 +72,6 @@ public partial class App : Application
7272
public static FileTagsManager FileTagsManager { get; private set; }
7373

7474
public static ILogger Logger { get; private set; }
75-
private static readonly UniversalLogWriter logWriter = new UniversalLogWriter();
7675
public static SecondaryTileHelper SecondaryTileHelper { get; private set; } = new SecondaryTileHelper();
7776

7877
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
8685
/// </summary>
8786
public App()
8887
{
89-
// Initialize logger
90-
Logger = new Logger(logWriter);
91-
9288
UnhandledException += OnUnhandledException;
9389
TaskScheduler.UnobservedTaskException += OnUnobservedException;
9490
InitializeComponent();
@@ -119,7 +115,7 @@ private static Task StartAppCenter()
119115
}
120116
catch (Exception ex)
121117
{
122-
Logger.Warn(ex, "AppCenter could not be started.");
118+
App.Logger.LogWarning(ex, "AppCenter could not be started.");
123119
}
124120

125121
return Task.CompletedTask;
@@ -174,16 +170,19 @@ protected override void OnLaunched(LaunchActivatedEventArgs e)
174170
{
175171
var activatedEventArgs = Microsoft.Windows.AppLifecycle.AppInstance.GetCurrent().GetActivatedEventArgs();
176172

177-
Task.Run(async () => await logWriter.InitializeAsync("debug.log"));
178-
Logger.Info($"App launched. Launch args type: {activatedEventArgs.Data.GetType().Name}");
179-
173+
var logPath = Path.Combine(ApplicationData.Current.LocalFolder.Path, "debug.log");
180174
//start tracking app usage
181175
if (activatedEventArgs.Data is Windows.ApplicationModel.Activation.IActivatedEventArgs iaea)
182176
SystemInformation.Instance.TrackAppUse(iaea);
183177

184178
// Initialize MainWindow here
185179
EnsureWindowIsInitialized();
186180
host = Host.CreateDefaultBuilder()
181+
.ConfigureLogging(builder =>
182+
builder
183+
.AddProvider(new FileLoggerProvider(logPath))
184+
.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Information)
185+
)
187186
.ConfigureServices(services =>
188187
services
189188
.AddSingleton<IUserSettingsService, UserSettingsService>()
@@ -201,7 +200,6 @@ protected override void OnLaunched(LaunchActivatedEventArgs e)
201200
.AddSingleton<IDisplayPageContext, DisplayPageContext>()
202201
.AddSingleton<IWindowContext, WindowContext>()
203202
.AddSingleton<IMultitaskingContext, MultitaskingContext>()
204-
.AddSingleton(Logger)
205203
.AddSingleton<IDialogService, DialogService>()
206204
.AddSingleton<IImageService, ImagingService>()
207205
.AddSingleton<IThreadingService, ThreadingService>()
@@ -235,10 +233,13 @@ protected override void OnLaunched(LaunchActivatedEventArgs e)
235233
.AddSingleton<AppearanceViewModel>()
236234
)
237235
.Build();
236+
Logger = host.Services.GetRequiredService<ILogger<App>>();
237+
App.Logger.LogInformation($"App launched. Launch args type: {activatedEventArgs.Data.GetType().Name}");
238+
238239
Ioc.Default.ConfigureServices(host.Services);
239240
EnsureSettingsAndConfigurationAreBootstrapped();
240241

241-
_ = InitializeAppComponentsAsync().ContinueWith(t => Logger.Warn(t.Exception, "Error during InitializeAppComponentsAsync()"), TaskContinuationOptions.OnlyOnFaulted);
242+
_ = InitializeAppComponentsAsync().ContinueWith(t => Logger.LogWarning(t.Exception, "Error during InitializeAppComponentsAsync()"), TaskContinuationOptions.OnlyOnFaulted);
242243

243244
_ = Window.InitializeApplication(activatedEventArgs.Data);
244245
}
@@ -263,7 +264,7 @@ private void Window_Activated(object sender, WindowActivatedEventArgs args)
263264

264265
public void OnActivated(AppActivationArguments activatedEventArgs)
265266
{
266-
Logger.Info($"App activated. Activated args type: {activatedEventArgs.Data.GetType().Name}");
267+
App.Logger.LogInformation($"App activated. Activated args type: {activatedEventArgs.Data.GetType().Name}");
267268
var data = activatedEventArgs.Data;
268269
// InitializeApplication accesses UI, needs to be called on UI thread
269270
_ = Window.DispatcherQueue.EnqueueAsync(() => Window.InitializeApplication(data));
@@ -391,7 +392,7 @@ private static void AppUnhandledException(Exception ex, bool shouldShowNotificat
391392
Debugger.Break(); // Please check "Output Window" for exception details (View -> Output Window) (CTRL + ALT + O)
392393

393394
SaveSessionTabs();
394-
Logger.UnhandledError(ex, ex.Message);
395+
App.Logger.LogError(ex, ex.Message);
395396

396397
if (!ShowErrorNotification || !shouldShowNotification)
397398
return;

src/Files.App/Files.App.csproj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,7 @@
8080
<PackageReference Include="Microsoft.Data.Sqlite.Core" Version="7.0.4" />
8181
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
8282
<PackageReference Include="Microsoft.Extensions.Hosting" Version="7.0.1" />
83+
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
8384
<PackageReference Include="Microsoft.Windows.SDK.BuildTools" Version="10.0.22621.756" />
8485
<PackageReference Include="SevenZipSharp" Version="1.0.0" />
8586
<PackageReference Include="SQLitePCLRaw.bundle_green" Version="2.1.4" />

src/Files.App/Filesystem/Archive/ArchiveCreator.cs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
using CommunityToolkit.Mvvm.DependencyInjection;
22
using Files.Shared;
3+
using Microsoft.Extensions.Logging;
34
using SevenZip;
45
using System;
56
using System.Collections.Generic;
@@ -144,8 +145,8 @@ public async Task<bool> RunCreationAsync()
144145
}
145146
catch (Exception ex)
146147
{
147-
var logger = Ioc.Default.GetService<ILogger>();
148-
logger?.Warn(ex, $"Error compressing folder: {archivePath}");
148+
var logger = Ioc.Default.GetRequiredService<ILogger<App>>();
149+
logger?.LogWarning(ex, $"Error compressing folder: {archivePath}");
149150

150151
return false;
151152
}

src/Files.App/Filesystem/Cloud/CloudDrivesManager.cs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
using Files.App.Helpers;
55
using Files.Shared;
66
using Files.Shared.Cloud;
7+
using Microsoft.Extensions.Logging;
78
using System;
89
using System.Collections.Generic;
910
using System.Collections.Specialized;
@@ -15,7 +16,7 @@ namespace Files.App.Filesystem.Cloud
1516
{
1617
public class CloudDrivesManager
1718
{
18-
private readonly ILogger logger = Ioc.Default.GetService<ILogger>();
19+
private readonly ILogger logger = Ioc.Default.GetRequiredService<ILogger<App>>();
1920
private readonly ICloudDetector detector = Ioc.Default.GetService<ICloudDetector>();
2021

2122
public EventHandler<NotifyCollectionChangedEventArgs> DataChanged;
@@ -42,7 +43,7 @@ public async Task UpdateDrivesAsync()
4243

4344
foreach (var provider in providers)
4445
{
45-
logger?.Info($"Adding cloud provider \"{provider.Name}\" mapped to {provider.SyncFolder}");
46+
logger?.LogInformation($"Adding cloud provider \"{provider.Name}\" mapped to {provider.SyncFolder}");
4647
var cloudProviderItem = new DriveItem
4748
{
4849
Text = provider.Name,
@@ -56,7 +57,7 @@ public async Task UpdateDrivesAsync()
5657
}
5758
catch (Exception ex)
5859
{
59-
logger?.Warn(ex, "Cloud provider local folder couldn't be found");
60+
logger?.LogWarning(ex, "Cloud provider local folder couldn't be found");
6061
}
6162

6263
cloudProviderItem.MenuOptions = new ContextMenuOptions

src/Files.App/Filesystem/Drives.cs

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
using Files.Backend.Services.SizeProvider;
77
using Files.Shared;
88
using Files.Shared.Enums;
9+
using Microsoft.Extensions.Logging;
910
using System;
1011
using System.Collections.Generic;
1112
using System.Collections.Specialized;
@@ -24,7 +25,7 @@ namespace Files.App.Filesystem
2425
{
2526
public class DrivesManager : ObservableObject
2627
{
27-
private readonly ILogger logger = Ioc.Default.GetService<ILogger>();
28+
private readonly ILogger logger = Ioc.Default.GetRequiredService<ILogger<App>>();
2829
private readonly ISizeProvider folderSizeProvider = Ioc.Default.GetService<ISizeProvider>();
2930

3031
private bool isDriveEnumInProgress;
@@ -204,7 +205,7 @@ private async void OnDeviceAdded(object? sender, Helpers.MMI.DeviceEventArgs e)
204205
var rootAdded = await FilesystemTasks.Wrap(() => StorageFolder.GetFolderFromPathAsync(e.DeviceId).AsTask());
205206
if (!rootAdded)
206207
{
207-
logger.Warn($"{rootAdded.ErrorCode}: Attempting to add the device, {e.DeviceId},"
208+
logger.LogWarning($"{rootAdded.ErrorCode}: Attempting to add the device, {e.DeviceId},"
208209
+ " failed at the StorageFolder initialization step. This device will be ignored.");
209210
return;
210211
}
@@ -230,7 +231,7 @@ private async void OnDeviceAdded(object? sender, Helpers.MMI.DeviceEventArgs e)
230231
matchingDrive.DeviceID = e.DeviceId;
231232
return;
232233
}
233-
logger.Info($"Drive added from fulltrust process: {driveItem.Path}, {driveItem.Type}");
234+
logger.LogInformation($"Drive added from fulltrust process: {driveItem.Path}, {driveItem.Type}");
234235
drives.Add(driveItem);
235236
}
236237

@@ -260,7 +261,7 @@ private async void Watcher_Added(DeviceWatcher _, DeviceInformation info)
260261
}
261262
catch (Exception ex) when (ex is ArgumentException or UnauthorizedAccessException)
262263
{
263-
logger.Warn($"{ex.GetType()}: Attempting to add the device, {info.Name},"
264+
logger.LogWarning($"{ex.GetType()}: Attempting to add the device, {info.Name},"
264265
+ $" failed at the StorageFolder initialization step. This device will be ignored. Device ID: {deviceId}");
265266
return;
266267
}
@@ -289,7 +290,7 @@ private async void Watcher_Added(DeviceWatcher _, DeviceInformation info)
289290
return;
290291
}
291292

292-
logger.Info($"Drive added: {driveItem.Path}, {driveItem.Type}");
293+
logger.LogInformation($"Drive added: {driveItem.Path}, {driveItem.Type}");
293294
drives.Add(driveItem);
294295
}
295296

@@ -301,7 +302,7 @@ private async void Watcher_Added(DeviceWatcher _, DeviceInformation info)
301302

302303
private void Watcher_Removed(DeviceWatcher sender, DeviceInformationUpdate args)
303304
{
304-
logger.Info($"Drive removed: {args.Id}");
305+
logger.LogInformation($"Drive removed: {args.Id}");
305306
lock (drives)
306307
{
307308
drives.RemoveAll(x => x.DeviceID == args.Id);
@@ -332,13 +333,13 @@ private async Task<bool> GetDrivesAsync()
332333
if (res.ErrorCode is FileSystemStatusCode.Unauthorized)
333334
{
334335
unauthorizedAccessDetected = true;
335-
logger.Warn($"{res.ErrorCode}: Attempting to add the device, {drive.Name},"
336+
logger.LogWarning($"{res.ErrorCode}: Attempting to add the device, {drive.Name},"
336337
+ " failed at the StorageFolder initialization step. This device will be ignored.");
337338
continue;
338339
}
339340
else if (!res)
340341
{
341-
logger.Warn($"{res.ErrorCode}: Attempting to add the device, {drive.Name},"
342+
logger.LogWarning($"{res.ErrorCode}: Attempting to add the device, {drive.Name},"
342343
+ " failed at the StorageFolder initialization step. This device will be ignored.");
343344
continue;
344345
}
@@ -355,7 +356,7 @@ private async Task<bool> GetDrivesAsync()
355356
continue;
356357
}
357358

358-
logger.Info($"Drive added: {driveItem.Path}, {driveItem.Type}");
359+
logger.LogInformation($"Drive added: {driveItem.Path}, {driveItem.Type}");
359360
drives.Add(driveItem);
360361
}
361362

src/Files.App/Filesystem/FileTagsManager.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
using CommunityToolkit.Mvvm.DependencyInjection;
22
using Files.App.DataModels.NavigationControlItems;
33
using Files.Backend.Services.Settings;
4-
using Files.Shared;
4+
using Microsoft.Extensions.Logging;
55
using System;
66
using System.Collections.Generic;
77
using System.Collections.Specialized;
@@ -12,7 +12,7 @@ namespace Files.App.Filesystem
1212
{
1313
public class FileTagsManager
1414
{
15-
private readonly ILogger logger = Ioc.Default.GetService<ILogger>();
15+
private readonly ILogger logger = Ioc.Default.GetRequiredService<ILogger<App>>();
1616
private readonly IFileTagsSettingsService fileTagsSettingsService = Ioc.Default.GetService<IFileTagsSettingsService>();
1717

1818
public EventHandler<NotifyCollectionChangedEventArgs> DataChanged;
@@ -70,7 +70,7 @@ public Task UpdateFileTagsAsync()
7070
}
7171
catch (Exception ex)
7272
{
73-
logger.Warn(ex, "Error loading tags section.");
73+
logger.LogWarning(ex, "Error loading tags section.");
7474
}
7575

7676
return Task.CompletedTask;

src/Files.App/Filesystem/FilesystemOperations/Helpers/FilesystemHelpers.cs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
using Files.Shared.Enums;
1111
using Files.Shared.Extensions;
1212
using Files.Shared.Services;
13+
using Microsoft.Extensions.Logging;
1314
using System;
1415
using System.Collections.Generic;
1516
using System.Diagnostics;
@@ -668,7 +669,7 @@ public static bool IsValidForFilename(string name)
668669
if (collisions.ContainsKey(incomingItems.ElementAt(item.index).SourcePath))
669670
{
670671
// Something strange happened, log
671-
App.Logger.Warn($"Duplicate key when resolving conflicts: {incomingItems.ElementAt(item.index).SourcePath}, {item.src.Name}\n" +
672+
App.Logger.LogWarning($"Duplicate key when resolving conflicts: {incomingItems.ElementAt(item.index).SourcePath}, {item.src.Name}\n" +
672673
$"Source: {string.Join(", ", source.Select(x => string.IsNullOrEmpty(x.Path) ? x.Item.Name : x.Path))}");
673674
}
674675
collisions.AddIfNotPresent(incomingItems.ElementAt(item.index).SourcePath, FileNameConflictResolveOptionType.GenerateNewName);
@@ -753,7 +754,7 @@ public static async Task<IEnumerable<IStorageItemWithPath>> GetDraggedStorageIte
753754
}
754755
catch (Exception ex)
755756
{
756-
App.Logger.Warn(ex, ex.Message);
757+
App.Logger.LogWarning(ex, ex.Message);
757758
return itemsList;
758759
}
759760
}

src/Files.App/Filesystem/LibraryManager.cs

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
using Files.Shared;
66
using Files.Shared.Enums;
77
using Files.Shared.Extensions;
8+
using Microsoft.Extensions.Logging;
89
using Microsoft.UI.Xaml.Controls;
910
using System;
1011
using System.Collections.Generic;
@@ -110,7 +111,7 @@ public static async Task<List<LibraryLocationItem>> ListUserLibraries()
110111
}
111112
catch (Exception e)
112113
{
113-
App.Logger.Warn(e);
114+
App.Logger.LogWarning(e, null);
114115
}
115116

116117
return new();
@@ -170,7 +171,7 @@ public async Task<bool> CreateNewLibrary(string name)
170171
}
171172
catch (Exception e)
172173
{
173-
App.Logger.Warn(e);
174+
App.Logger.LogWarning(e, null);
174175
}
175176

176177
return Task.FromResult<ShellLibraryItem>(null);
@@ -251,7 +252,7 @@ public async Task<LibraryLocationItem> UpdateLibrary(string libraryPath, string
251252
}
252253
catch (Exception e)
253254
{
254-
App.Logger.Warn(e);
255+
App.Logger.LogWarning(e, null);
255256
}
256257

257258
return Task.FromResult<ShellLibraryItem>(null);
@@ -402,7 +403,7 @@ private async void OnLibraryChanged(WatcherChangeTypes changeType, string oldPat
402403
var library = SafetyExtensions.IgnoreExceptions(() => new ShellLibrary2(Shell32.ShellUtil.GetShellItemForPath(newPath), true));
403404
if (library is null)
404405
{
405-
App.Logger.Warn($"Failed to open library after {changeType}: {newPath}");
406+
App.Logger.LogWarning($"Failed to open library after {changeType}: {newPath}");
406407
return;
407408
}
408409

src/Files.App/Filesystem/RecentItems.cs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
using Files.App.Helpers;
22
using Files.App.Shell;
33
using Files.Shared.Extensions;
4+
using Microsoft.Extensions.Logging;
45
using Microsoft.Win32;
56
using System;
67
using System.Collections.Generic;
@@ -141,7 +142,7 @@ public async Task<List<RecentItem>> ListRecentFoldersAsync()
141142
}
142143
catch (Exception ex)
143144
{
144-
App.Logger.Warn(ex, ex.Message);
145+
App.Logger.LogWarning(ex, ex.Message);
145146
}
146147

147148
return null;
@@ -169,7 +170,7 @@ public bool AddToRecentItems(string path)
169170
}
170171
catch (Exception ex)
171172
{
172-
App.Logger.Warn(ex, ex.Message);
173+
App.Logger.LogWarning(ex, ex.Message);
173174
return false;
174175
}
175176
}
@@ -188,7 +189,7 @@ public bool ClearRecentItems()
188189
}
189190
catch (Exception ex)
190191
{
191-
App.Logger.Warn(ex, ex.Message);
192+
App.Logger.LogWarning(ex, ex.Message);
192193
return false;
193194
}
194195
}

0 commit comments

Comments
 (0)