Improve exception handling of existing ex

Added logger instances for DisplayMagicianShared
functions. Also added logger debug commands to
all exceptions with existing ex objects.
This commit is contained in:
Terry MacDonald 2021-02-07 14:42:17 +13:00
parent 7d3533fb2a
commit ba636414c0
12 changed files with 141 additions and 20 deletions

View File

@ -20,7 +20,7 @@ namespace DisplayMagician.GameLibraries
private string _steamGameExe; private string _steamGameExe;
private string _steamGameProcessName; private string _steamGameProcessName;
private string _steamGameIconPath; private string _steamGameIconPath;
//private static List<SteamGame> _allInstalledSteamGames = null; private static readonly NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
static SteamGame() static SteamGame()
{ {
@ -90,6 +90,7 @@ namespace DisplayMagician.GameLibraries
} }
catch (Exception ex) catch (Exception ex)
{ {
logger.Debug(ex, $"SteamGame/IsRunning: Accessing Process.MainModule caused exception. Trying GameUtils.GetMainModuleFilepath instead");
if (GameUtils.GetMainModuleFilepath(gameProcess.Id).StartsWith(_steamGameExePath)) if (GameUtils.GetMainModuleFilepath(gameProcess.Id).StartsWith(_steamGameExePath))
numGameProcesses++; numGameProcesses++;
} }

View File

@ -54,19 +54,19 @@ namespace DisplayMagician.GameLibraries
} }
catch (SecurityException ex) catch (SecurityException ex)
{ {
logger.Warn("The user does not have the permissions required to read the Steam registry key."); logger.Warn(ex,"The user does not have the permissions required to read the Steam registry key.");
} }
catch (ObjectDisposedException ex) catch (ObjectDisposedException ex)
{ {
logger.Warn("The Microsoft.Win32.RegistryKey is closed when trying to access theSteam registry key (closed keys cannot be accessed)."); logger.Warn(ex, "The Microsoft.Win32.RegistryKey is closed when trying to access theSteam registry key (closed keys cannot be accessed).");
} }
catch (IOException ex) catch (IOException ex)
{ {
logger.Warn("The Steam registry key has been marked for deletion so we cannot access the value during the SteamLibrary check."); logger.Warn(ex, "The Steam registry key has been marked for deletion so we cannot access the value during the SteamLibrary check.");
} }
catch (UnauthorizedAccessException ex) catch (UnauthorizedAccessException ex)
{ {
logger.Warn("The user does not have the necessary registry rights to check whether Steam is installed."); logger.Warn(ex, "The user does not have the necessary registry rights to check whether Steam is installed.");
} }
} }
#endregion #endregion

View File

@ -18,7 +18,7 @@ namespace DisplayMagician.GameLibraries
private string _uplayGameExe; private string _uplayGameExe;
private string _uplayGameProcessName; private string _uplayGameProcessName;
private string _uplayGameIconPath; private string _uplayGameIconPath;
//private static List<UplayGame> _allInstalledUplayGames = null; private static readonly NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
static UplayGame() static UplayGame()
{ {
@ -91,6 +91,9 @@ namespace DisplayMagician.GameLibraries
} }
catch (Exception ex) catch (Exception ex)
{ {
logger.Debug(ex, $"UplayGame/IsRunning: Accessing Process.MainModule caused exception. Trying GameUtils.GetMainModuleFilepath instead");
// If there is a race condition where MainModule isn't available, then we
// instead try the much slower GetMainModuleFilepath (which does the same thing)
if (GameUtils.GetMainModuleFilepath(gameProcess.Id).StartsWith(_uplayGameExePath)) if (GameUtils.GetMainModuleFilepath(gameProcess.Id).StartsWith(_uplayGameExePath))
numGameProcesses++; numGameProcesses++;
} }

View File

@ -59,19 +59,19 @@ namespace DisplayMagician.GameLibraries
} }
catch (SecurityException ex) catch (SecurityException ex)
{ {
logger.Warn("The user does not have the permissions required to read the Uplay InstallDir registry key."); logger.Warn(ex, "UplayLibrary/UplayLibrary: The user does not have the permissions required to read the Uplay InstallDir registry key.");
} }
catch(ObjectDisposedException ex) catch(ObjectDisposedException ex)
{ {
logger.Warn("The Microsoft.Win32.RegistryKey is closed when trying to access the Uplay InstallDir registry key (closed keys cannot be accessed)."); logger.Warn(ex, "UplayLibrary/UplayLibrary: The Microsoft.Win32.RegistryKey is closed when trying to access the Uplay InstallDir registry key (closed keys cannot be accessed).");
} }
catch (IOException ex) catch (IOException ex)
{ {
logger.Warn("The Uplay InstallDir registry key has been marked for deletion so we cannot access the value dueing the UplayLibrary check."); logger.Warn(ex, "UplayLibrary/UplayLibrary: The Uplay InstallDir registry key has been marked for deletion so we cannot access the value dueing the UplayLibrary check.");
} }
catch (UnauthorizedAccessException ex) catch (UnauthorizedAccessException ex)
{ {
logger.Warn("The user does not have the necessary registry rights to check whether Uplay is installed."); logger.Warn(ex, "UplayLibrary/UplayLibrary: The user does not have the necessary registry rights to check whether Uplay is installed.");
} }
} }
#endregion #endregion

