diff --git a/src/modules/launcher/Plugins/Microsoft.Plugin.Calculator/Main.cs b/src/modules/launcher/Plugins/Microsoft.Plugin.Calculator/Main.cs index 0195c68f66..90247b1e8f 100644 --- a/src/modules/launcher/Plugins/Microsoft.Plugin.Calculator/Main.cs +++ b/src/modules/launcher/Plugins/Microsoft.Plugin.Calculator/Main.cs @@ -51,7 +51,7 @@ namespace Microsoft.Plugin.Calculator catch (Exception e) #pragma warning restore CA1031 // Do not catch general exception types { - Log.Exception($"|Microsoft.Plugin.Calculator.Main.Query|Exception when query for <{query}>", e); + Log.Exception("Exception when query for <{query}>", e, GetType()); } return new List(); diff --git a/src/modules/launcher/Plugins/Microsoft.Plugin.Folder/ContextMenuLoader.cs b/src/modules/launcher/Plugins/Microsoft.Plugin.Folder/ContextMenuLoader.cs index 04964aaa8f..be368be864 100644 --- a/src/modules/launcher/Plugins/Microsoft.Plugin.Folder/ContextMenuLoader.cs +++ b/src/modules/launcher/Plugins/Microsoft.Plugin.Folder/ContextMenuLoader.cs @@ -54,7 +54,7 @@ namespace Microsoft.Plugin.Folder catch (Exception e) { var message = Properties.Resources.Microsoft_plugin_folder_clipboard_failed; - LogException(message, e); + Log.Exception(message, e, GetType()); _context.API.ShowMsg(message); return false; } @@ -87,7 +87,8 @@ namespace Microsoft.Plugin.Folder } catch (Exception e) { - Log.Exception($"|Microsoft.Plugin.Folder.ContextMenuLoader.LoadContextMenus| Failed to open {record.FullPath} in console, {e.Message}", e); + Log.Exception($"Failed to open {record.FullPath} in console, {e.Message}", e, GetType()); + return false; } }, @@ -117,8 +118,9 @@ namespace Microsoft.Plugin.Folder catch (Exception e) { var message = $"{Properties.Resources.Microsoft_plugin_folder_file_open_failed} {record.FullPath}"; - LogException(message, e); + Log.Exception(message, e, GetType()); _context.API.ShowMsg(message); + return false; } @@ -126,11 +128,6 @@ namespace Microsoft.Plugin.Folder }, }; } - - public static void LogException(string message, Exception e) - { - Log.Exception($"|Microsoft.Plugin.Folder.ContextMenu|{message}", e); - } } public enum ResultType diff --git a/src/modules/launcher/Plugins/Microsoft.Plugin.Folder/Main.cs b/src/modules/launcher/Plugins/Microsoft.Plugin.Folder/Main.cs index 54ed650d24..977d2356d6 100644 --- a/src/modules/launcher/Plugins/Microsoft.Plugin.Folder/Main.cs +++ b/src/modules/launcher/Plugins/Microsoft.Plugin.Folder/Main.cs @@ -8,6 +8,7 @@ using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; +using System.Reflection; using System.Text.RegularExpressions; using System.Windows; using System.Windows.Controls; @@ -120,7 +121,7 @@ namespace Microsoft.Plugin.Folder catch (Exception e) { string messageBoxTitle = string.Format(CultureInfo.InvariantCulture, "{0} {1}", Properties.Resources.wox_plugin_folder_select_folder_OpenFileOrFolder_error_message, path); - Log.Exception($"|Microsoft.Plugin.Folder.Main.OpenFileOrFolder| Failed to open {path} in explorer, {e.Message}", e); + Log.Exception($"Failed to open {path} in explorer, {e.Message}", e, MethodBase.GetCurrentMethod().DeclaringType); _context.API.ShowMsg(messageBoxTitle, e.Message); } diff --git a/src/modules/launcher/Plugins/Microsoft.Plugin.Indexer/ContextMenuLoader.cs b/src/modules/launcher/Plugins/Microsoft.Plugin.Indexer/ContextMenuLoader.cs index 7b8e11c39c..b2885e8321 100644 --- a/src/modules/launcher/Plugins/Microsoft.Plugin.Indexer/ContextMenuLoader.cs +++ b/src/modules/launcher/Plugins/Microsoft.Plugin.Indexer/ContextMenuLoader.cs @@ -73,7 +73,8 @@ namespace Microsoft.Plugin.Indexer catch (Exception e) { var message = Properties.Resources.Microsoft_plugin_indexer_clipboard_failed; - LogException(message, e); + Log.Exception(message, e, GetType()); + _context.API.ShowMsg(message); return false; } @@ -105,7 +106,7 @@ namespace Microsoft.Plugin.Indexer } catch (Exception e) { - Log.Exception($"|Microsoft.Plugin.Indexer.ContextMenuLoader.LoadContextMenus| Failed to open {record.Path} in console, {e.Message}", e); + Log.Exception($"Failed to open {record.Path} in console, {e.Message}", e, GetType()); return false; } }, @@ -136,7 +137,7 @@ namespace Microsoft.Plugin.Indexer } catch (Exception e) { - Log.Exception($"|Microsoft.Plugin.Indexer.ContextMenu| Failed to run {record.Path} as admin, {e.Message}", e); + Log.Exception($"Failed to run {record.Path} as admin, {e.Message}", e, MethodBase.GetCurrentMethod().DeclaringType); return false; } }, @@ -178,7 +179,8 @@ namespace Microsoft.Plugin.Indexer catch (Exception e) { var message = $"{Properties.Resources.Microsoft_plugin_indexer_folder_open_failed} {record.Path}"; - LogException(message, e); + Log.Exception(message, e, GetType()); + _context.API.ShowMsg(message); return false; } @@ -187,10 +189,5 @@ namespace Microsoft.Plugin.Indexer }, }; } - - public static void LogException(string message, Exception e) - { - Log.Exception($"|Microsoft.Plugin.Folder.ContextMenu|{message}", e); - } } } diff --git a/src/modules/launcher/Plugins/Microsoft.Plugin.Indexer/Main.cs b/src/modules/launcher/Plugins/Microsoft.Plugin.Indexer/Main.cs index 9c6906f4ac..93adfb5ac5 100644 --- a/src/modules/launcher/Plugins/Microsoft.Plugin.Indexer/Main.cs +++ b/src/modules/launcher/Plugins/Microsoft.Plugin.Indexer/Main.cs @@ -88,7 +88,7 @@ namespace Microsoft.Plugin.Indexer } catch (Exception ex) { - Log.Exception("Microsoft.Plugin.Indexer", $"Unable to launch Windows Search Settings: {ex.Message}", ex, "Query"); + Log.Exception($"Unable to launch Windows Search Settings: {ex.Message}", ex, GetType()); } return true; @@ -163,7 +163,7 @@ namespace Microsoft.Plugin.Indexer } catch (Exception ex) { - Log.Info(ex.ToString()); + Log.Exception("Something failed", ex, GetType()); } } } diff --git a/src/modules/launcher/Plugins/Microsoft.Plugin.Program/Logger/ProgramLogger.cs b/src/modules/launcher/Plugins/Microsoft.Plugin.Program/Logger/ProgramLogger.cs index ed8e4097f2..825be50585 100644 --- a/src/modules/launcher/Plugins/Microsoft.Plugin.Program/Logger/ProgramLogger.cs +++ b/src/modules/launcher/Plugins/Microsoft.Plugin.Program/Logger/ProgramLogger.cs @@ -22,51 +22,29 @@ namespace Microsoft.Plugin.Program.Logger /// Logs an exception /// [MethodImpl(MethodImplOptions.Synchronized)] - internal static void LogException(string classname, string callingMethodName, string loadingProgramPath, string interpretationMessage, Exception e) + internal static void Exception(string message, Exception ex, Type fullClassName, string loadingProgramPath, [CallerMemberName] string methodName = "", [CallerFilePath] string sourceFilePath = "", [CallerLineNumber] int sourceLineNumber = 0) { - Debug.WriteLine($"ERROR{classname}|{callingMethodName}|{loadingProgramPath}|{interpretationMessage}"); - + // internal static void LogException(string classname, string callingMethodName, string loadingProgramPath, string interpretationMessage, Exception e) var possibleResolution = "Not yet known"; var errorStatus = "UNKNOWN"; - if (IsKnownWinProgramError(e, callingMethodName) || IsKnownUWPProgramError(e, callingMethodName)) + if (IsKnownWinProgramError(ex, methodName) || IsKnownUWPProgramError(ex, methodName)) { possibleResolution = "Can be ignored and Wox should still continue, however the program may not be loaded"; errorStatus = "KNOWN"; } - var calledMethod = e.TargetSite != null ? e.TargetSite.ToString() : e.StackTrace; + var calledMethod = ex.TargetSite != null ? ex.TargetSite.ToString() : ex.StackTrace; calledMethod = string.IsNullOrEmpty(calledMethod) ? "Not available" : calledMethod; - var msg = $"Error status: {errorStatus}" - + $"\nProgram path: {loadingProgramPath}" - + $"\nException thrown in called method: {calledMethod}" - + $"\nPossible interpretation of the error: {interpretationMessage}" - + $"\nPossible resolution: {possibleResolution}"; + var msg = $"\tError status: {errorStatus}" + + $"\n\t\tProgram path: {loadingProgramPath}" + + $"\n\t\tException thrown in called method: {calledMethod}" + + $"\n\t\tPossible interpretation of the error: {message}" + + $"\n\t\tPossible resolution: {possibleResolution}"; // removed looping logic since that is inside Log class - Log.Exception(classname, msg, e, callingMethodName); - } - - /// - /// Please follow exception format: |class name|calling method name|loading program path|user friendly message that explains the error - /// => Example: |Win32|LnkProgram|c:\..\chrome.exe|Permission denied on directory, but Wox should continue - /// - [MethodImpl(MethodImplOptions.Synchronized)] - internal static void LogException(string message, Exception e) - { - var parts = message.Split('|'); - if (parts.Length < 4) - { - Log.Exception($"|ProgramLogger|LogException|Fail to log exception in program logger, parts length is too small: {parts.Length}, message: {message}", e); - } - - var classname = parts[1]; - var callingMethodName = parts[2]; - var loadingProgramPath = parts[3]; - var interpretationMessage = parts[4]; - - LogException(classname, callingMethodName, loadingProgramPath, interpretationMessage, e); + Log.Exception(msg, ex, fullClassName, methodName, sourceFilePath, sourceLineNumber); } private static bool IsKnownWinProgramError(Exception e, string callingMethodName) diff --git a/src/modules/launcher/Plugins/Microsoft.Plugin.Program/Programs/PackageWrapper.cs b/src/modules/launcher/Plugins/Microsoft.Plugin.Program/Programs/PackageWrapper.cs index 1200fab18a..fdcc0a7161 100644 --- a/src/modules/launcher/Plugins/Microsoft.Plugin.Program/Programs/PackageWrapper.cs +++ b/src/modules/launcher/Plugins/Microsoft.Plugin.Program/Programs/PackageWrapper.cs @@ -4,6 +4,7 @@ using System; using System.IO; +using System.Reflection; using Microsoft.Plugin.Program.Logger; using Package = Windows.ApplicationModel.Package; @@ -51,7 +52,7 @@ namespace Microsoft.Plugin.Program.Programs } catch (Exception e) when (e is ArgumentException || e is FileNotFoundException || e is DirectoryNotFoundException) { - ProgramLogger.LogException($"PackageWrapper", "GetWrapperFromPackage", "Path could not be determined", $"Exception {package.Id.Name}", e); + ProgramLogger.Exception($"Exception {package.Id.Name}", e, MethodBase.GetCurrentMethod().DeclaringType, "Path could not be determined"); return new PackageWrapper( package.Id.Name, package.Id.FullName, diff --git a/src/modules/launcher/Plugins/Microsoft.Plugin.Program/Programs/PackagemanagerWrapper.cs b/src/modules/launcher/Plugins/Microsoft.Plugin.Program/Programs/PackagemanagerWrapper.cs index 2d4d6ce9df..7a9ee51053 100644 --- a/src/modules/launcher/Plugins/Microsoft.Plugin.Program/Programs/PackagemanagerWrapper.cs +++ b/src/modules/launcher/Plugins/Microsoft.Plugin.Program/Programs/PackagemanagerWrapper.cs @@ -38,7 +38,7 @@ namespace Microsoft.Plugin.Program.Programs } catch (Exception e) { - Log.Error(nameof(PackageManagerWrapper), e.Message, nameof(FindPackagesForCurrentUser)); + Log.Error(e.Message, GetType()); } } } diff --git a/src/modules/launcher/Plugins/Microsoft.Plugin.Program/Programs/ShellLinkHelper.cs b/src/modules/launcher/Plugins/Microsoft.Plugin.Program/Programs/ShellLinkHelper.cs index 5c7f37b644..792c8da879 100644 --- a/src/modules/launcher/Plugins/Microsoft.Plugin.Program/Programs/ShellLinkHelper.cs +++ b/src/modules/launcher/Plugins/Microsoft.Plugin.Program/Programs/ShellLinkHelper.cs @@ -142,7 +142,7 @@ namespace Microsoft.Plugin.Program.Programs } catch (System.IO.FileNotFoundException ex) { - ProgramLogger.LogException($"|Win32| ShellLinkHelper.retrieveTargetPath | {path} | Path could not be retrieved", ex); + ProgramLogger.Exception("Path could not be retrieved", ex, GetType(), path); return string.Empty; } diff --git a/src/modules/launcher/Plugins/Microsoft.Plugin.Program/Programs/UWP.cs b/src/modules/launcher/Plugins/Microsoft.Plugin.Program/Programs/UWP.cs index 42cf3e512f..ed8c2d0537 100644 --- a/src/modules/launcher/Plugins/Microsoft.Plugin.Program/Programs/UWP.cs +++ b/src/modules/launcher/Plugins/Microsoft.Plugin.Program/Programs/UWP.cs @@ -6,6 +6,7 @@ using System; using System.Collections.Generic; using System.IO; using System.Linq; +using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.InteropServices.ComTypes; using System.Xml.Linq; @@ -80,9 +81,7 @@ namespace Microsoft.Plugin.Program.Programs else { var e = Marshal.GetExceptionForHR((int)hResult); - ProgramLogger.LogException( - $"|UWP|InitializeAppInfo|{path}" + - "|Error caused while trying to get the details of the UWP program", e); + ProgramLogger.Exception("Error caused while trying to get the details of the UWP program", e, GetType(), path); Apps = new List().ToArray(); } @@ -104,7 +103,7 @@ namespace Microsoft.Plugin.Program.Programs } else { - Log.Error($"|UWP.XmlNamespaces|Error occurred while trying to get the XML from {path}"); + Log.Error($"Error occurred while trying to get the XML from {path}", MethodBase.GetCurrentMethod().DeclaringType); return Array.Empty(); } @@ -128,10 +127,7 @@ namespace Microsoft.Plugin.Program.Programs } } - ProgramLogger.LogException( - $"|UWP|XmlNamespaces|{Location}" + - "|Trying to get the package version of the UWP program, but a unknown UWP appmanifest version " - + $"{FullName} from location {Location} is returned.", new FormatException()); + ProgramLogger.Exception($"|Trying to get the package version of the UWP program, but a unknown UWP appmanifest version {FullName} from location {Location} is returned.", new FormatException(), GetType(), Location); Version = PackageVersion.Unknown; } @@ -153,9 +149,8 @@ namespace Microsoft.Plugin.Program.Programs } catch (Exception e) { - ProgramLogger.LogException( - $"|UWP|All|{p.InstalledLocation}|An unexpected error occurred and " - + $"unable to convert Package to UWP for {p.FullName}", e); + ProgramLogger.Exception($"Unable to convert Package to UWP for {p.FullName}", e, MethodBase.GetCurrentMethod().DeclaringType, p.InstalledLocation); + return Array.Empty(); } @@ -190,7 +185,7 @@ namespace Microsoft.Plugin.Program.Programs } catch (Exception e) { - ProgramLogger.LogException("UWP", "CurrentUserPackages", $"id", "An unexpected error occurred and unable to verify if package is valid", e); + ProgramLogger.Exception("An unexpected error occurred and unable to verify if package is valid", e, MethodBase.GetCurrentMethod().DeclaringType, "id"); return false; } diff --git a/src/modules/launcher/Plugins/Microsoft.Plugin.Program/Programs/UWPApplication.cs b/src/modules/launcher/Plugins/Microsoft.Plugin.Program/Programs/UWPApplication.cs index c9e0275168..1cec7be9df 100644 --- a/src/modules/launcher/Plugins/Microsoft.Plugin.Program/Programs/UWPApplication.cs +++ b/src/modules/launcher/Plugins/Microsoft.Plugin.Program/Programs/UWPApplication.cs @@ -185,7 +185,7 @@ namespace Microsoft.Plugin.Program.Programs } catch (Exception e) { - Log.Exception($"|Microsoft.Plugin.Program.UWP.ContextMenu| Failed to open {Name} in console, {e.Message}", e); + Log.Exception($"Failed to open {Name} in console, {e.Message}", e, GetType()); return false; } }, @@ -310,9 +310,8 @@ namespace Microsoft.Plugin.Program.Programs } else { - ProgramLogger.LogException( - $"|UWP|ResourceFromPri|{Package.Location}|Can't load null or empty result " - + $"pri {source} in uwp location {Package.Location}", new NullReferenceException()); + ProgramLogger.Exception($"Can't load null or empty result pri {source} in uwp location {Package.Location}", new NullReferenceException(), GetType(), Package.Location); + return string.Empty; } } @@ -325,7 +324,8 @@ namespace Microsoft.Plugin.Program.Programs // Microsoft.MicrosoftOfficeHub_17.7608.23501.0_x64__8wekyb3d8bbwe: ms-resource://Microsoft.MicrosoftOfficeHub/officehubintl/AppManifest_GetOffice_Description // Microsoft.BingFoodAndDrink_3.0.4.336_x64__8wekyb3d8bbwe: ms-resource:AppDescription var e = Marshal.GetExceptionForHR((int)hResult); - ProgramLogger.LogException($"|UWP|ResourceFromPri|{Package.Location}|Load pri failed {source} with HResult {hResult} and location {Package.Location}", e); + ProgramLogger.Exception($"Load pri failed {source} with HResult {hResult} and location {Package.Location}", e, GetType(), Package.Location); + return string.Empty; } } @@ -569,9 +569,7 @@ namespace Microsoft.Plugin.Program.Programs { LogoPath = string.Empty; LogoType = LogoType.Error; - ProgramLogger.LogException( - $"|UWP|LogoPathFromUri|{Package.Location}" + - $"|{UserModelId} can't find logo uri for {uri} in package location: {Package.Location}", new FileNotFoundException()); + ProgramLogger.Exception($"|{UserModelId} can't find logo uri for {uri} in package location: {Package.Location}", new FileNotFoundException(), GetType(), Package.Location); } } @@ -589,6 +587,8 @@ namespace Microsoft.Plugin.Program.Programs } } + private const int _dpiScale100 = 96; + private ImageSource PlatedImage(BitmapImage image) { if (!string.IsNullOrEmpty(BackgroundColor)) @@ -630,21 +630,21 @@ namespace Microsoft.Plugin.Program.Programs var context = visual.RenderOpen(); context.DrawDrawing(group); context.Close(); - const int dpiScale100 = 96; + var bitmap = new RenderTargetBitmap( Convert.ToInt32(width), Convert.ToInt32(height), - dpiScale100, - dpiScale100, + _dpiScale100, + _dpiScale100, PixelFormats.Pbgra32); + bitmap.Render(visual); + return bitmap; } else { - ProgramLogger.LogException( - $"|UWP|PlatedImage|{Package.Location}|Unable to convert background string {BackgroundColor} " + - $"to color for {Package.Location}", new InvalidOperationException()); + ProgramLogger.Exception($"Unable to convert background string {BackgroundColor} to color for {Package.Location}", new InvalidOperationException(), GetType(), Package.Location); return new BitmapImage(new Uri(Constant.ErrorIcon)); } @@ -674,9 +674,7 @@ namespace Microsoft.Plugin.Program.Programs } else { - ProgramLogger.LogException( - $"|UWP|ImageFromPath|{path}|Unable to get logo for {UserModelId} from {path} and" + - $" located in {Package.Location}", new FileNotFoundException()); + ProgramLogger.Exception($"Unable to get logo for {UserModelId} from {path} and located in {Package.Location}", new FileNotFoundException(), GetType(), path); return new BitmapImage(new Uri(ImageLoader.ErrorIconPath)); } } diff --git a/src/modules/launcher/Plugins/Microsoft.Plugin.Program/Programs/Win32Program.cs b/src/modules/launcher/Plugins/Microsoft.Plugin.Program/Programs/Win32Program.cs index 852faddad6..67d88f95d0 100644 --- a/src/modules/launcher/Plugins/Microsoft.Plugin.Program/Programs/Win32Program.cs +++ b/src/modules/launcher/Plugins/Microsoft.Plugin.Program/Programs/Win32Program.cs @@ -316,7 +316,7 @@ namespace Microsoft.Plugin.Program.Programs } catch (Exception e) { - Log.Exception($"|Microsoft.Plugin.Program.Win32.ContextMenu| Failed to open {Name} in console, {e.Message}", e); + Log.Exception($"|Failed to open {Name} in console, {e.Message}", e, GetType()); return false; } }, @@ -351,9 +351,7 @@ namespace Microsoft.Plugin.Program.Programs } catch (Exception e) when (e is SecurityException || e is UnauthorizedAccessException) { - ProgramLogger.LogException( - $"|Win32|Win32Program|{path}" + - $"|Permission denied when trying to load the program from {path}", e); + ProgramLogger.Exception($"|Permission denied when trying to load the program from {path}", e, MethodBase.GetCurrentMethod().DeclaringType, path); return new Win32Program() { Valid = false, Enabled = false }; } @@ -386,7 +384,7 @@ namespace Microsoft.Plugin.Program.Programs { // To catch the exception if the uri cannot be parsed. // Link to watson crash: https://watsonportal.microsoft.com/Failure?FailureSearchText=5f871ea7-e886-911f-1b31-131f63f6655b - ProgramLogger.LogException($"|Win32Program|InternetShortcutProgram|{urlPath}|url could not be parsed", e); + ProgramLogger.Exception($"url could not be parsed", e, MethodBase.GetCurrentMethod().DeclaringType, urlPath); return new Win32Program() { Valid = false, Enabled = false }; } @@ -426,9 +424,7 @@ namespace Microsoft.Plugin.Program.Programs } catch (Exception e) when (e is SecurityException || e is UnauthorizedAccessException) { - ProgramLogger.LogException( - $"|Win32|InternetShortcutProgram|{path}" + - $"|Permission denied when trying to load the program from {path}", e); + ProgramLogger.Exception($"|Permission denied when trying to load the program from {path}", e, MethodBase.GetCurrentMethod().DeclaringType, path); return new Win32Program() { Valid = false, Enabled = false }; } @@ -476,9 +472,7 @@ namespace Microsoft.Plugin.Program.Programs // Error caused likely due to trying to get the description of the program catch (Exception e) { - ProgramLogger.LogException( - $"|Win32|LnkProgram|{path}" + - "|An unexpected error occurred in the calling method LnkProgram", e); + ProgramLogger.Exception("An unexpected error occurred in the calling method LnkProgram", e, MethodBase.GetCurrentMethod().DeclaringType, path); program.Valid = false; return program; @@ -501,17 +495,13 @@ namespace Microsoft.Plugin.Program.Programs } catch (Exception e) when (e is SecurityException || e is UnauthorizedAccessException) { - ProgramLogger.LogException( - $"|Win32|ExeProgram|{path}" + - $"|Permission denied when trying to load the program from {path}", e); + ProgramLogger.Exception($"|Permission denied when trying to load the program from {path}", e, MethodBase.GetCurrentMethod().DeclaringType, path); return new Win32Program() { Valid = false, Enabled = false }; } catch (FileNotFoundException e) { - ProgramLogger.LogException( - $"|Win32|ExeProgram|{path}" + - $"|Unable to locate exe file at {path}", e); + ProgramLogger.Exception($"|Unable to locate exe file at {path}", e, MethodBase.GetCurrentMethod().DeclaringType, path); return new Win32Program() { Valid = false, Enabled = false }; } @@ -619,17 +609,13 @@ namespace Microsoft.Plugin.Program.Programs } catch (DirectoryNotFoundException e) { - ProgramLogger.LogException( - $"|Win32|ProgramPaths|{currentDirectory}" + - "|The directory trying to load the program from does not exist", e); + ProgramLogger.Exception("|The directory trying to load the program from does not exist", e, MethodBase.GetCurrentMethod().DeclaringType, currentDirectory); } } } catch (Exception e) when (e is SecurityException || e is UnauthorizedAccessException) { - ProgramLogger.LogException( - $"|Win32|ProgramPaths|{currentDirectory}" + - $"|Permission denied when trying to load programs from {currentDirectory}", e); + ProgramLogger.Exception($"|Permission denied when trying to load programs from {currentDirectory}", e, MethodBase.GetCurrentMethod().DeclaringType, currentDirectory); } try @@ -647,9 +633,7 @@ namespace Microsoft.Plugin.Program.Programs } catch (Exception e) when (e is SecurityException || e is UnauthorizedAccessException) { - ProgramLogger.LogException( - $"|Win32|ProgramPaths|{currentDirectory}" + - $"|Permission denied when trying to load programs from {currentDirectory}", e); + ProgramLogger.Exception($"|Permission denied when trying to load programs from {currentDirectory}", e, MethodBase.GetCurrentMethod().DeclaringType, currentDirectory); } } while (folderQueue.Any()); @@ -841,9 +825,7 @@ namespace Microsoft.Plugin.Program.Programs } catch (Exception e) when (e is SecurityException || e is UnauthorizedAccessException) { - ProgramLogger.LogException( - $"|Win32|GetProgramPathFromRegistrySubKeys|{path}" + - $"|Permission denied when trying to load the program from {path}", e); + ProgramLogger.Exception($"|Permission denied when trying to load the program from {path}", e, MethodBase.GetCurrentMethod().DeclaringType, path); return string.Empty; } @@ -963,7 +945,7 @@ namespace Microsoft.Plugin.Program.Programs } catch (Exception e) { - ProgramLogger.LogException("|Win32|All|Not available|An unexpected error occurred", e); + ProgramLogger.Exception("An unexpected error occurred", e, MethodBase.GetCurrentMethod().DeclaringType, "Not available"); return Array.Empty(); } diff --git a/src/modules/launcher/Plugins/Microsoft.Plugin.Program/Storage/PackageRepository.cs b/src/modules/launcher/Plugins/Microsoft.Plugin.Program/Storage/PackageRepository.cs index 9759823f5b..e570cff973 100644 --- a/src/modules/launcher/Plugins/Microsoft.Plugin.Program/Storage/PackageRepository.cs +++ b/src/modules/launcher/Plugins/Microsoft.Plugin.Program/Storage/PackageRepository.cs @@ -53,7 +53,7 @@ namespace Microsoft.Plugin.Program.Storage // eg. "Could not find file 'C:\\Program Files\\WindowsApps\\Microsoft.WindowsTerminalPreview_2020.616.45.0_neutral_~_8wekyb3d8bbwe\\AppxManifest.xml'." catch (System.IO.FileNotFoundException e) { - ProgramLogger.LogException($"|UWP|OnPackageInstalling|{args.Package.InstalledLocation}|{e.Message}", e); + ProgramLogger.Exception(e.Message, e, GetType(), args.Package.InstalledLocation.ToString()); } } } @@ -66,6 +66,7 @@ namespace Microsoft.Plugin.Program.Storage var packageWrapper = PackageWrapper.GetWrapperFromPackage(args.Package); var uwp = new UWP(packageWrapper); var apps = Items.Where(a => a.Package.Equals(uwp)).ToArray(); + foreach (var app in apps) { Remove(app); diff --git a/src/modules/launcher/Plugins/Microsoft.Plugin.Program/Storage/Win32ProgramRepository.cs b/src/modules/launcher/Plugins/Microsoft.Plugin.Program/Storage/Win32ProgramRepository.cs index d7bec7c65f..b47ad6bcd0 100644 --- a/src/modules/launcher/Plugins/Microsoft.Plugin.Program/Storage/Win32ProgramRepository.cs +++ b/src/modules/launcher/Plugins/Microsoft.Plugin.Program/Storage/Win32ProgramRepository.cs @@ -94,7 +94,7 @@ namespace Microsoft.Plugin.Program.Storage } catch (Exception ex) { - Log.Info($"|Win32ProgramRepository|OnAppRenamed-{extension}Program|{oldPath}|Unable to create program from {oldPath}| {ex.Message}"); + Log.Exception($"OnAppRenamed-{extension}Program|{oldPath}|Unable to create program from {oldPath}", ex, GetType()); } // To remove the old app which has been renamed and to add the new application. @@ -134,7 +134,7 @@ namespace Microsoft.Plugin.Program.Storage } catch (Exception ex) { - Log.Info($"|Win32ProgramRepository|OnAppDeleted-{extension}Program|{path}|Unable to create program from {path}| {ex.Message}"); + Log.Exception($"OnAppDeleted-{extension}Program|{path}|Unable to create program from {path}", ex, GetType()); } if (app != null) diff --git a/src/modules/launcher/Plugins/Microsoft.Plugin.Shell/Main.cs b/src/modules/launcher/Plugins/Microsoft.Plugin.Shell/Main.cs index fa9019b9d9..a698ffbcc7 100644 --- a/src/modules/launcher/Plugins/Microsoft.Plugin.Shell/Main.cs +++ b/src/modules/launcher/Plugins/Microsoft.Plugin.Shell/Main.cs @@ -68,7 +68,7 @@ namespace Microsoft.Plugin.Shell } catch (Exception e) { - Log.Exception($"|Microsoft.Plugin.Shell.Main.Query|Exception when query for <{query}>", e); + Log.Exception($"Exception when query for <{query}>", e, GetType()); } return results; diff --git a/src/modules/launcher/Plugins/Microsoft.Plugin.Uri/Main.cs b/src/modules/launcher/Plugins/Microsoft.Plugin.Uri/Main.cs index 0760133ee7..2b05ab239d 100644 --- a/src/modules/launcher/Plugins/Microsoft.Plugin.Uri/Main.cs +++ b/src/modules/launcher/Plugins/Microsoft.Plugin.Uri/Main.cs @@ -145,7 +145,7 @@ namespace Microsoft.Plugin.Uri catch (Exception e) { BrowserIconPath = DefaultIconPath; - Log.Exception("Exception when retreiving icon", e); + Log.Exception("Exception when retreiving icon", e, GetType()); } } diff --git a/src/modules/launcher/PowerLauncher/App.xaml.cs b/src/modules/launcher/PowerLauncher/App.xaml.cs index 64ae5c3b64..dd38a47753 100644 --- a/src/modules/launcher/PowerLauncher/App.xaml.cs +++ b/src/modules/launcher/PowerLauncher/App.xaml.cs @@ -82,8 +82,9 @@ namespace PowerLauncher bootTime.Start(); Stopwatch.Normal("|App.OnStartup|Startup cost", () => { - Log.Info("|App.OnStartup|Begin PowerToys Run startup ----------------------------------------------------"); - Log.Info($"|App.OnStartup|Runtime info:{ErrorReporting.RuntimeInfo()}"); + Log.Info("Begin PowerToys Run startup ----------------------------------------------------", GetType()); + Log.Info($"Runtime info:{ErrorReporting.RuntimeInfo()}", GetType()); + RegisterAppDomainExceptions(); RegisterDispatcherUnhandledException(); @@ -118,7 +119,7 @@ namespace PowerLauncher _mainVM.MainWindowVisibility = Visibility.Visible; _mainVM.ColdStartFix(); _themeManager.ThemeChanged += OnThemeChanged; - Log.Info("|App.OnStartup|End PowerToys Run startup ---------------------------------------------------- "); + Log.Info("End PowerToys Run startup ---------------------------------------------------- ", GetType()); bootTime.Stop(); @@ -178,7 +179,7 @@ namespace PowerLauncher { Stopwatch.Normal("|App.OnExit|Exit cost", () => { - Log.Info("|App.OnExit| Start PowerToys Run Exit---------------------------------------------------- "); + Log.Info("Start PowerToys Run Exit---------------------------------------------------- ", GetType()); if (disposing) { if (_themeManager != null) @@ -198,7 +199,7 @@ namespace PowerLauncher // TODO: free unmanaged resources (unmanaged objects) and override finalizer // TODO: set large fields to null _disposed = true; - Log.Info("|App.OnExit| End PowerToys Run Exit ---------------------------------------------------- "); + Log.Info("End PowerToys Run Exit ---------------------------------------------------- ", GetType()); }); } } diff --git a/src/modules/launcher/PowerLauncher/MainWindow.xaml.cs b/src/modules/launcher/PowerLauncher/MainWindow.xaml.cs index a97cb6a4d8..74217db0bc 100644 --- a/src/modules/launcher/PowerLauncher/MainWindow.xaml.cs +++ b/src/modules/launcher/PowerLauncher/MainWindow.xaml.cs @@ -313,7 +313,7 @@ namespace PowerLauncher // Hence, there can be a situation where the element index that we want to scroll into view is out of range for it's parent control. // To mitigate this we use the UpdateLayout function, which forces layout update to ensure that the parent element contains the latest properties. // However, it has a performance impact and is therefore not called each time. - Log.Exception("MainWindow", "The parent element layout is not updated yet", ex, "SuggestionsList_SelectionChanged"); + Log.Exception("The parent element layout is not updated yet", ex, GetType()); listview.UpdateLayout(); listview.ScrollIntoView(e.AddedItems[0]); } diff --git a/src/modules/launcher/PowerLauncher/SettingsWatcher.cs b/src/modules/launcher/PowerLauncher/SettingsWatcher.cs index 1c1c318c64..347fe9ed10 100644 --- a/src/modules/launcher/PowerLauncher/SettingsWatcher.cs +++ b/src/modules/launcher/PowerLauncher/SettingsWatcher.cs @@ -44,7 +44,7 @@ namespace PowerLauncher { if (!_settingsUtils.SettingsExists(PowerLauncherSettings.ModuleName)) { - Log.Info("|SettingsWatcher.OverloadSettings|PT Run settings.json was missing, creating a new one"); + Log.Info("PT Run settings.json was missing, creating a new one", GetType()); var defaultSettings = new PowerLauncherSettings(); defaultSettings.Save(_settingsUtils); @@ -110,7 +110,7 @@ namespace PowerLauncher if (retryCount > MaxRetries) { retry = false; - Log.Exception($"|SettingsWatcher.OverloadSettings| Failed to Deserialize PowerToys settings, Retrying {e.Message}", e); + Log.Exception($"Failed to Deserialize PowerToys settings, Retrying {e.Message}", e, GetType()); } else { @@ -122,7 +122,7 @@ namespace PowerLauncher if (retryCount > MaxRetries) { retry = false; - Log.Exception($"|SettingsWatcher.OverloadSettings| Failed to Deserialize PowerToys settings, Creating new settings as file could be corrupted {e.Message}", e); + Log.Exception($"Failed to Deserialize PowerToys settings, Creating new settings as file could be corrupted {e.Message}", e, GetType()); // Settings.json could possibly be corrupted. To mitigate this we delete the // current file and replace it with a correct json value. diff --git a/src/modules/launcher/PowerLauncher/ViewModel/ResultViewModel.cs b/src/modules/launcher/PowerLauncher/ViewModel/ResultViewModel.cs index e07717a2c5..ba2e323dec 100644 --- a/src/modules/launcher/PowerLauncher/ViewModel/ResultViewModel.cs +++ b/src/modules/launcher/PowerLauncher/ViewModel/ResultViewModel.cs @@ -189,7 +189,7 @@ namespace PowerLauncher.ViewModel catch (Exception e) #pragma warning restore CA1031 // Do not catch general exception types { - Log.Exception($"|ResultViewModel.Image|IcoPath is empty and exception when calling Icon() for result <{Result.Title}> of plugin <{Result.PluginDirectory}>", e); + Log.Exception($"IcoPath is empty and exception when calling Icon() for result <{Result.Title}> of plugin <{Result.PluginDirectory}>", e, GetType()); imagePath = ImageLoader.ErrorIconPath; } } diff --git a/src/modules/launcher/Wox.Core/Plugin/JsonRPCPlugin.cs b/src/modules/launcher/Wox.Core/Plugin/JsonRPCPlugin.cs index 152e501203..ae0512eea1 100644 --- a/src/modules/launcher/Wox.Core/Plugin/JsonRPCPlugin.cs +++ b/src/modules/launcher/Wox.Core/Plugin/JsonRPCPlugin.cs @@ -43,7 +43,7 @@ namespace Wox.Core.Plugin } catch (Exception e) { - Log.Exception($"|JsonRPCPlugin.Query|Exception when query <{query}>", e); + Log.Exception($"Exception when query <{query}>", e, GetType()); return null; } } @@ -61,7 +61,7 @@ namespace Wox.Core.Plugin } catch (Exception e) { - Log.Exception($"|JsonRPCPlugin.LoadContextMenus| THIS IS A BUG - Exception on result <{selectedResult}>", e); + Log.Exception($"THIS IS A BUG - Exception on result <{selectedResult}>", e, GetType()); return null; } } @@ -179,12 +179,14 @@ namespace Wox.Core.Plugin var error = standardError.ReadToEnd(); if (!string.IsNullOrEmpty(error)) { - Log.Error($"|JsonRPCPlugin.Execute|{error}"); + Log.Error(error, GetType()); + return string.Empty; } else { - Log.Error("|JsonRPCPlugin.Execute|Empty standard output and standard error."); + Log.Error("Empty standard output and standard error.", GetType()); + return string.Empty; } } @@ -192,6 +194,7 @@ namespace Wox.Core.Plugin else if (result.StartsWith("DEBUG:")) { MessageBox.Show(new Form { TopMost = true }, result.Substring(6)); + return string.Empty; } else @@ -202,14 +205,16 @@ namespace Wox.Core.Plugin } else { - Log.Error("|JsonRPCPlugin.Execute|Can't start new process"); + Log.Error("Can't start new process", GetType()); + return string.Empty; } } } catch (Exception e) { - Log.Exception($"|JsonRPCPlugin.Execute|Exception for filename <{startInfo.FileName}> with argument <{startInfo.Arguments}>", e); + Log.Exception($"Exception for filename <{startInfo.FileName}> with argument <{startInfo.Arguments}>", e, GetType()); + return string.Empty; } } diff --git a/src/modules/launcher/Wox.Core/Plugin/PluginConfig.cs b/src/modules/launcher/Wox.Core/Plugin/PluginConfig.cs index 9f86fe0a7b..0727fae26e 100644 --- a/src/modules/launcher/Wox.Core/Plugin/PluginConfig.cs +++ b/src/modules/launcher/Wox.Core/Plugin/PluginConfig.cs @@ -6,6 +6,7 @@ using System; using System.Collections.Generic; using System.IO; using System.Linq; +using System.Reflection; using Newtonsoft.Json; using Wox.Infrastructure.Logger; using Wox.Plugin; @@ -27,6 +28,7 @@ namespace Wox.Core.Plugin PluginMetadatas.Clear(); var directories = pluginDirectories.SelectMany(Directory.GetDirectories); ParsePluginConfigs(directories); + return PluginMetadatas; } @@ -43,7 +45,7 @@ namespace Wox.Core.Plugin } catch (Exception e) { - Log.Exception($"|PluginConfig.ParsePLuginConfigs|Can't delete <{directory}>", e); + Log.Exception($"Can't delete <{directory}>", e, MethodBase.GetCurrentMethod().DeclaringType); } } else @@ -62,7 +64,8 @@ namespace Wox.Core.Plugin string configPath = Path.Combine(pluginDirectory, PluginConfigName); if (!File.Exists(configPath)) { - Log.Error($"|PluginConfig.GetPluginMetadata|Didn't find config file <{configPath}>"); + Log.Error($"Didn't find config file <{configPath}>", MethodBase.GetCurrentMethod().DeclaringType); + return null; } @@ -80,19 +83,19 @@ namespace Wox.Core.Plugin } catch (Exception e) { - Log.Exception($"|PluginConfig.GetPluginMetadata|invalid json for config <{configPath}>", e); + Log.Exception($"|PluginConfig.GetPluginMetadata|invalid json for config <{configPath}>", e, MethodBase.GetCurrentMethod().DeclaringType); return null; } if (!AllowedLanguage.IsAllowed(metadata.Language)) { - Log.Error($"|PluginConfig.GetPluginMetadata|Invalid language <{metadata.Language}> for config <{configPath}>"); + Log.Error($"|PluginConfig.GetPluginMetadata|Invalid language <{metadata.Language}> for config <{configPath}>", MethodBase.GetCurrentMethod().DeclaringType); return null; } if (!File.Exists(metadata.ExecuteFilePath)) { - Log.Error($"|PluginConfig.GetPluginMetadata|execute file path didn't exist <{metadata.ExecuteFilePath}> for config <{configPath}"); + Log.Error($"|PluginConfig.GetPluginMetadata|execute file path didn't exist <{metadata.ExecuteFilePath}> for config <{configPath}", MethodBase.GetCurrentMethod().DeclaringType); return null; } diff --git a/src/modules/launcher/Wox.Core/Plugin/PluginManager.cs b/src/modules/launcher/Wox.Core/Plugin/PluginManager.cs index 1e1d8a446e..06cae61259 100644 --- a/src/modules/launcher/Wox.Core/Plugin/PluginManager.cs +++ b/src/modules/launcher/Wox.Core/Plugin/PluginManager.cs @@ -7,6 +7,7 @@ using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Linq; +using System.Reflection; using System.Threading.Tasks; using Wox.Infrastructure; using Wox.Infrastructure.Logger; @@ -103,11 +104,11 @@ namespace Wox.Core.Plugin }); }); pair.Metadata.InitTime += milliseconds; - Log.Info($"|PluginManager.InitializePlugins|Total init cost for <{pair.Metadata.Name}> is <{pair.Metadata.InitTime}ms>"); + Log.Info($"Total init cost for <{pair.Metadata.Name}> is <{pair.Metadata.InitTime}ms>", MethodBase.GetCurrentMethod().DeclaringType); } catch (Exception e) { - Log.Exception(nameof(PluginManager), $"Fail to Init plugin: {pair.Metadata.Name}", e); + Log.Exception($"Fail to Init plugin: {pair.Metadata.Name}", e, MethodBase.GetCurrentMethod().DeclaringType); pair.Metadata.Disabled = true; failedPlugins.Enqueue(pair); } @@ -175,13 +176,16 @@ namespace Wox.Core.Plugin UpdateResultWithActionKeyword(results, query); } }); + metadata.QueryCount += 1; metadata.AvgQueryTime = metadata.QueryCount == 1 ? milliseconds : (metadata.AvgQueryTime + milliseconds) / 2; + return results; } catch (Exception e) { - Log.Exception($"|PluginManager.QueryForPlugin|Exception for plugin <{pair.Metadata.Name}> when query <{query}>", e); + Log.Exception($"Exception for plugin <{pair.Metadata.Name}> when query <{query}>", e, MethodBase.GetCurrentMethod().DeclaringType); + return new List(); } } @@ -245,11 +249,13 @@ namespace Wox.Core.Plugin try { var results = plugin.LoadContextMenus(result); + return results; } catch (Exception e) { - Log.Exception($"|PluginManager.GetContextMenusForPlugin|Can't load context menus for plugin <{metadata.Name}>", e); + Log.Exception($"Can't load context menus for plugin <{metadata.Name}>", e, MethodBase.GetCurrentMethod().DeclaringType); + return new List(); } } diff --git a/src/modules/launcher/Wox.Core/Plugin/PluginsLoader.cs b/src/modules/launcher/Wox.Core/Plugin/PluginsLoader.cs index 0f1550b3c0..35456e480d 100644 --- a/src/modules/launcher/Wox.Core/Plugin/PluginsLoader.cs +++ b/src/modules/launcher/Wox.Core/Plugin/PluginsLoader.cs @@ -47,7 +47,7 @@ namespace Wox.Core.Plugin } catch (Exception e) { - Infrastructure.Logger.Log.Exception($"|PluginsLoader.CSharpPlugins|Couldn't load assembly for {metadata.Name}", e); + Infrastructure.Logger.Log.Exception($"Couldn't load assembly for {metadata.Name}", e, MethodBase.GetCurrentMethod().DeclaringType); return; } @@ -59,7 +59,7 @@ namespace Wox.Core.Plugin } catch (InvalidOperationException e) { - Infrastructure.Logger.Log.Exception($"|PluginsLoader.CSharpPlugins|Can't find class implement IPlugin for <{metadata.Name}>", e); + Infrastructure.Logger.Log.Exception($"Can't find class implement IPlugin for <{metadata.Name}>", e, MethodBase.GetCurrentMethod().DeclaringType); return; } @@ -70,7 +70,7 @@ namespace Wox.Core.Plugin } catch (Exception e) { - Infrastructure.Logger.Log.Exception($"|PluginsLoader.CSharpPlugins|Can't create instance for <{metadata.Name}>", e); + Infrastructure.Logger.Log.Exception($"Can't create instance for <{metadata.Name}>", e, MethodBase.GetCurrentMethod().DeclaringType); return; } #endif @@ -96,6 +96,7 @@ namespace Wox.Core.Plugin Plugin = new ExecutablePlugin(metadata.ExecuteFilePath), Metadata = metadata, }); + return plugins; } } diff --git a/src/modules/launcher/Wox.Infrastructure/Alphabet.cs b/src/modules/launcher/Wox.Infrastructure/Alphabet.cs index ba057eb373..5aa8768945 100644 --- a/src/modules/launcher/Wox.Infrastructure/Alphabet.cs +++ b/src/modules/launcher/Wox.Infrastructure/Alphabet.cs @@ -41,7 +41,7 @@ namespace Wox.Infrastructure // force pinyin library static constructor initialize PinyinHelper.toHanyuPinyinStringArray('T', _pinyinFormat); }); - Log.Info($"|Wox.Infrastructure.Alphabet.Initialize|Number of preload pinyin combination<{_pinyinCache.Count}>"); + Log.Info($"Number of preload pinyin combination<{_pinyinCache.Count}>", GetType()); } public string Translate(string str) diff --git a/src/modules/launcher/Wox.Infrastructure/FileSystemHelper/FileWrapper.cs b/src/modules/launcher/Wox.Infrastructure/FileSystemHelper/FileWrapper.cs index 244a8a77e7..b5bf644740 100644 --- a/src/modules/launcher/Wox.Infrastructure/FileSystemHelper/FileWrapper.cs +++ b/src/modules/launcher/Wox.Infrastructure/FileSystemHelper/FileWrapper.cs @@ -21,7 +21,8 @@ namespace Wox.Infrastructure.FileSystemHelper } catch (IOException ex) { - Log.Info($"File {path} is being accessed by another process| {ex.Message}"); + Log.Info($"File {path} is being accessed by another process| {ex.Message}", GetType()); + return new string[] { string.Empty }; } } diff --git a/src/modules/launcher/Wox.Infrastructure/Helper.cs b/src/modules/launcher/Wox.Infrastructure/Helper.cs index 9da3e31b75..6b5f839521 100644 --- a/src/modules/launcher/Wox.Infrastructure/Helper.cs +++ b/src/modules/launcher/Wox.Infrastructure/Helper.cs @@ -5,6 +5,7 @@ using System; using System.Diagnostics; using System.IO; +using System.Reflection; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Wox.Infrastructure.Logger; @@ -95,7 +96,7 @@ namespace Wox.Infrastructure } catch (System.Exception ex) { - Log.Exception($"Wox.Infrastructure.Helper| Unable to Run {path} as admin : {ex.Message}", ex); + Log.Exception($"Unable to Run {path} as admin : {ex.Message}", ex, MethodBase.GetCurrentMethod().DeclaringType); } } diff --git a/src/modules/launcher/Wox.Infrastructure/Http/Http.cs b/src/modules/launcher/Wox.Infrastructure/Http/Http.cs index cdff6125d0..1fdac292c9 100644 --- a/src/modules/launcher/Wox.Infrastructure/Http/Http.cs +++ b/src/modules/launcher/Wox.Infrastructure/Http/Http.cs @@ -5,6 +5,7 @@ using System.IO; using System.Net; using System.Net.Http; +using System.Reflection; using System.Text; using System.Threading.Tasks; using JetBrains.Annotations; @@ -61,7 +62,8 @@ namespace Wox.Infrastructure.Http public static async Task Get([NotNull] string url, string encoding = "UTF-8") { - Log.Debug($"|Http.Get|Url <{url}>"); + Log.Debug($"Url <{url}>", MethodBase.GetCurrentMethod().DeclaringType); + var request = WebRequest.CreateHttp(url); request.Method = "GET"; request.Timeout = 1000; diff --git a/src/modules/launcher/Wox.Infrastructure/Image/ImageLoader.cs b/src/modules/launcher/Wox.Infrastructure/Image/ImageLoader.cs index 9988745a51..8a4d47ca5d 100644 --- a/src/modules/launcher/Wox.Infrastructure/Image/ImageLoader.cs +++ b/src/modules/launcher/Wox.Infrastructure/Image/ImageLoader.cs @@ -7,6 +7,7 @@ using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Linq; +using System.Reflection; using System.Threading.Tasks; using System.Windows.Media; using System.Windows.Media.Imaging; @@ -62,7 +63,8 @@ namespace Wox.Infrastructure.Image Load(x.Key); }); }); - Log.Info($"|ImageLoader.Initialize|Number of preload images is <{ImageCache.Usage.Count}>, Images Number: {ImageCache.CacheSize()}, Unique Items {ImageCache.UniqueImagesInCache()}"); + + Log.Info($"Number of preload images is <{ImageCache.Usage.Count}>, Images Number: {ImageCache.CacheSize()}, Unique Items {ImageCache.UniqueImagesInCache()}", MethodBase.GetCurrentMethod().DeclaringType); }); } @@ -188,7 +190,7 @@ namespace Wox.Infrastructure.Image } catch (System.Exception e) { - Log.Exception($"|ImageLoader.Load|Failed to get thumbnail for {path}", e); + Log.Exception($"Failed to get thumbnail for {path}", e, MethodBase.GetCurrentMethod().DeclaringType); type = ImageType.Error; image = ImageCache[ErrorIconPath]; ImageCache[path] = image; diff --git a/src/modules/launcher/Wox.Infrastructure/Logger/Log.cs b/src/modules/launcher/Wox.Infrastructure/Logger/Log.cs index 15cc2ff62a..ba97966bad 100644 --- a/src/modules/launcher/Wox.Infrastructure/Logger/Log.cs +++ b/src/modules/launcher/Wox.Infrastructure/Logger/Log.cs @@ -2,6 +2,7 @@ // The Microsoft Corporation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System; using System.IO; using System.Runtime.CompilerServices; using NLog; @@ -37,67 +38,25 @@ namespace Wox.Infrastructure.Logger LogManager.Configuration = configuration; } - private static void LogFaultyFormat(string message) + private static void LogInternalException(string message, System.Exception e, Type fullClassName, [CallerMemberName] string methodName = "", [CallerFilePath] string sourceFilePath = "", [CallerLineNumber] int sourceLineNumber = 0) { - var logger = LogManager.GetLogger("FaultyLogger"); - message = $"Wrong logger message format <{message}>"; - System.Diagnostics.Debug.WriteLine($"FATAL|{message}"); - logger.Fatal(message); - } + var logger = GetLogger(fullClassName.FullName, methodName); - private static bool FormatValid(string message) - { - var parts = message.Split('|'); - var valid = parts.Length == 3 && !string.IsNullOrWhiteSpace(parts[1]) && !string.IsNullOrWhiteSpace(parts[2]); - return valid; - } - - [MethodImpl(MethodImplOptions.Synchronized)] - public static void Exception(string className, string message, System.Exception exception, [CallerMemberName] string methodName = "") - { - var classNameWithMethod = CheckClassAndMessageAndReturnFullClassWithMethod(className, message, methodName); - - ExceptionInternal(classNameWithMethod, message, exception); - } - - private static string CheckClassAndMessageAndReturnFullClassWithMethod(string className, string message, string methodName) - { - if (string.IsNullOrWhiteSpace(className)) - { - LogFaultyFormat($"Fail to specify a class name during logging of message: {message ?? "no message entered"}"); - } - - if (string.IsNullOrWhiteSpace(message)) - { - // todo: not sure we really need that - LogFaultyFormat($"Fail to specify a message during logging"); - } - - if (!string.IsNullOrWhiteSpace(methodName)) - { - return className + "." + methodName; - } - - return className; - } - - private static void ExceptionInternal(string classAndMethod, string message, System.Exception e) - { - var logger = LogManager.GetLogger(classAndMethod); - - System.Diagnostics.Debug.WriteLine($"ERROR|{message}"); + LogInternal(LogLevel.Error, message, fullClassName, logger, methodName, sourceFilePath, sourceLineNumber); logger.Error("-------------------------- Begin exception --------------------------"); - logger.Error(message); + logger.Error($"\n\tMessage:\n\t {message}"); do { - logger.Error($"Exception full name:\n <{e.GetType().FullName}>"); - logger.Error($"Exception message:\n <{e.Message}>"); - logger.Error($"Exception stack trace:\n <{e.StackTrace}>"); - logger.Error($"Exception source:\n <{e.Source}>"); - logger.Error($"Exception target site:\n <{e.TargetSite}>"); - logger.Error($"Exception HResult:\n <{e.HResult}>"); + logger.Error( + $"\n\tException full name:\n\t <{e.GetType().FullName}>" + + $"\n\tException message:\n\t <{e.Message}>" + + $"\n\tException stack trace:\n\t <{e.StackTrace}>" + + $"\n\tException source:\n\t <{e.Source}>" + + $"\n\tException target site:\n\t <{e.TargetSite}>" + + $"\n\tException HResult:\n\t <{e.HResult}>"); + e = e.InnerException; } while (e != null); @@ -105,93 +64,53 @@ namespace Wox.Infrastructure.Logger logger.Error("-------------------------- End exception --------------------------"); } - private static void LogInternal(string message, LogLevel level) + public static void Info(string message, Type fullClassName, [CallerMemberName] string methodName = "", [CallerFilePath] string sourceFilePath = "", [CallerLineNumber] int sourceLineNumber = 0) { - if (FormatValid(message)) - { - var parts = message.Split('|'); - var prefix = parts[1]; - var unprefixed = parts[2]; - var logger = LogManager.GetLogger(prefix); - - System.Diagnostics.Debug.WriteLine($"{level.Name}|{message}"); - logger.Log(level, unprefixed); - } - else - { - LogFaultyFormat(message); - } + LogInternal(LogLevel.Info, message, fullClassName, methodName, sourceFilePath, sourceLineNumber); } - /// example: "|prefix|unprefixed" - [MethodImpl(MethodImplOptions.Synchronized)] - public static void Exception(string message, System.Exception e) + public static void Debug(string message, Type fullClassName, [CallerMemberName] string methodName = "", [CallerFilePath] string sourceFilePath = "", [CallerLineNumber] int sourceLineNumber = 0) { - if (FormatValid(message)) - { - var parts = message.Split('|'); - var prefix = parts[1]; - var unprefixed = parts[2]; - ExceptionInternal(prefix, unprefixed, e); - } - else - { - LogFaultyFormat(message); - } + LogInternal(LogLevel.Debug, message, fullClassName, methodName, sourceFilePath, sourceLineNumber); } - /// example: "|prefix|unprefixed" - public static void Error(string message) + public static void Warn(string message, Type fullClassName, [CallerMemberName] string methodName = "", [CallerFilePath] string sourceFilePath = "", [CallerLineNumber] int sourceLineNumber = 0) { - LogInternal(message, LogLevel.Error); + LogInternal(LogLevel.Warn, message, fullClassName, methodName, sourceFilePath, sourceLineNumber); } - public static void Error(string className, string message, [CallerMemberName] string methodName = "") + public static void Error(string message, Type fullClassName, [CallerMemberName] string methodName = "", [CallerFilePath] string sourceFilePath = "", [CallerLineNumber] int sourceLineNumber = 0) { - LogInternal(LogLevel.Error, className, message, methodName); + LogInternal(LogLevel.Error, message, fullClassName, methodName, sourceFilePath, sourceLineNumber); } - private static void LogInternal(LogLevel level, string className, string message, [CallerMemberName] string methodName = "") + public static void Exception(string message, System.Exception ex, Type fullClassName, [CallerMemberName] string methodName = "", [CallerFilePath] string sourceFilePath = "", [CallerLineNumber] int sourceLineNumber = 0) { - var classNameWithMethod = CheckClassAndMessageAndReturnFullClassWithMethod(className, message, methodName); - - var logger = LogManager.GetLogger(classNameWithMethod); - - System.Diagnostics.Debug.WriteLine($"{level.Name}|{message}"); - logger.Log(level, message); + LogInternalException(message, ex, fullClassName, methodName, sourceFilePath, sourceLineNumber); } - public static void Debug(string className, string message, [CallerMemberName] string methodName = "") + private static void LogInternal(LogLevel level, string message, Type fullClassName, [CallerMemberName] string methodName = "", [CallerFilePath] string sourceFilePath = "", [CallerLineNumber] int sourceLineNumber = 0) { - LogInternal(LogLevel.Debug, className, message, methodName); + var logger = GetLogger(fullClassName.FullName, methodName); + + LogInternal(level, message, fullClassName, logger, methodName, sourceFilePath, sourceLineNumber); } - /// example: "|prefix|unprefixed" - public static void Debug(string message) + private static void LogInternal(LogLevel level, string message, Type fullClassName, NLog.Logger logger, [CallerMemberName] string methodName = "", [CallerFilePath] string sourceFilePath = "", [CallerLineNumber] int sourceLineNumber = 0) { - LogInternal(message, LogLevel.Debug); + // System.Diagnostics.Debug.WriteLine($" {level.Name} | {message}"); + var msg = $"\n\tMessage: {message}" + + $"\n\tArea: {fullClassName}.{methodName}" + + $"\n\tSource Path: {sourceFilePath}::{sourceLineNumber}\n"; + + logger.Log(level, msg); } - public static void Info(string className, string message, [CallerMemberName] string methodName = "") + private static NLog.Logger GetLogger(string fullClassName, string methodName) { - LogInternal(LogLevel.Info, className, message, methodName); - } + var classNameWithMethod = $"{fullClassName}.{methodName}"; - /// example: "|prefix|unprefixed" - public static void Info(string message) - { - LogInternal(message, LogLevel.Info); - } - - public static void Warn(string className, string message, [CallerMemberName] string methodName = "") - { - LogInternal(LogLevel.Warn, className, message, methodName); - } - - /// example: "|prefix|unprefixed" - public static void Warn(string message) - { - LogInternal(message, LogLevel.Warn); + return LogManager.GetLogger(classNameWithMethod); } } } diff --git a/src/modules/launcher/Wox.Infrastructure/Stopwatch.cs b/src/modules/launcher/Wox.Infrastructure/Stopwatch.cs index f2cfe14f91..54e39b3b3c 100644 --- a/src/modules/launcher/Wox.Infrastructure/Stopwatch.cs +++ b/src/modules/launcher/Wox.Infrastructure/Stopwatch.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; +using System.Reflection; using Wox.Infrastructure.Logger; namespace Wox.Infrastructure @@ -24,7 +25,7 @@ namespace Wox.Infrastructure stopWatch.Stop(); var milliseconds = stopWatch.ElapsedMilliseconds; string info = $"{message} <{milliseconds}ms>"; - Log.Debug(info); + Log.Debug(info, MethodBase.GetCurrentMethod().DeclaringType); return milliseconds; } @@ -36,7 +37,7 @@ namespace Wox.Infrastructure stopWatch.Stop(); var milliseconds = stopWatch.ElapsedMilliseconds; string info = $"{message} <{milliseconds}ms>"; - Log.Info(info); + Log.Info(info, MethodBase.GetCurrentMethod().DeclaringType); return milliseconds; } @@ -65,7 +66,7 @@ namespace Wox.Infrastructure foreach (var key in Count.Keys) { string info = $"{key} already cost {Count[key]}ms"; - Log.Debug(info); + Log.Debug(info, MethodBase.GetCurrentMethod().DeclaringType); } } } diff --git a/src/modules/launcher/Wox.Infrastructure/Storage/BinaryStorage`1.cs b/src/modules/launcher/Wox.Infrastructure/Storage/BinaryStorage`1.cs index c79dabcbf2..62dce38403 100644 --- a/src/modules/launcher/Wox.Infrastructure/Storage/BinaryStorage`1.cs +++ b/src/modules/launcher/Wox.Infrastructure/Storage/BinaryStorage`1.cs @@ -44,7 +44,8 @@ namespace Wox.Infrastructure.Storage if (File.Exists(FilePath)) { File.Delete(FilePath); - Log.Info($"|BinaryStorage.TryLoad|Deleting cached data at <{FilePath}>"); + + Log.Info($"Deleting cached data at <{FilePath}>", GetType()); } } @@ -52,7 +53,8 @@ namespace Wox.Infrastructure.Storage { if (new FileInfo(FilePath).Length == 0) { - Log.Error($"|BinaryStorage.TryLoad|Zero length cache file <{FilePath}>"); + Log.Error($"Zero length cache file <{FilePath}>", GetType()); + Save(defaultData); return defaultData; } @@ -65,7 +67,8 @@ namespace Wox.Infrastructure.Storage } else { - Log.Info("|BinaryStorage.TryLoad|Cache file not exist, load default data"); + Log.Info("Cache file not exist, load default data", GetType()); + Save(defaultData); return defaultData; } @@ -87,7 +90,8 @@ namespace Wox.Infrastructure.Storage } catch (System.Exception e) { - Log.Exception($"|BinaryStorage.Deserialize|Deserialize error for file <{FilePath}>", e); + Log.Exception($"Deserialize error for file <{FilePath}>", e, GetType()); + return defaultData; } finally @@ -128,12 +132,12 @@ namespace Wox.Infrastructure.Storage } catch (SerializationException e) { - Log.Exception($"|BinaryStorage.Save|serialize error for file <{FilePath}>", e); + Log.Exception($"Serialize error for file <{FilePath}>", e, GetType()); } } _storageHelper.Close(); - Log.Info($"|BinaryStorage.Save|Saving cached data at <{FilePath}>"); + Log.Info($"Saving cached data at <{FilePath}>", GetType()); } } } diff --git a/src/modules/launcher/Wox.Infrastructure/Storage/JsonStorage`1.cs b/src/modules/launcher/Wox.Infrastructure/Storage/JsonStorage`1.cs index 2b22029dec..75eea78946 100644 --- a/src/modules/launcher/Wox.Infrastructure/Storage/JsonStorage`1.cs +++ b/src/modules/launcher/Wox.Infrastructure/Storage/JsonStorage`1.cs @@ -51,7 +51,7 @@ namespace Wox.Infrastructure.Storage if (File.Exists(FilePath)) { File.Delete(FilePath); - Log.Info($"|JsonStorage.TryLoad|Deleting cached data at <{FilePath}>"); + Log.Info($"Deleting cached data at <{FilePath}>", GetType()); } } @@ -84,7 +84,7 @@ namespace Wox.Infrastructure.Storage catch (JsonException e) { LoadDefault(); - Log.Exception($"|JsonStorage.Deserialize|Deserialize error for json <{FilePath}>", e); + Log.Exception($"Deserialize error for json <{FilePath}>", e, GetType()); } if (_data == null) @@ -123,11 +123,12 @@ namespace Wox.Infrastructure.Storage string serialized = JsonConvert.SerializeObject(_data, Formatting.Indented); File.WriteAllText(FilePath, serialized); _storageHelper.Close(); - Log.Info($"|JsonStorage.Save|Saving cached data at <{FilePath}>"); + + Log.Info($"Saving cached data at <{FilePath}>", GetType()); } catch (IOException e) { - Log.Error($"|JsonStorage.Save|Error in saving data at <{FilePath}>", e.Message); + Log.Exception($"Error in saving data at <{FilePath}>", e, GetType()); } } } diff --git a/src/modules/launcher/Wox.Infrastructure/Storage/ListRepository`1.cs b/src/modules/launcher/Wox.Infrastructure/Storage/ListRepository`1.cs index dd0759a907..ef86817a44 100644 --- a/src/modules/launcher/Wox.Infrastructure/Storage/ListRepository`1.cs +++ b/src/modules/launcher/Wox.Infrastructure/Storage/ListRepository`1.cs @@ -38,7 +38,7 @@ namespace Wox.Infrastructure.Storage } catch (ArgumentException e) { - Log.Info($"|LisRepository.Set| Trying to insert a duplicate item", e.Message); + Log.Info($"Trying to insert a duplicate item {e.Message}", GetType()); } } @@ -51,7 +51,7 @@ namespace Wox.Infrastructure.Storage { if (!_items.TryAdd(insertedItem.GetHashCode(), insertedItem)) { - Log.Error($"|ListRepository.Add| Item Already Exists <{insertedItem}>"); + Log.Error($"Item Already Exists <{insertedItem}>", GetType()); } } @@ -59,7 +59,7 @@ namespace Wox.Infrastructure.Storage { if (!_items.TryRemove(removedItem.GetHashCode(), out _)) { - Log.Error($"|ListRepository.Remove| Item Not Found <{removedItem}>"); + Log.Error($"Item Not Found <{removedItem}>", GetType()); } } diff --git a/src/modules/launcher/Wox.Infrastructure/UserSettings/Settings.cs b/src/modules/launcher/Wox.Infrastructure/UserSettings/Settings.cs index 2d901d95e6..6bdcb53e81 100644 --- a/src/modules/launcher/Wox.Infrastructure/UserSettings/Settings.cs +++ b/src/modules/launcher/Wox.Infrastructure/UserSettings/Settings.cs @@ -89,7 +89,7 @@ namespace Wox.Infrastructure.UserSettings } catch (ArgumentException e) { - Logger.Log.Exception(nameof(Settings), "Failed to load QuerySearchPrecisionString value from Settings file", e); + Logger.Log.Exception("Failed to load QuerySearchPrecisionString value from Settings file", e, GetType()); QuerySearchPrecision = StringMatcher.SearchPrecisionScore.Regular; StringMatcher.Instance.UserSettingSearchPrecision = StringMatcher.SearchPrecisionScore.Regular;