Skip to content

Commit

Permalink
Improve logging for PT Run (#6800)
Browse files Browse the repository at this point in the history
* init code pass

* adjusting tabbing for readabilty

* few small adjustments
  • Loading branch information
crutkas committed Sep 23, 2020
1 parent dafc1e0 commit b071220
Show file tree
Hide file tree
Showing 35 changed files with 184 additions and 287 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ public List<Result> Query(Query query)
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<Result>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ public List<ContextMenuResult> LoadContextMenus(Result selectedResult)
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;
}
Expand Down Expand Up @@ -87,7 +87,8 @@ public List<ContextMenuResult> LoadContextMenus(Result selectedResult)
}
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;
}
},
Expand Down Expand Up @@ -117,20 +118,16 @@ private ContextMenuResult CreateOpenContainingFolderResult(SearchResult record)
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;
}
return true;
},
};
}

public static void LogException(string message, Exception e)
{
Log.Exception($"|Microsoft.Plugin.Folder.ContextMenu|{message}", e);
}
}

public enum ResultType
Expand Down
3 changes: 2 additions & 1 deletion src/modules/launcher/Plugins/Microsoft.Plugin.Folder/Main.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
Expand Down Expand Up @@ -120,7 +121,7 @@ private static bool OpenFileOrFolder(string program, string path)
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);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,8 @@ public List<ContextMenuResult> LoadContextMenus(Result selectedResult)
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;
}
Expand Down Expand Up @@ -105,7 +106,7 @@ public List<ContextMenuResult> LoadContextMenus(Result selectedResult)
}
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;
}
},
Expand Down Expand Up @@ -136,7 +137,7 @@ private static ContextMenuResult CreateRunAsAdminContextMenu(SearchResult record
}
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;
}
},
Expand Down Expand Up @@ -178,7 +179,8 @@ private ContextMenuResult CreateOpenContainingFolderResult(SearchResult record)
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;
}
Expand All @@ -187,10 +189,5 @@ private ContextMenuResult CreateOpenContainingFolderResult(SearchResult record)
},
};
}

public static void LogException(string message, Exception e)
{
Log.Exception($"|Microsoft.Plugin.Folder.ContextMenu|{message}", e);
}
}
}
4 changes: 2 additions & 2 deletions src/modules/launcher/Plugins/Microsoft.Plugin.Indexer/Main.cs
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ public List<Result> Query(Query query, bool isFullQuery)
}
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;
Expand Down Expand Up @@ -163,7 +163,7 @@ public List<Result> Query(Query query, bool isFullQuery)
}
catch (Exception ex)
{
Log.Info(ex.ToString());
Log.Exception("Something failed", ex, GetType());
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,51 +22,29 @@ internal static class ProgramLogger
/// Logs an exception
/// </summary>
[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);
}

/// <summary>
/// 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
/// </summary>
[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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

using System;
using System.IO;
using System.Reflection;
using Microsoft.Plugin.Program.Logger;
using Package = Windows.ApplicationModel.Package;

Expand Down Expand Up @@ -51,7 +52,7 @@ public static PackageWrapper GetWrapperFromPackage(Package package)
}
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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public IEnumerable<IPackage> FindPackagesForCurrentUser()
}
catch (Exception e)
{
Log.Error(nameof(PackageManagerWrapper), e.Message, nameof(FindPackagesForCurrentUser));
Log.Error(e.Message, GetType());
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ public string RetrieveTargetPath(string path)
}
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;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
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;
Expand Down Expand Up @@ -80,9 +81,7 @@ public void InitializeAppInfo(string installedLocation)
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<UWPApplication>().ToArray();
}
Expand All @@ -104,7 +103,7 @@ private static string[] XmlNamespaces(string path)
}
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<string>();
}
Expand All @@ -128,10 +127,7 @@ private void InitPackageVersion(string[] namespaces)
}
}

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;
}
Expand All @@ -153,9 +149,8 @@ public static UWPApplication[] All()
}
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<UWPApplication>();
}
Expand Down Expand Up @@ -190,7 +185,7 @@ private static IEnumerable<IPackage> CurrentUserPackages()
}
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;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ public List<ContextMenuResult> ContextMenus(IPublicAPI api)
}
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;
}
},
Expand Down Expand Up @@ -310,9 +310,8 @@ internal string ResourceFromPri(string packageFullName, string resourceReference
}
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;
}
}
Expand All @@ -325,7 +324,8 @@ internal string ResourceFromPri(string packageFullName, string resourceReference
// 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;
}
}
Expand Down Expand Up @@ -569,9 +569,7 @@ internal void LogoPathFromUri(string uri, Theme theme)
{
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);
}
}

Expand All @@ -589,6 +587,8 @@ public ImageSource Logo()
}
}

private const int _dpiScale100 = 96;

private ImageSource PlatedImage(BitmapImage image)
{
if (!string.IsNullOrEmpty(BackgroundColor))
Expand Down Expand Up @@ -630,21 +630,21 @@ private ImageSource PlatedImage(BitmapImage image)
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));
}
Expand Down Expand Up @@ -674,9 +674,7 @@ private BitmapImage ImageFromPath(string path)
}
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));
}
}
Expand Down

0 comments on commit b071220

Please sign in to comment.