View File

@ -62,9 +62,6 @@ namespace DisplayMagician
public class ShortcutItem : IComparable public class ShortcutItem : IComparable
{ {
//private static List<ShortcutItem> _allSavedShortcuts = new List<ShortcutItem>();
//private MultiIcon _shortcutIcon, _originalIcon = null;
//private string _savedShortcutIconCacheFilename = "";
private string _profileUuid = ""; private string _profileUuid = "";
private ProfileItem _profileToUse; private ProfileItem _profileToUse;
private string _uuid = ""; private string _uuid = "";
@ -102,6 +99,7 @@ namespace DisplayMagician
[JsonIgnore] [JsonIgnore]
public string _savedShortcutIconCacheFilename; public string _savedShortcutIconCacheFilename;
#pragma warning restore CS3008 // Identifier is not CLS-compliant #pragma warning restore CS3008 // Identifier is not CLS-compliant
private static readonly NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
public ShortcutItem() public ShortcutItem()
{ {
@ -2109,7 +2107,7 @@ namespace DisplayMagician
} }
catch (Exception ex) catch (Exception ex)
{ {
Console.WriteLine($"ShortcutItem/CreateShortcut exception (deleting old shortcut)"); logger.Warn(ex, $"ShortcutItem/CreateShortcut: Execption while creating desktop shortcut!");
// Clean up a failed attempt // Clean up a failed attempt
if (System.IO.File.Exists(shortcutFileName)) if (System.IO.File.Exists(shortcutFileName))

View File

@ -19,6 +19,7 @@ namespace DisplayMagician.UIForms
{ {
private bool disposed; private bool disposed;
private static readonly NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
/// <summary> /// <summary>
/// Initializes a new instance of the <see cref="FileSystemAdaptor"/> class. /// Initializes a new instance of the <see cref="FileSystemAdaptor"/> class.
@ -170,6 +171,7 @@ namespace DisplayMagician.UIForms
catch (Exception ex) catch (Exception ex)
{ {
// catch the System.Drawing.Image exception created while accessing the Size // catch the System.Drawing.Image exception created while accessing the Size
logger.Debug(ex, "ProfileAdaptor/GetDetails: System.Drawing.Image exception caused while trying to get the ProfileBitmap Size as an Integer.");
} }
} }
@ -187,6 +189,7 @@ namespace DisplayMagician.UIForms
catch (Exception ex) catch (Exception ex)
{ {
// catch the System.Drawing.Image exception created while accessing the Size // catch the System.Drawing.Image exception created while accessing the Size
logger.Debug(ex, "ProfileAdaptor/GetDetails: System.Drawing.Image exception caused while trying to get the ProfileBitmap Size as a Float.");
} }
} }
string name = profileToUse.Name; string name = profileToUse.Name;

View File

@ -17,6 +17,7 @@ namespace DisplayMagician.UIForms
{ {
private bool disposed; private bool disposed;
private static readonly NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
/// <summary> /// <summary>
/// Initializes a new instance of the <see cref="ShortcutAdaptor"/> class. /// Initializes a new instance of the <see cref="ShortcutAdaptor"/> class.
@ -145,7 +146,7 @@ namespace DisplayMagician.UIForms
catch (Exception ex) catch (Exception ex)
{ {
// catch the System.Drawing.Image exception created while accessing the Size // catch the System.Drawing.Image exception created while accessing the Size
mySize = new Size(256, 256); logger.Debug(ex, "ShortcutAdaptor/GetDetails: System.Drawing.Image exception caused while trying to get the ProfileBitmap Size as an Integer.");
} }
} }
@ -163,7 +164,7 @@ namespace DisplayMagician.UIForms
catch (Exception ex) catch (Exception ex)
{ {
// catch the System.Drawing.Image exception created while accessing the Size // catch the System.Drawing.Image exception created while accessing the Size
mySizeF = new SizeF(256, 256); logger.Debug(ex, "ShortcutAdaptor/GetDetails: System.Drawing.Image exception caused while trying to get the ProfileBitmap Size as a Float.");
} }
} }

