A Swiss Army knife for developers.
C# blazorcross-platformcsharpdesktopdesktop-appdesktop-applicationdeveloper-toolsextensiblefluentfluent-designlinuxmacosmicasyntax-highlightingtypescriptwindowswindows-10windows-11winui
Improved logging
Etienne Baudoux585587a9bce6
diff --git a/src/app/dev/DevToys.Blazor/BuiltInTools/ExtensionsManager/ExtensionInstallationManager.cs b/src/app/dev/DevToys.Blazor/BuiltInTools/ExtensionsManager/ExtensionInstallationManager.csindex 4201ce075..e9af2802f 100644--- a/src/app/dev/DevToys.Blazor/BuiltInTools/ExtensionsManager/ExtensionInstallationManager.cs+++ b/src/app/dev/DevToys.Blazor/BuiltInTools/ExtensionsManager/ExtensionInstallationManager.cs@@ -1,21 +1,28 @@-namespace DevToys.Blazor.BuiltInTools.ExtensionsManager;+using Microsoft.Extensions.Logging;++namespace DevToys.Blazor.BuiltInTools.ExtensionsManager;public static class ExtensionInstallationManager{+ private static readonly ILogger logger = typeof(ExtensionInstallationManager).Log();+public static string PreferredExtensionInstallationFolder { get; set; } = string.Empty;public static string[] ExtensionInstallationFolders { get; set; } = Array.Empty<string>();public static void UninstallExtensionsScheduledForRemoval(){+ DateTime startTime = DateTime.UtcNow;if (!Directory.Exists(PreferredExtensionInstallationFolder)){return;}+ int uninstalledExtensions = 0;string scheduledForUninstallFilePath = Path.Combine(PreferredExtensionInstallationFolder, "uninstall.txt");if (File.Exists(scheduledForUninstallFilePath)){+ logger.LogInformation("There is one or more extension scheduled to be uninstalled.");Process[] appInstances = Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName);// Only uninstall if there's only 1 instance of the app running.@@ -25,26 +32,36 @@ public static class ExtensionInstallationManagerfor (int i = 0; i < lines.Length; i++){+ string extensionInstallationPath = lines[i];+try{// Make sure we're not deleting something that's not in the extension folder. Could be a security concern otherwise.- if (ExtensionInstallationFolders.Any(path => lines[i].StartsWith(path)))+ if (ExtensionInstallationFolders.Any(path => extensionInstallationPath.StartsWith(path))){- if (Directory.Exists(lines[i]))+ if (Directory.Exists(extensionInstallationPath)){- Directory.Delete(lines[i], true);+ Directory.Delete(extensionInstallationPath, true);+ uninstalledExtensions++;}}}- catch+ catch (Exception ex){- // TODO: Log error.+ logger.LogError(ex, "Unable to uninstall extension '{extensionInstallationPath}'", extensionInstallationPath);}}File.Delete(scheduledForUninstallFilePath);}+ else+ {+ logger.LogWarning("Extensions won't be uninstall yet because another instance of the app is running (extensions may be in use at the moment). We will retry next time the app start.");+ }}++ double elapsedMilliseconds = (DateTime.UtcNow - startTime).TotalMilliseconds;+ logger.LogInformation("Finished uninstalling {uninstalledExtensions} extensions in {elapsedMilliseconds}ms", uninstalledExtensions, elapsedMilliseconds);}public static void ScheduleExtensionToBeUninstalled(string extensionInstallationPath)@@ -61,5 +78,6 @@ public static class ExtensionInstallationManager}File.AppendAllLines(scheduledForUninstallFilePath, new[] { extensionInstallationPath });+ logger.LogInformation("Scheduled to uninstall extension '{extensionInstallationPath}' next time the app start.", extensionInstallationPath);}}diff --git a/src/app/dev/DevToys.Core/Mef/MefComposer.cs b/src/app/dev/DevToys.Core/Mef/MefComposer.csindex 54a82d872..206999639 100644--- a/src/app/dev/DevToys.Core/Mef/MefComposer.cs+++ b/src/app/dev/DevToys.Core/Mef/MefComposer.cs@@ -67,6 +67,8 @@ public sealed partial class MefComposer : IDisposabletypeof(MefComposer).Assembly, // DevToys.Core};+ int assemblyCount = assemblies.Count;+// Discover MEF extensions coming from known assemblies.var catalog = new AggregateCatalog();foreach (Assembly assembly in assemblies)@@ -81,7 +83,9 @@ public sealed partial class MefComposer : IDisposableLogDiscoveringPlugin(pluginFolder);try{- catalog.Catalogs.Add(new RecursiveDirectoryCatalog(pluginFolder));+ var directoryCatalog = new RecursiveDirectoryCatalog(pluginFolder);+ assemblyCount += directoryCatalog.AssemblyCount;+ catalog.Catalogs.Add(directoryCatalog);}catch (Exception ex){@@ -100,7 +104,8 @@ public sealed partial class MefComposer : IDisposable}container.Compose(batch);- LogMefComposition((DateTime.Now - startTime).TotalMilliseconds);+ Guard.IsNotNull(container.Catalog);+ LogMefComposition(container.Catalog.Count(), assemblyCount, (DateTime.Now - startTime).TotalMilliseconds);ExportProvider = container;@@ -111,36 +116,32 @@ public sealed partial class MefComposer : IDisposableprivate IEnumerable<string> GetPotentialPluginFolders(){- // TODO: Maybe plugins should be placed in the app's LocalStorage instead?- string appFolder = AppContext.BaseDirectory;- if (!string.IsNullOrEmpty(appFolder))+ string[] pluginFolders;+ if (_pluginFolders is not null){- string[] pluginFolders;- if (_pluginFolders is not null)- {- pluginFolders = _pluginFolders;- }- else- {- pluginFolders = new[] { Path.Combine(appFolder!, "Plugins") };- }+ pluginFolders = _pluginFolders;+ }+ else+ {+ string appFolder = AppContext.BaseDirectory;+ pluginFolders = new[] { Path.Combine(appFolder!, "Plugins") };+ }- for (int i = 0; i < pluginFolders.Length; i++)+ for (int i = 0; i < pluginFolders.Length; i++)+ {+ string pluginFolder = pluginFolders[i];+ if (Directory.Exists(pluginFolder)){- string pluginFolder = pluginFolders[i];- if (Directory.Exists(pluginFolder))+ foreach (string folder in Directory.EnumerateDirectories(pluginFolder, "*", SearchOption.TopDirectoryOnly)){- foreach (string folder in Directory.EnumerateDirectories(pluginFolder, "*", SearchOption.TopDirectoryOnly))- {- yield return folder;- }+ yield return folder;}}}}- [LoggerMessage(0, LogLevel.Information, "MEF composed in {duration} ms")]- partial void LogMefComposition(double duration);+ [LoggerMessage(0, LogLevel.Information, "MEF composed {parts} parts from {assemblies} assemblies in {duration}ms")]+ partial void LogMefComposition(int parts, int assemblies, double duration);[LoggerMessage(1, LogLevel.Information, "Discovering plugin in '{pluginFolder}'...")]partial void LogDiscoveringPlugin(string pluginFolder);diff --git a/src/app/dev/DevToys.Core/Mef/RecursiveDirectoryCatalog.cs b/src/app/dev/DevToys.Core/Mef/RecursiveDirectoryCatalog.csindex 3791d5e0c..defee3fa8 100644--- a/src/app/dev/DevToys.Core/Mef/RecursiveDirectoryCatalog.cs+++ b/src/app/dev/DevToys.Core/Mef/RecursiveDirectoryCatalog.cs@@ -41,6 +41,33 @@ internal sealed partial class RecursiveDirectoryCatalog : ComposablePartCatalog,Initialize(path, searchPattern);}+ /// <summary>+ /// The number of assemblies read from the directory catalog.+ /// </summary>+ internal int AssemblyCount { get; private set; }++ /// <summary>+ /// Gets the part definitions that are contained in the recursive directory catalog. (Overrides ComposablePartCatalog.Parts.)+ /// </summary>+ public override IQueryable<ComposablePartDefinition> Parts+ {+ get+ {+ Guard.IsNotNull(_aggregateCatalog);+ return _aggregateCatalog.Parts;+ }+ }++ /// <summary>+ /// Occurs when the contents of the catalog has changed.+ /// </summary>+ public event EventHandler<ComposablePartCatalogChangeEventArgs>? Changed;++ /// <summary>+ /// Occurs when the catalog is changing.+ /// </summary>+ public event EventHandler<ComposablePartCatalogChangeEventArgs>? Changing;+private void Initialize(string path, string searchPattern){IEnumerable<string> files@@ -62,11 +89,12 @@ internal sealed partial class RecursiveDirectoryCatalog : ComposablePartCatalog,{try{+ AssemblyCount++;var asmCat = new AssemblyCatalog(file);// Force MEF to load the plugin and figure out if there are any exports// good assemblies will not throw the RTLE exception and can be added to the catalog- if (asmCat.Parts.ToList().Count > 0)+ if (asmCat.Parts.Any()){_aggregateCatalog.Catalogs.Add(asmCat);}@@ -81,28 +109,6 @@ internal sealed partial class RecursiveDirectoryCatalog : ComposablePartCatalog,}}- /// <summary>- /// Gets the part definitions that are contained in the recursive directory catalog. (Overrides ComposablePartCatalog.Parts.)- /// </summary>- public override IQueryable<ComposablePartDefinition> Parts- {- get- {- Guard.IsNotNull(_aggregateCatalog);- return _aggregateCatalog.Parts;- }- }-- /// <summary>- /// Occurs when the contents of the catalog has changed.- /// </summary>- public event EventHandler<ComposablePartCatalogChangeEventArgs>? Changed;-- /// <summary>- /// Occurs when the catalog is changing.- /// </summary>- public event EventHandler<ComposablePartCatalogChangeEventArgs>? Changing;-private string GetDisplayName(){return string.Format(diff --git a/src/app/dev/DevToys.Core/Tools/GuiToolProvider.cs b/src/app/dev/DevToys.Core/Tools/GuiToolProvider.csindex 3e6a16160..56e3ba9a9 100644--- a/src/app/dev/DevToys.Core/Tools/GuiToolProvider.cs+++ b/src/app/dev/DevToys.Core/Tools/GuiToolProvider.cs@@ -33,6 +33,8 @@ public sealed partial class GuiToolProvidertypeof(DevToysLocalizationResourceManagerAssemblyIdentifier).Assembly),showLongDisplayTitle: true);+ private static readonly char[] WordSeparator = new char[] { ' ', '\t' };+private readonly ILogger _logger;private readonly IEnumerable<Lazy<IResourceAssemblyIdentifier, ResourceAssemblyIdentifierMetadata>> _resourceAssemblyIdentifiers;private readonly IEnumerable<Lazy<GuiToolGroup, GuiToolGroupMetadata>> _guiToolGroups;@@ -330,7 +332,7 @@ public sealed partial class GuiToolProviderreturn;}- string[] searchQueries = searchQuery.Split(new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);+ string[] searchQueries = searchQuery.Split(WordSeparator, StringSplitOptions.RemoveEmptyEntries);var weightedToolList = new List<(double weight, GuiToolViewItem tool)>();for (int i = 0; i < AllTools.Count; i++)@@ -359,15 +361,15 @@ public sealed partial class GuiToolProviderif (weightedToolList.Count > 0){- var descOrderedWeightedToolList = weightedToolList.OrderByDescending(i => i.weight).ToList();- int thirdQuarterItemIndex = Math.Min((int)(0.25 * descOrderedWeightedToolList.Count), descOrderedWeightedToolList.Count - 1);- double thirdQuarterWeight = descOrderedWeightedToolList[thirdQuarterItemIndex].weight;+ var descOrderedWeightedToolList = weightedToolList.OrderByDescending(i => i.weight).ToList(); // Order by weight.+ int thirdQuarterItemIndex = Math.Min((int)(0.25 * descOrderedWeightedToolList.Count), descOrderedWeightedToolList.Count - 1); // Get the 3/4 item index in the list.+ double thirdQuarterWeight = descOrderedWeightedToolList[thirdQuarterItemIndex].weight; // Get the 3/4 item weight.searchResultListToUpdate.AddRange(descOrderedWeightedToolList- .Take(5)- .TakeWhile(i => i.weight >= thirdQuarterWeight)+ .Take(5) // Take the 5 first items.+ .TakeWhile(i => i.weight >= thirdQuarterWeight) // Take items with a weight greater or equal to the 3/4 item weight. This is to avoid showing too many items with a low weight..Select(i => i.tool));}@@ -404,6 +406,8 @@ public sealed partial class GuiToolProviderout IReadOnlyList<GuiToolInstance> footerTools,out IReadOnlyList<GuiToolInstance> bodyTools){+ DateTime startTime = DateTime.UtcNow;+var allToolInstances = new List<GuiToolInstance>();var footerToolInstances = new List<GuiToolInstance>();var bodyToolInstances = new List<GuiToolInstance>();@@ -464,6 +468,9 @@ public sealed partial class GuiToolProviderallTools = allToolInstances;footerTools = footerToolInstances;bodyTools = bodyToolInstances;++ double elapsedMilliseconds = (DateTime.UtcNow - startTime).TotalMilliseconds;+ LogToolInstancesCreated(allToolInstances.Count, elapsedMilliseconds);}private IEnumerable<GuiToolViewItem> BuildFooterToolViewItems()@@ -717,7 +724,7 @@ public sealed partial class GuiToolProvideri++;}- string[] stringToTestAgainstSplitted = stringToTestAgainst.Split(new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);+ string[] stringToTestAgainstSplitted = stringToTestAgainst.Split(WordSeparator, StringSplitOptions.RemoveEmptyEntries);for (i = 0; i < stringToTestAgainstSplitted.Length; i++){// Fuzzy match@@ -768,4 +775,7 @@ public sealed partial class GuiToolProvider[LoggerMessage(2, LogLevel.Error, "Error while ordering groups.")]partial void LogOrderingGroupsFailed(Exception ex);++ [LoggerMessage(3, LogLevel.Information, "Instantiated {toolCount} tools in {duration}ms")]+ partial void LogToolInstancesCreated(int toolCount, double duration);}