Skip to content

Commit

Permalink
Feature: New Logging provider (#11937)
Browse files Browse the repository at this point in the history
  • Loading branch information
lukeblevins authored Apr 2, 2023
1 parent aec3c54 commit 20ebfe3
Show file tree
Hide file tree
Showing 43 changed files with 228 additions and 315 deletions.
29 changes: 15 additions & 14 deletions src/Files.App/App.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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
{
Expand All @@ -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}";
Expand All @@ -86,9 +85,6 @@ public partial class App : Application
/// </summary>
public App()
{
// Initialize logger
Logger = new Logger(logWriter);

UnhandledException += OnUnhandledException;
TaskScheduler.UnobservedTaskException += OnUnobservedException;
InitializeComponent();
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -174,16 +170,19 @@ 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);

// Initialize MainWindow here
EnsureWindowIsInitialized();
host = Host.CreateDefaultBuilder()
.ConfigureLogging(builder =>
builder
.AddProvider(new FileLoggerProvider(logPath))
.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Information)
)
.ConfigureServices(services =>
services
.AddSingleton<IUserSettingsService, UserSettingsService>()
Expand All @@ -201,7 +200,6 @@ protected override void OnLaunched(LaunchActivatedEventArgs e)
.AddSingleton<IDisplayPageContext, DisplayPageContext>()
.AddSingleton<IWindowContext, WindowContext>()
.AddSingleton<IMultitaskingContext, MultitaskingContext>()
.AddSingleton(Logger)
.AddSingleton<IDialogService, DialogService>()
.AddSingleton<IImageService, ImagingService>()
.AddSingleton<IThreadingService, ThreadingService>()
Expand Down Expand Up @@ -235,10 +233,13 @@ protected override void OnLaunched(LaunchActivatedEventArgs e)
.AddSingleton<AppearanceViewModel>()
)
.Build();
Logger = host.Services.GetRequiredService<ILogger<App>>();
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);
}
Expand All @@ -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));
Expand Down Expand Up @@ -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;
Expand Down
1 change: 1 addition & 0 deletions src/Files.App/Files.App.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@
<PackageReference Include="Microsoft.Data.Sqlite.Core" Version="7.0.4" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="7.0.1" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
<PackageReference Include="Microsoft.Windows.SDK.BuildTools" Version="10.0.22621.756" />
<PackageReference Include="SevenZipSharp" Version="1.0.0" />
<PackageReference Include="SQLitePCLRaw.bundle_green" Version="2.1.4" />
Expand Down
5 changes: 3 additions & 2 deletions src/Files.App/Filesystem/Archive/ArchiveCreator.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using CommunityToolkit.Mvvm.DependencyInjection;
using Files.Shared;
using Microsoft.Extensions.Logging;
using SevenZip;
using System;
using System.Collections.Generic;
Expand Down Expand Up @@ -144,8 +145,8 @@ public async Task<bool> RunCreationAsync()
}
catch (Exception ex)
{
var logger = Ioc.Default.GetService<ILogger>();
logger?.Warn(ex, $"Error compressing folder: {archivePath}");
var logger = Ioc.Default.GetRequiredService<ILogger<App>>();
logger?.LogWarning(ex, $"Error compressing folder: {archivePath}");

return false;
}
Expand Down
7 changes: 4 additions & 3 deletions src/Files.App/Filesystem/Cloud/CloudDrivesManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -15,7 +16,7 @@ namespace Files.App.Filesystem.Cloud
{
public class CloudDrivesManager
{
private readonly ILogger logger = Ioc.Default.GetService<ILogger>();
private readonly ILogger logger = Ioc.Default.GetRequiredService<ILogger<App>>();
private readonly ICloudDetector detector = Ioc.Default.GetService<ICloudDetector>();

public EventHandler<NotifyCollectionChangedEventArgs> DataChanged;
Expand All @@ -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,
Expand All @@ -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
Expand Down
19 changes: 10 additions & 9 deletions src/Files.App/Filesystem/Drives.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -24,7 +25,7 @@ namespace Files.App.Filesystem
{
public class DrivesManager : ObservableObject
{
private readonly ILogger logger = Ioc.Default.GetService<ILogger>();
private readonly ILogger logger = Ioc.Default.GetRequiredService<ILogger<App>>();
private readonly ISizeProvider folderSizeProvider = Ioc.Default.GetService<ISizeProvider>();

private bool isDriveEnumInProgress;
Expand Down Expand Up @@ -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;
}
Expand All @@ -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);
}

Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -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);
}

Expand All @@ -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);
Expand Down Expand Up @@ -332,13 +333,13 @@ private async Task<bool> 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;
}
Expand All @@ -355,7 +356,7 @@ private async Task<bool> GetDrivesAsync()
continue;
}

logger.Info($"Drive added: {driveItem.Path}, {driveItem.Type}");
logger.LogInformation($"Drive added: {driveItem.Path}, {driveItem.Type}");
drives.Add(driveItem);
}

Expand Down
6 changes: 3 additions & 3 deletions src/Files.App/Filesystem/FileTagsManager.cs
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -12,7 +12,7 @@ namespace Files.App.Filesystem
{
public class FileTagsManager
{
private readonly ILogger logger = Ioc.Default.GetService<ILogger>();
private readonly ILogger logger = Ioc.Default.GetRequiredService<ILogger<App>>();
private readonly IFileTagsSettingsService fileTagsSettingsService = Ioc.Default.GetService<IFileTagsSettingsService>();

public EventHandler<NotifyCollectionChangedEventArgs> DataChanged;
Expand Down Expand Up @@ -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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -753,7 +754,7 @@ public static async Task<IEnumerable<IStorageItemWithPath>> GetDraggedStorageIte
}
catch (Exception ex)
{
App.Logger.Warn(ex, ex.Message);
App.Logger.LogWarning(ex, ex.Message);
return itemsList;
}
}
Expand Down
9 changes: 5 additions & 4 deletions src/Files.App/Filesystem/LibraryManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -110,7 +111,7 @@ public static async Task<List<LibraryLocationItem>> ListUserLibraries()
}
catch (Exception e)
{
App.Logger.Warn(e);
App.Logger.LogWarning(e, null);
}

return new();
Expand Down Expand Up @@ -170,7 +171,7 @@ public async Task<bool> CreateNewLibrary(string name)
}
catch (Exception e)
{
App.Logger.Warn(e);
App.Logger.LogWarning(e, null);
}

return Task.FromResult<ShellLibraryItem>(null);
Expand Down Expand Up @@ -251,7 +252,7 @@ public async Task<LibraryLocationItem> UpdateLibrary(string libraryPath, string
}
catch (Exception e)
{
App.Logger.Warn(e);
App.Logger.LogWarning(e, null);
}

return Task.FromResult<ShellLibraryItem>(null);
Expand Down Expand Up @@ -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;
}

Expand Down
7 changes: 4 additions & 3 deletions src/Files.App/Filesystem/RecentItems.cs
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -141,7 +142,7 @@ public async Task<List<RecentItem>> ListRecentFoldersAsync()
}
catch (Exception ex)
{
App.Logger.Warn(ex, ex.Message);
App.Logger.LogWarning(ex, ex.Message);
}

return null;
Expand Down Expand Up @@ -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;
}
}
Expand All @@ -188,7 +189,7 @@ public bool ClearRecentItems()
}
catch (Exception ex)
{
App.Logger.Warn(ex, ex.Message);
App.Logger.LogWarning(ex, ex.Message);
return false;
}
}
Expand Down
Loading

0 comments on commit 20ebfe3

Please sign in to comment.