View File

@ -7,7 +7,7 @@
<ProjectGuid>{1CACDA43-01C7-4CD4-BF6E-9421A29510FC}</ProjectGuid> <ProjectGuid>{1CACDA43-01C7-4CD4-BF6E-9421A29510FC}</ProjectGuid>
<OutputType>Library</OutputType> <OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder> <AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>DisplayMagician.Shared</RootNamespace> <RootNamespace>DisplayMagicianShared</RootNamespace>
<AssemblyName>DisplayMagician.Shared</AssemblyName> <AssemblyName>DisplayMagician.Shared</AssemblyName>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion> <TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment> <FileAlignment>512</FileAlignment>
@ -51,6 +51,7 @@
<Reference Include="System.Xml" /> <Reference Include="System.Xml" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Include="Logger.cs" />
<Compile Include="Properties\Resources.Designer.cs"> <Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen> <AutoGen>True</AutoGen>
<DesignTime>True</DesignTime> <DesignTime>True</DesignTime>
@ -112,6 +113,9 @@
<PackageReference Include="Newtonsoft.Json"> <PackageReference Include="Newtonsoft.Json">
<Version>12.0.3</Version> <Version>12.0.3</Version>
</PackageReference> </PackageReference>
<PackageReference Include="NLog">
<Version>4.7.7</Version>
</PackageReference>
<PackageReference Include="NvAPIWrapper.Net"> <PackageReference Include="NvAPIWrapper.Net">
<Version>0.7.2.63</Version> <Version>0.7.2.63</Version>
</PackageReference> </PackageReference>

View File

@ -0,0 +1,99 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace DisplayMagicianShared
{
class Logger
{
internal static string AppDataPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "DisplayMagician");
internal static string AppLogPath = Path.Combine(AppDataPath, $"Logs");
internal static string AppSettingsFile = Path.Combine(AppDataPath, $"Settings_1.0.json");
public static readonly NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
static Logger()
{
// Prepare NLog for logging
var config = new NLog.Config.LoggingConfiguration();
// Targets where to log to: File and Console
//string date = DateTime.Now.ToString("yyyyMMdd.HHmmss");
string AppLogFilename = Path.Combine(AppLogPath, $"DisplayMagicianShared.log");
// Create the Logging Dir if it doesn't exist so that it's avilable for all
// parts of the program to use
if (!Directory.Exists(AppLogPath))
{
try
{
Directory.CreateDirectory(AppLogPath);
}
catch (Exception ex)
{
Console.WriteLine($"Logger/Logger: Exception creating logging directory {AppLogPath} - {ex.Message}: {ex.StackTrace} - {ex.InnerException}");
}
}
var logfile = new NLog.Targets.FileTarget("logfile")
{
FileName = AppLogFilename
};
var logconsole = new NLog.Targets.ConsoleTarget("logconsole");
// Figure out what logging level we're at in the main app
// and set that up here
NLog.LogLevel logLevel = NLog.LogLevel.Info;
// Look for the LogLevel line and use that
// "LogLevel": "Warn"
if (File.Exists(AppLogFilename))
{
using (StreamReader sr = File.OpenText(AppLogFilename))
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
string pattern = @"\s?""LogLevel""\s?\:\s?""(Trace|Info|Warn|Error|Debug|Fatal)""";
MatchCollection matches = Regex.Matches(s, pattern);
switch (matches[1].Value)
{
case "Trace":
logLevel = NLog.LogLevel.Trace;
break;
case "Info":
logLevel = NLog.LogLevel.Info;
break;
case "Warn":
logLevel = NLog.LogLevel.Warn;
break;
case "Error":
logLevel = NLog.LogLevel.Error;
break;
case "Debug":
logLevel = NLog.LogLevel.Debug;
break;
default:
logLevel = NLog.LogLevel.Warn;
break;
}
break;
}
}
}
config.AddRule(NLog.LogLevel.Info, NLog.LogLevel.Fatal, logconsole);
config.AddRule(logLevel, NLog.LogLevel.Fatal, logfile);
// Apply config
NLog.LogManager.Configuration = config;
}
}
}

View File

@ -9,11 +9,13 @@ using Newtonsoft.Json;
using Newtonsoft.Json.Converters; using Newtonsoft.Json.Converters;
using NvAPIWrapper.Mosaic; using NvAPIWrapper.Mosaic;
using NvAPIWrapper.Native.Exceptions; using NvAPIWrapper.Native.Exceptions;
using DisplayMagicianShared;
namespace DisplayMagicianShared.NVIDIA namespace DisplayMagicianShared.NVIDIA
{ {
public class SurroundTopologyDisplay public class SurroundTopologyDisplay
{ {
public SurroundTopologyDisplay(GridTopologyDisplay display) public SurroundTopologyDisplay(GridTopologyDisplay display)
{ {
DisplayId = display.DisplayDevice.DisplayId; DisplayId = display.DisplayDevice.DisplayId;
@ -34,6 +36,7 @@ namespace DisplayMagicianShared.NVIDIA
catch (NVIDIAApiException ex) catch (NVIDIAApiException ex)
{ {
//Debug.WriteLine($"SurroundTopologyDisplay/NVIDIAApiException exception: {ex.Message}: {ex.StackTrace} - {ex.InnerException}"); //Debug.WriteLine($"SurroundTopologyDisplay/NVIDIAApiException exception: {ex.Message}: {ex.StackTrace} - {ex.InnerException}");
Logger.logger.Debug(ex, $"SurroundTopologyDisplay/NVIDIAApiException: Accessing NvAPIWRapper ReadEDDIDData caused exception. Setting generic DisplayID instead");
// If we hit here then we cannot find the DisplayName from the EDID Data from the GPU // If we hit here then we cannot find the DisplayName from the EDID Data from the GPU
// So we just make one up using the DisplayID // So we just make one up using the DisplayID
DisplayName = $"Display #{DisplayId}"; DisplayName = $"Display #{DisplayId}";

View File

@ -549,10 +549,13 @@ namespace DisplayMagicianShared
isNvidia = true; isNvidia = true;
} }
catch (Exception ex) catch (Exception ex)
{ } {
Logger.logger.Debug(ex, "ProfileRepository/GenerateProfileDisplayIdentifiers: Attemped to get GetPhysicalCPUs through NvAPIWrapper library but got exception.");
}
if (isNvidia && myPhysicalGPUs != null && myPhysicalGPUs.Length > 0) if (isNvidia && myPhysicalGPUs != null && myPhysicalGPUs.Length > 0)
{ {
Logger.logger.Debug("ProfileRepository/GenerateProfileDisplayIdentifiers: Was able to GetPhysicalCPUs through NvAPIWrapper library.");
foreach (NvAPIWrapper.GPU.PhysicalGPU myPhysicalGPU in myPhysicalGPUs) foreach (NvAPIWrapper.GPU.PhysicalGPU myPhysicalGPU in myPhysicalGPUs)
{ {
@ -683,7 +686,9 @@ namespace DisplayMagicianShared
isNvidia = true; isNvidia = true;
} }
catch (Exception ex) catch (Exception ex)
{ } {
Logger.logger.Debug(ex, "ProfileRepository/GenerateAllAvailableDisplayIdentifiers: Attemped to get GetPhysicalCPUs through NvAPIWrapper library but got exception.");
}
if (isNvidia && myPhysicalGPUs != null && myPhysicalGPUs.Length > 0) if (isNvidia && myPhysicalGPUs != null && myPhysicalGPUs.Length > 0)
{ {

View File

@ -23,6 +23,7 @@
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>
<UseVSHostingProcess>true</UseVSHostingProcess> <UseVSHostingProcess>true</UseVSHostingProcess>
<RegisterForComInterop>false</RegisterForComInterop> <RegisterForComInterop>false</RegisterForComInterop>
<CodeAnalysisRuleSet>DisplayMagicianShellExtension.ruleset</CodeAnalysisRuleSet>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType> <DebugType>pdbonly</DebugType>
@ -31,6 +32,8 @@
<DefineConstants>TRACE</DefineConstants> <DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport> <ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>
<CodeAnalysisRuleSet>DisplayMagicianShellExtension.ruleset</CodeAnalysisRuleSet>
<CodeAnalysisIgnoreGeneratedCode>true</CodeAnalysisIgnoreGeneratedCode>
</PropertyGroup> </PropertyGroup>
<PropertyGroup> <PropertyGroup>
<ApplicationIcon>Resources\DisplayMagician.ico</ApplicationIcon> <ApplicationIcon>Resources\DisplayMagician.ico</ApplicationIcon>
@ -88,6 +91,7 @@
<None Include="..\.editorconfig"> <None Include="..\.editorconfig">
<Link>.editorconfig</Link> <Link>.editorconfig</Link>
</None> </None>
<None Include="DisplayMagicianShellExtension.ruleset" />
<None Include="key.snk" /> <None Include="key.snk" />
<None Include="Resources\DisplayMagicianMenuImage.png" /> <None Include="Resources\DisplayMagicianMenuImage.png" />
</ItemGroup> </ItemGroup>