From 2776837637bf17a0975b91d7512f3d05267e52df Mon Sep 17 00:00:00 2001 From: "Beale, Michael" Date: Fri, 6 Feb 2026 17:01:11 -0800 Subject: [PATCH] Work in Progress on Logging Refactor. --- src/Applications/ACATApp/Program.cs | 7 +- .../ACATConfigNext/Forms/SettingsForm.cs | 11 +- .../UserControls/GroupedSettingsPanel.cs | 14 +- src/Applications/ACATTalk/Program.cs | 7 +- src/Applications/ACATWatch/ACATWatchForm.cs | 41 +++--- src/Applications/ACATWatch/Program.cs | 13 +- src/Applications/AppCommon/Onboarding.cs | 7 +- .../SampleActuator/SampleActuator.cs | 6 +- .../SampleActuator/SampleActuatorSwitch.cs | 3 +- .../UI/OnboardingWizard.cs | 7 +- .../UserControlHardwareSwitchSetup.cs | 14 +- .../UserControlHardwareSwitchTest.cs | 17 ++- .../UserControls/UserControlSwitchSelect.cs | 7 +- .../Dialogs/WindowMoveResizeScannerForm.cs | 10 +- .../Scanners/CursorNavigationScanner.cs | 10 +- .../Scanners/DashboardAppScanner.cs | 28 ++-- .../Scanners/TalkApplicationScanner.cs | 18 +-- .../Scanners/YesNoResponseScanner.cs | 12 +- .../Scanners/YesNoScanner.cs | 12 +- .../SentencePredictionUserControl.cs | 7 +- .../UserControls/PhrasesUserControlBCI.cs | 9 +- .../UserControls/TTSYesNoUserControlBCI.cs | 9 +- .../UserControls/TTSYesNoUserControlBCI2.cs | 9 +- .../EEGProcessing/Utilities/FileReader.cs | 12 +- .../BCI/Actuators/EEGUtilities/SerialComm.cs | 9 +- .../BCI/Actuators/gTec_SensorUI/SensorForm.cs | 20 +-- .../UserControlBCISignalCheck.cs | 18 ++- .../UserControlErrorBluetoothDisconnected.cs | 14 +- .../BCI/Actuators/gTec_SensorUI/Utils.cs | 5 +- .../gTec_SensorUI/gTecDeviceTester.cs | 29 ++-- .../openBCI_SensorUI/OpenBCIDeviceTester.cs | 3 + .../UserControlBCIErrorOpticalSensor.cs | 7 +- .../BCI/Actuators/openBCI_SensorUI/Utils.cs | 5 +- .../AnimationSharp/AnimationSharpManagerV2.cs | 92 ++++++------ .../Utility/AnimationManagerUtils.cs | 34 ++--- .../Common/AnimationSharp/Utility/BCIUtils.cs | 11 +- .../AnimationSharp/Utility/CachedLogBCI.cs | 7 +- .../AnimationSharp/Utility/SharpDXUtils.cs | 26 ++-- .../CalibrationEyesSettingsForm.cs | 17 ++- .../ConfirmBoxCalibrationModes.cs | 37 +++-- .../ConfirmBoxTriggerBoxSettings.cs | 11 +- .../BCIInterfaceUtilities/OtherTestForm.cs | 15 +- .../RemapCalibrationForm.cs | 21 ++- .../CameraActuator/CameraActuator.cs | 3 + .../CameraActuator/CameraActuatorSwitch.cs | 11 +- .../CameraActuator/ConfigureActuatorForm.cs | 21 +-- .../CameraActuator/VideoWindowFinder.cs | 11 +- .../WebcamGestureSelectUserControl.cs | 7 +- .../TalkApplicationScannerAgent.cs | 34 ++++- .../TalkApplicationTextControlAgent.cs | 11 +- .../LaunchAppAgent/LaunchAppAgent.cs | 16 ++- .../SwitchWindowsAgent/SwitchWindowsAgent.cs | 10 +- .../SwitchWindowsScanner.cs | 3 +- .../TTSEngines/SAPIEngine/SAPIEngine.cs | 42 +++--- .../Default/TTSEngines/TTSClient/TTSClient.cs | 36 ++--- .../TTSEngines/TTSClient/TransportHttp.cs | 10 +- .../ConvAssist/ConvAssistUtils.cs | 4 +- .../ConvAssist/ConvAssistWordPredictor.cs | 16 ++- .../ConvAssist/NamedPipeServerConvAssist.cs | 38 ++--- .../SentencePredictionsRequestHandler.cs | 15 +- .../WordPredictionsRequestHandler.cs | 20 +-- .../AbbreviationsManagement/Abbreviation.cs | 11 +- .../AbbreviationsManagement/Abbreviations.cs | 13 +- .../AbbreviationsManager.cs | 6 +- .../ActuatorManagement/ActuatorBase.cs | 6 +- .../ACATCore/ActuatorManagement/ActuatorEx.cs | 6 +- .../ActuatorManagement/ActuatorManager.cs | 10 +- .../ActuatorManagement/ActuatorSwitchBase.cs | 9 +- .../ACATCore/ActuatorManagement/Actuators.cs | 6 +- .../BaseActuators/KeyboardSwitch.cs | 14 +- .../UI/SwitchCommandMapForm.cs | 11 +- .../WinsockClientActuatorBase.cs | 29 ++-- .../WinsockActuators/WinsockCommon.cs | 15 +- .../ClientConnHandler.cs | 25 ++-- .../ACATCore/AgentManagement/AgentBase.cs | 13 +- .../ACATCore/AgentManagement/AgentUtils.cs | 16 ++- .../AgentManagement/GenericAppAgentBase.cs | 11 +- .../ACATCore/AgentManagement/Keyboard.cs | 19 ++- src/Libraries/ACATCore/Audit/AuditLog.cs | 9 +- .../PanelManagement/Common/ScannerCommon.cs | 33 +++-- .../PanelManagement/Common/TextController.cs | 59 ++++---- .../ACATCore/PanelManagement/PanelManager.cs | 19 ++- .../ACATCore/PanelManagement/PanelStack.cs | 29 ++-- .../SpellCheckManagement/SpellCheckManager.cs | 9 +- .../SpellCheckManagement/SpellCheckers.cs | 13 +- .../ACATCore/TTSManagement/TTSEngines.cs | 13 +- .../ACATCore/TTSManagement/TTSManager.cs | 9 +- .../UserControlCommon.cs | 50 ++++--- .../UserControlManager.cs | 57 ++++---- .../ACATCore/UserManagement/UserManager.cs | 6 +- .../Utility/AutomationEventManager.cs | 134 +++++++++--------- src/Libraries/ACATCore/Utility/CachedLog.cs | 8 +- .../ACATCore/Utility/DirectoryWalker.cs | 14 +- src/Libraries/ACATCore/Utility/EnumWindows.cs | 20 ++- src/Libraries/ACATCore/Utility/FileUtils.cs | 31 ++-- .../ACATCore/Utility/GlobalPreferences.cs | 8 +- src/Libraries/ACATCore/Utility/HtmlUtils.cs | 4 +- src/Libraries/ACATCore/Utility/ImageUtils.cs | 10 +- .../ACATCore/Utility/KeyStateTracker.cs | 2 + .../ACATCore/Utility/NamedPipe/PipeServer.cs | 10 +- .../ACATCore/Utility/ResourceUtils.cs | 12 +- .../ACATCore/Utility/SoundManager.cs | 10 +- src/Libraries/ACATCore/Utility/TextUtils.cs | 10 +- .../ACATCore/Utility/TypeLoader/TypeLoader.cs | 4 +- src/Libraries/ACATCore/Utility/Windows.cs | 57 ++++---- src/Libraries/ACATCore/Utility/XmlUtils.cs | 8 +- .../Layout/LayoutAttribute.cs | 27 ++-- .../Layout/WidgetAttribute.cs | 11 +- .../Layout/WidgetAttributes.cs | 17 ++- .../ACATCore/WidgetManagement/Widget.cs | 35 +++-- .../WidgetManagement/WidgetManager.cs | 33 +++-- .../ACATCore/Widgets/ButtonControlWidget.cs | 17 ++- .../ACATCore/Widgets/ButtonWidgetBase.cs | 12 +- .../ACATCore/Widgets/CheckBoxWidget.cs | 8 +- .../ACATCore/Widgets/CurrentWordWidget.cs | 12 +- src/Libraries/ACATCore/Widgets/ImageWidget.cs | 13 +- .../ACATCore/Widgets/ImageWidgetBase.cs | 12 +- src/Libraries/ACATCore/Widgets/LabelWidget.cs | 14 +- .../ACATCore/Widgets/LetterListItemWidget.cs | 8 +- .../ACATCore/Widgets/ScannerButtonBase.cs | 11 +- .../Widgets/SentenceListItemWidget.cs | 12 +- .../ACATCore/Widgets/SliderWidget.cs | 21 +-- .../ACATCore/Widgets/TabStopScannerButton.cs | 11 +- .../ACATCore/Widgets/TextBoxWidget.cs | 11 +- .../ACATCore/Widgets/WordListItemWidget.cs | 12 +- .../NullWordPredictor.cs | 9 +- .../WordPredictionManager.cs | 12 +- .../WordPredictorManagement/WordPredictors.cs | 23 +-- .../AppAgents/ACATApp/ACATAgentBase.cs | 8 +- .../DialogControlAgentBase.cs | 12 +- .../AppAgents/Outlook/OutlookAgentBase.cs | 32 +++-- .../WindowsExplorerAgentBase.cs | 28 ++-- .../AppWindowManagementHandler.cs | 17 ++- .../CommandHandlers/DocumentEditingHandler.cs | 11 +- .../CommandHandlers/FunctionKeyHandler.cs | 9 +- .../CommandHandlers/GoBackHandler.cs | 9 +- .../CommandHandlers/NavigationHandler.cs | 11 +- .../CommandHandlers/ShowDialogsHandler.cs | 9 +- .../ACATExtension/UI/AlphabetScannerCommon.cs | 46 +++--- src/Libraries/ACATExtension/UI/DialogUtils.cs | 22 ++- .../UI/HorizontalStripScanner.cs | 8 +- .../UI/ScannerForms/GenericScannerForm.cs | 23 +-- .../ACATExtension/UI/ScannerHelper.cs | 11 +- .../UI/UserControlWordPredictionCommon.cs | 73 +++++----- .../UI/UserControls/GenericUserControl.cs | 5 +- 145 files changed, 1595 insertions(+), 927 deletions(-) diff --git a/src/Applications/ACATApp/Program.cs b/src/Applications/ACATApp/Program.cs index 9b085d0a..fe08c339 100644 --- a/src/Applications/ACATApp/Program.cs +++ b/src/Applications/ACATApp/Program.cs @@ -22,6 +22,7 @@ using ACAT.Extension; using ACAT.Extension.CommandHandlers; using ACATResources; +using Microsoft.Extensions.Logging; using System; using System.Windows.Forms; using System.Windows.Navigation; @@ -36,6 +37,7 @@ internal static class Program { private static Splash splash = null; private static Microsoft.Extensions.Logging.ILoggerFactory modernLoggingFactory = null; + private static ILogger _logger; /// /// The main entry point for the application. @@ -102,8 +104,9 @@ private static void InitializeLogging() // Initialize modern logging infrastructure (ticket #3) modernLoggingFactory = LoggingConfiguration.CreateLoggerFactory(); + _logger = modernLoggingFactory.CreateLogger(typeof(Program)); - Log.Debug("ACAT Dashboard Application Launch"); + _logger.LogDebug("ACAT Dashboard Application Launch"); } private static void InitializeUser() @@ -210,7 +213,7 @@ private static void ShutdownApplication() Context.Dispose(); Common.Uninit(); CloseSplashScreen(); - Log.Debug("ACATTalk Application shutdown"); + _logger.LogDebug("ACATTalk Application shutdown"); Log.Close(); modernLoggingFactory?.Dispose(); AppCommon.OnExit(); diff --git a/src/Applications/ACATConfigNext/Forms/SettingsForm.cs b/src/Applications/ACATConfigNext/Forms/SettingsForm.cs index 7095803a..fc33658f 100644 --- a/src/Applications/ACATConfigNext/Forms/SettingsForm.cs +++ b/src/Applications/ACATConfigNext/Forms/SettingsForm.cs @@ -6,6 +6,7 @@ using ACAT.Core.WidgetManagement; using ACAT.Extension; using ACATConfigNext.UserControls; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.ComponentModel; @@ -18,6 +19,7 @@ namespace ACATConfigNext.Forms { public class SettingsForm : Form { + private readonly ILogger _logger; private TableLayoutPanel basePanel; private FlowLayoutPanel leftPanel; private TableLayoutPanel navPanel; @@ -40,8 +42,9 @@ public class SettingsForm : Form private bool _isDirty = false; - public SettingsForm() + public SettingsForm(ILogger logger) { + _logger = logger; WpfInitializationHelper.EnsureApplicationResources(); InitializeComponent(); @@ -183,7 +186,7 @@ private void ButtonClicked_Cancel(object sender, EventArgs e) } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, "An error occurred while canceling changes"); MessageBox.Show("An error occurred while canceling changes.", "Cancel Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } @@ -215,7 +218,7 @@ private void ButtonClicked_Exit(object sender, EventArgs e) } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, "An error occurred while exiting"); MessageBox.Show("An error occurred while saving settings.", "Save Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } @@ -401,7 +404,7 @@ private void CopyPreferencesValues(IPreferences source, IPreferences target) } catch (Exception ex) { - Log.Debug($"Could not copy property {prop.Name}: {ex.Message}"); + _logger.LogDebug("Could not copy property {PropertyName}: {Message}", prop.Name, ex.Message); } } } diff --git a/src/Applications/ACATConfigNext/UserControls/GroupedSettingsPanel.cs b/src/Applications/ACATConfigNext/UserControls/GroupedSettingsPanel.cs index 9bc88e68..f98c7794 100644 --- a/src/Applications/ACATConfigNext/UserControls/GroupedSettingsPanel.cs +++ b/src/Applications/ACATConfigNext/UserControls/GroupedSettingsPanel.cs @@ -1,5 +1,6 @@ using ACAT.Core.Utility; using ACAT.Core.Extensions; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Drawing; @@ -18,9 +19,11 @@ namespace ACATConfigNext.UserControls { internal class GroupedSettingsPanel : UserControl { + private readonly ILogger _logger; private TableLayoutPanel basePanel; - public GroupedSettingsPanel(Action showPanel, IEnumerable acat_extensions, PropertyChangedEventHandler settingsChangedHandler) + public GroupedSettingsPanel(Action showPanel, IEnumerable acat_extensions, PropertyChangedEventHandler settingsChangedHandler, ILogger logger = null) { + _logger = logger; basePanel = new TableLayoutPanel() { BackColor = Color.Transparent, @@ -153,7 +156,8 @@ private static void AddPanelClickEvent(Control control, Action { - Log.Debug("Clicked on control: " + control.Name); + var logger = LoggingConfiguration.CreateLogger(); + logger.LogDebug("Clicked on control: {ControlName}", control.Name); Control clickedControl = s as Control; while (clickedControl != null && clickedControl is not TableLayoutPanel) @@ -166,7 +170,7 @@ private static void AddPanelClickEvent(Control control, Action /// The main entry point for the application. @@ -91,8 +93,9 @@ public static void Main(string[] args) // Initialize modern logging infrastructure (ticket #3) var modernLoggingFactory = LoggingConfiguration.CreateLoggerFactory(); + _logger = modernLoggingFactory.CreateLogger(typeof(Program)); - Log.Debug("ACAT Talk Application Launch"); + _logger.LogDebug("ACAT Talk Application Launch"); AuditLog.Audit(new AuditEvent("Application", "start")); @@ -194,7 +197,7 @@ public static void Main(string[] args) splash?.Close(); splash = null; - Log.Debug("ACATTalk Application shutdown"); + _logger.LogDebug("ACATTalk Application shutdown"); Log.Close(); modernLoggingFactory?.Dispose(); diff --git a/src/Applications/ACATWatch/ACATWatchForm.cs b/src/Applications/ACATWatch/ACATWatchForm.cs index 88181a11..b8c1d461 100644 --- a/src/Applications/ACATWatch/ACATWatchForm.cs +++ b/src/Applications/ACATWatch/ACATWatchForm.cs @@ -16,6 +16,7 @@ using ACAT.Core.Utility; using ACAT.Core.Utility.NamedPipe; +using Microsoft.Extensions.Logging; using System; using System.ComponentModel; using System.Diagnostics; @@ -31,12 +32,14 @@ public partial class ACATWatchForm : Form { private static readonly int ASFW_ANY = -1; private static readonly uint LSFW_UNLOCK = 2; + private readonly ILogger _logger; private PipeServer _pipeServer; private NotifyIcon trayIcon; private readonly ContextMenu trayMenu; - public ACATWatchForm() + public ACATWatchForm(ILogger logger) { + _logger = logger; InitializeComponent(); Application.ApplicationExit += Application_ApplicationExit; @@ -1294,9 +1297,9 @@ public static void ForceWindowIntoForeground(IntPtr window) AllowSetForegroundWindow(ASFW_ANY); User32Interop.SetForegroundWindow(window); - Log.Debug("Calling BringWindowToTop"); + _logger.LogDebug("Calling BringWindowToTop"); User32Interop.BringWindowToTop(window); - Log.Debug("Calling ShowWindow"); + _logger.LogDebug("Calling ShowWindow"); User32Interop.ShowWindow(window.ToInt32(), User32Interop.SW_SHOW); SystemParametersInfo(SPI.SPI_SETFOREGROUNDLOCKTIMEOUT, 0, ref oldTimeout, 0); @@ -1311,36 +1314,36 @@ public void FocusWindow(IntPtr focusOnWindowHandle) { User32Interop.GetWindowLong(focusOnWindowHandle, User32Interop.GWL_STYLE); IntPtr fg = User32Interop.GetForegroundWindow(); - Log.Debug("Fg window handle: " + fg.ToInt32()); + _logger.LogDebug("Fg window handle: " + fg.ToInt32()); User32Interop.GetWindowThreadProcessId(User32Interop.GetForegroundWindow(), out uint h); - Log.Debug("Process id of fgwindow: " + h); + _logger.LogDebug("Process id of fgwindow: " + h); uint currentlyFocusedWindowProcessIdThread = User32Interop.GetWindowThreadProcessId(focusOnWindowHandle, out h); - Log.Debug("Process id of focusOnWindowHandle: " + h); + _logger.LogDebug("Process id of focusOnWindowHandle: " + h); uint appThread = Kernel32Interop.GetCurrentThreadId(); - Log.Debug("appthread: " + appThread); + _logger.LogDebug("appthread: " + appThread); if (currentlyFocusedWindowProcessIdThread != appThread) { - Log.Debug("currentlyFocusedWindowProcessId != appThread"); + _logger.LogDebug("currentlyFocusedWindowProcessId != appThread"); bool ret = User32Interop.AttachThreadInput(currentlyFocusedWindowProcessIdThread, appThread, true); - Log.Debug("AttachThreaInput returned " + ret); - Log.Debug("Calling BringWindowToTop"); + _logger.LogDebug("AttachThreaInput returned " + ret); + _logger.LogDebug("Calling BringWindowToTop"); User32Interop.BringWindowToTop(focusOnWindowHandle); - Log.Debug("Calling ShowWindow"); + _logger.LogDebug("Calling ShowWindow"); User32Interop.ShowWindow(focusOnWindowHandle.ToInt32(), User32Interop.SW_SHOW); User32Interop.AttachThreadInput(currentlyFocusedWindowProcessIdThread, appThread, false); } else { - Log.Debug("Calling BringWindowToTop"); + _logger.LogDebug("Calling BringWindowToTop"); User32Interop.BringWindowToTop(focusOnWindowHandle); - Log.Debug("Calling ShowWindow"); + _logger.LogDebug("Calling ShowWindow"); User32Interop.ShowWindow(focusOnWindowHandle.ToInt32(), User32Interop.SW_SHOW); } @@ -1369,9 +1372,9 @@ private void _pipeServer_MessageReceived(object sender, MessageReceivedEventArgs return; } - Log.Debug("Set focus to " + e.Message); + _logger.LogDebug("Set focus to " + e.Message); int h = Int32.Parse(e.Message); - Log.Debug("h: " + h); + _logger.LogDebug("h: " + h); if (h != 0) { IntPtr handle = new(h); @@ -1428,7 +1431,7 @@ private void dispose() private void LauncherForm_FormClosing(object sender, FormClosingEventArgs e) { - Log.Debug("Closing ACATWatchForm"); + _logger.LogDebug("Closing ACATWatchForm"); dispose(); } @@ -1440,7 +1443,7 @@ private void LauncherForm_Load(object sender, EventArgs e) _pipeServer = new PipeServer("ACATWatch", PipeDirection.InOut); _pipeServer.MessageReceived += _pipeServer_MessageReceived; - Log.Debug("Starting pipe server"); + _logger.LogDebug("Starting pipe server"); try { @@ -1448,7 +1451,7 @@ private void LauncherForm_Load(object sender, EventArgs e) } catch (Exception ex) { - Log.Exception("Failed to start pipe server", ex); + _logger.LogError(ex, "Failed to start pipe server"); } } @@ -1490,7 +1493,7 @@ private void PipesMessageHandler(string message) } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, "Error in PipesMessageHandler"); } } } diff --git a/src/Applications/ACATWatch/Program.cs b/src/Applications/ACATWatch/Program.cs index 62e5a9c9..8723ab47 100644 --- a/src/Applications/ACATWatch/Program.cs +++ b/src/Applications/ACATWatch/Program.cs @@ -14,6 +14,7 @@ using ACAT.Applications.ACATWatch; using ACAT.Core.Utility; using ACAT.Extension; +using Microsoft.Extensions.Logging; using System; using System.Reflection; using System.Windows.Forms; @@ -22,6 +23,8 @@ namespace ACATWatch { internal static class Program { + private static ILogger _logger; + /// /// The main entry point for the application. /// @@ -46,14 +49,15 @@ private static void Main() // Initialize modern logging infrastructure (ticket #3) var modernLogger = LoggingConfiguration.CreateLoggerFactory(); + _logger = modernLogger.CreateLogger(typeof(Program)); FileUtils.LogAssemblyInfo(Assembly.GetExecutingAssembly()); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); - Application.Run(new ACATWatchForm()); + Application.Run(new ACATWatchForm(_logger)); - Log.Info("**** Exit " + Common.AppPreferences.AppName + " " + DateTime.Now.ToString() + " ****"); + _logger.LogInformation("**** Exit " + Common.AppPreferences.AppName + " " + DateTime.Now.ToString() + " ****"); Log.Close(); modernLogger?.Dispose(); @@ -61,8 +65,11 @@ private static void Main() else { Log.SetupListeners(); - Log.Error("Failed to load user preferences. Exiting application."); + var tempFactory = LoggingConfiguration.CreateLoggerFactory(); + var tempLogger = tempFactory.CreateLogger(typeof(Program)); + tempLogger.LogError("Failed to load user preferences. Exiting application."); Log.Close(); + tempFactory.Dispose(); } } } diff --git a/src/Applications/AppCommon/Onboarding.cs b/src/Applications/AppCommon/Onboarding.cs index fad0458f..15bba16f 100644 --- a/src/Applications/AppCommon/Onboarding.cs +++ b/src/Applications/AppCommon/Onboarding.cs @@ -5,6 +5,7 @@ using ACAT.Extension; using ACAT.Extensions.Onboarding.UI; using ACAT.Extensions.Onboarding.UI.Forms; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Reflection; @@ -49,6 +50,7 @@ public static bool DoOnboarding() public static bool ResetAllPreferences(List currentCategory) { + var logger = LoggingConfiguration.CreateLogger(typeof(AppCommon)); try { // Reset general preferences @@ -82,13 +84,14 @@ public static bool ResetAllPreferences(List currentCategory } catch (Exception ex) { - Log.Exception(ex); + logger.LogError(ex, "Error resetting preferences"); return false; } } private static void CopyPreferencesValues(IPreferences source, IPreferences target) { + var logger = LoggingConfiguration.CreateLogger(typeof(AppCommon)); var sourceType = source.GetType(); var targetType = target.GetType(); @@ -110,7 +113,7 @@ private static void CopyPreferencesValues(IPreferences source, IPreferences targ } catch (Exception ex) { - Log.Debug($"Could not copy property {prop.Name}: {ex.Message}"); + logger.LogDebug("Could not copy property {PropertyName}: {Message}", prop.Name, ex.Message); } } } diff --git a/src/Docs/DeveloperSupport/SampleProjects/SampleActuator/SampleActuator.cs b/src/Docs/DeveloperSupport/SampleProjects/SampleActuator/SampleActuator.cs index 215900e3..6b80267c 100644 --- a/src/Docs/DeveloperSupport/SampleProjects/SampleActuator/SampleActuator.cs +++ b/src/Docs/DeveloperSupport/SampleProjects/SampleActuator/SampleActuator.cs @@ -15,6 +15,7 @@ using ACAT.Core.ActuatorManagement; using ACAT.Core.UserManagement; using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; namespace ACAT.Extensions.Actuators.SampleActuator @@ -24,6 +25,8 @@ namespace ACAT.Extensions.Actuators.SampleActuator "Skeleton sample code for a sample actuator")] internal class SampleActuator : ActuatorBase { + private readonly ILogger _logger; + /// /// The settings object for this actuator /// @@ -51,6 +54,7 @@ internal class SampleActuator : ActuatorBase /// public SampleActuator() { + _logger = LoggingConfiguration.CreateLogger(); } /// @@ -112,7 +116,7 @@ protected override void Dispose(bool disposing) { try { - Log.Verbose(); + _logger.LogTrace("Disposing SampleActuator"); if (disposing) { diff --git a/src/Docs/DeveloperSupport/SampleProjects/SampleActuator/SampleActuatorSwitch.cs b/src/Docs/DeveloperSupport/SampleProjects/SampleActuator/SampleActuatorSwitch.cs index a0fae505..11de966b 100644 --- a/src/Docs/DeveloperSupport/SampleProjects/SampleActuator/SampleActuatorSwitch.cs +++ b/src/Docs/DeveloperSupport/SampleProjects/SampleActuator/SampleActuatorSwitch.cs @@ -24,6 +24,7 @@ using ACAT.Core.ActuatorManagement; using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; namespace ACAT.Extensions.Actuators.SampleActuator { @@ -61,7 +62,7 @@ protected override void Dispose(bool disposing) { try { - Log.Verbose(); + _logger.LogTrace("Disposing SampleActuatorSwitch"); if (disposing) { diff --git a/src/Extensions/ACAT.Extensions.Onboarding/UI/OnboardingWizard.cs b/src/Extensions/ACAT.Extensions.Onboarding/UI/OnboardingWizard.cs index e6fd9ffa..ca16ee43 100644 --- a/src/Extensions/ACAT.Extensions.Onboarding/UI/OnboardingWizard.cs +++ b/src/Extensions/ACAT.Extensions.Onboarding/UI/OnboardingWizard.cs @@ -8,6 +8,7 @@ using ACAT.Core.CoreInterfaces; using ACAT.Core.Utility; using ACAT.Core.Utility.TypeLoader; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.IO; @@ -24,6 +25,7 @@ namespace ACAT.Extensions.Onboarding.UI public class OnboardingWizard : IOnboardingWizard { private static volatile bool _DLLError = false; + private readonly ILogger _logger; private int _extensionIndex = -1; private readonly List _extensionsTypeCache = new(); private readonly List _history = new(); @@ -32,6 +34,7 @@ public class OnboardingWizard : IOnboardingWizard public OnboardingWizard() { + _logger = LoggingConfiguration.CreateLogger(); } private readonly TypeLoader _TypeLoader = new(); @@ -164,7 +167,7 @@ public bool Initialize(OnboardingSequence sequence) if (_onboardingSequence.OnboardingSequenceItems.Count == 0) { - Log.Debug("No onboarding sequence items found!!"); + _logger.LogDebug("No onboarding sequence items found!!"); return false; } foreach (var onboardingItem in _onboardingSequence.OnboardingSequenceItems) @@ -184,7 +187,7 @@ public bool Initialize(OnboardingSequence sequence) if (_onboardingExtensions.Count == 0) { - Log.Debug("No onboarding extensions found!!"); + _logger.LogDebug("No onboarding extensions found!!"); return false; } diff --git a/src/Extensions/ACAT.Extensions.Onboarding/UI/UserControls/UserControlHardwareSwitchSetup.cs b/src/Extensions/ACAT.Extensions.Onboarding/UI/UserControls/UserControlHardwareSwitchSetup.cs index 45699429..9608c041 100644 --- a/src/Extensions/ACAT.Extensions.Onboarding/UI/UserControls/UserControlHardwareSwitchSetup.cs +++ b/src/Extensions/ACAT.Extensions.Onboarding/UI/UserControls/UserControlHardwareSwitchSetup.cs @@ -17,6 +17,7 @@ using ACAT.Core.Utility; using ACAT.Extensions.Onboarding.Onboarding; using ACATResources; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Drawing; @@ -35,6 +36,8 @@ public partial class UserControlHardwareSwitchSetup : UserControl, IOnboardingUs { #region Properties + private readonly ILogger _logger; + // TODO - Localize Me private const String bodyStyle = " background-color:#232433;"; @@ -62,6 +65,7 @@ public partial class UserControlHardwareSwitchSetup : UserControl, IOnboardingUs public UserControlHardwareSwitchSetup(IOnboardingWizard wizard, IOnboardingExtension onboardingExtension, String stepId, OnboardingHardwareSwitchSetup.SwitchType switchType) { + _logger = LoggingConfiguration.CreateLogger(); InitializeComponent(); _onboardingExtension = onboardingExtension; @@ -124,7 +128,7 @@ public bool Initialize() } } - Log.Debug("triggerHotKey: " + _strTriggerHotkey); + _logger.LogDebug("triggerHotKey: " + _strTriggerHotkey); _strTriggerHotkey = Regex.Replace(_strTriggerHotkey, "alt", "", RegexOptions.IgnoreCase); _strTriggerHotkey = Regex.Replace(_strTriggerHotkey, "shift", "", RegexOptions.IgnoreCase); @@ -133,11 +137,11 @@ public bool Initialize() if (!isFunctionKey(_strTriggerHotkey)) { - Log.Debug("Invalid triggerHotKey. Reseting to F12"); + _logger.LogDebug("Invalid triggerHotKey. Reseting to F12"); _strTriggerHotkey = "F12"; } - Log.Debug("After parsing triggerhotkey: " + _strTriggerHotkey); + _logger.LogDebug("After parsing triggerhotkey: " + _strTriggerHotkey); initButtons(); @@ -204,7 +208,7 @@ public bool QueryGoToNextStep() { var isValid = isHotkeyValid(); - Log.Debug("isValidKeyCombo: " + isValid); + _logger.LogDebug("isValidKeyCombo: " + isValid); bool retVal; @@ -252,7 +256,7 @@ private void webBrowser_Navigating(object sender, WebBrowserNavigatingEventArgs { var str = e.Url.ToString(); - Log.Debug("Url is [" + str + "]"); + _logger.LogDebug("Url is [" + str + "]"); if (str.ToLower().Contains("blank")) { diff --git a/src/Extensions/ACAT.Extensions.Onboarding/UI/UserControls/UserControlHardwareSwitchTest.cs b/src/Extensions/ACAT.Extensions.Onboarding/UI/UserControls/UserControlHardwareSwitchTest.cs index e008c6b7..72046ee3 100644 --- a/src/Extensions/ACAT.Extensions.Onboarding/UI/UserControls/UserControlHardwareSwitchTest.cs +++ b/src/Extensions/ACAT.Extensions.Onboarding/UI/UserControls/UserControlHardwareSwitchTest.cs @@ -18,6 +18,7 @@ using ACAT.Core.Utility; using ACAT.Extensions.Onboarding.Onboarding; using ACATResources; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.ComponentModel; @@ -36,6 +37,7 @@ namespace ACAT.Extensions.Onboarding.UI.UserControls [DesignerCategory("code")] public partial class UserControlHardwareSwitchTest : UserControl, IOnboardingUserControl { + private readonly ILogger _logger; private const String bodyStyle = " background-color:#232433;"; private const String headStyle = "a:link{color: rgb(255, 170, 0);}"; private const int switchActivationDelay = 300; @@ -57,6 +59,7 @@ public partial class UserControlHardwareSwitchTest : UserControl, IOnboardingUse public UserControlHardwareSwitchTest(IOnboardingWizard wizard, IOnboardingExtension onboardingExtension, String stepId, OnboardingHardwareSwitchSetup.SwitchType switchType) { + _logger = LoggingConfiguration.CreateLogger(); InitializeComponent(); _onboardingExtension = onboardingExtension; @@ -121,7 +124,7 @@ public void handleKeyDownEvent(object sender, KeyEventArgs e) hotKey += "+" + e.KeyCode; } - Log.Debug("Keyudown Hotkey: " + hotKey); + _logger.LogDebug("Keyudown Hotkey: " + hotKey); if (String.Compare(hotKey, _strTriggerHotkey, true) == 0) { @@ -147,16 +150,16 @@ public void handleKeyUpEvent(object sender, KeyEventArgs e) hotKey += "+" + e.KeyCode; } - Log.Debug("Keyup hotkey: " + hotKey); + _logger.LogDebug("Keyup hotkey: " + hotKey); if (String.Compare(e.KeyCode.ToString(), _strTriggerHotkey, true) == 0) { _hotkeyActive = false; - Log.Debug("elapsedmilliseconds " + _acceptTimer.ElapsedMilliseconds); + _logger.LogDebug("elapsedmilliseconds " + _acceptTimer.ElapsedMilliseconds); if (_acceptTimer.IsRunning && _acceptTimer.ElapsedMilliseconds >= _acceptTime) { - Log.Debug("Setting _switchTested to true"); + _logger.LogDebug("Setting _switchTested to true"); _switchTested = true; setButtonBackgroundAndText(true, "Switch\nActivated"); @@ -164,7 +167,7 @@ public void handleKeyUpEvent(object sender, KeyEventArgs e) } else { - Log.Debug("Key not accepted as elapsed time is < MinActuationHoldTime"); + _logger.LogDebug("Key not accepted as elapsed time is < MinActuationHoldTime"); } _acceptTimer.Stop(); @@ -206,7 +209,7 @@ public bool Initialize() } } - Log.Debug("keyboardActuationCombo: " + _strTriggerHotkey); + _logger.LogDebug("keyboardActuationCombo: " + _strTriggerHotkey); _acceptTime = CoreGlobals.AppPreferences.MinActuationHoldTime; @@ -238,7 +241,7 @@ public bool QueryCancelOnboarding() public bool QueryGoToNextStep() { - Log.Debug("QueryGoToNextStep: SwichTested: " + _switchTested); + _logger.LogDebug("QueryGoToNextStep: SwichTested: " + _switchTested); bool retVal; diff --git a/src/Extensions/ACAT.Extensions.Onboarding/UI/UserControls/UserControlSwitchSelect.cs b/src/Extensions/ACAT.Extensions.Onboarding/UI/UserControls/UserControlSwitchSelect.cs index 96c1c8eb..e043709a 100644 --- a/src/Extensions/ACAT.Extensions.Onboarding/UI/UserControls/UserControlSwitchSelect.cs +++ b/src/Extensions/ACAT.Extensions.Onboarding/UI/UserControls/UserControlSwitchSelect.cs @@ -11,6 +11,7 @@ using ACAT.Core.PanelManagement; using ACAT.Core.Utility; using ACATResources; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Drawing; @@ -25,6 +26,7 @@ namespace ACAT.Extensions.Onboarding.UI.UserControls public partial class UserControlSwitchSelect : UserControl, IOnboardingUserControl { public IActuator ActuatorSelected = null; + private readonly ILogger _logger; private const String bodyStyle = " background-color:#232433;"; private const String headStyle = "a:link{color: rgb(255, 170, 0);}"; private const String textStyle = "font-family:'Montserrat Medium'; font-size:24px; color:white"; @@ -36,6 +38,7 @@ public partial class UserControlSwitchSelect : UserControl, IOnboardingUserContr public UserControlSwitchSelect(IOnboardingWizard wizard, IOnboardingExtension onboardingExtension, String stepId) { + _logger = LoggingConfiguration.CreateLogger(); InitializeComponent(); _onboardingExtension = onboardingExtension; @@ -156,7 +159,7 @@ private void ListBoxActuators_SelectedIndexChanged(object sender, EventArgs e) if (!String.IsNullOrEmpty(desc)) { String html = String.Format(_htmlTemplate, headStyle, bodyStyle, textStyle, HtmlUtils.DecodeHtml(desc)); - Log.Debug(html); + _logger.LogDebug(html); html = html.Replace(CoreGlobals.MacroACATUserGuide, HtmlUtils.EncodeString(CoreGlobals.ACATUserGuideFileName)); @@ -189,7 +192,7 @@ private void WebBrowserDesc_Navigating(object sender, WebBrowserNavigatingEventA { var str = e.Url.ToString(); - Log.Debug("Url is [" + str + "]"); + _logger.LogDebug("Url is [" + str + "]"); if (str.ToLower().Contains("blank")) { diff --git a/src/Extensions/ACAT.Extensions.UI/Dialogs/WindowMoveResizeScannerForm.cs b/src/Extensions/ACAT.Extensions.UI/Dialogs/WindowMoveResizeScannerForm.cs index 9534ce58..4e0f1fbf 100644 --- a/src/Extensions/ACAT.Extensions.UI/Dialogs/WindowMoveResizeScannerForm.cs +++ b/src/Extensions/ACAT.Extensions.UI/Dialogs/WindowMoveResizeScannerForm.cs @@ -24,6 +24,7 @@ using ACAT.Core.Utility; using ACAT.Core.WidgetManagement; using ACAT.Extension.UI.ScannerForms; +using Microsoft.Extensions.Logging; using System; using System.Security.Permissions; using System.Threading; @@ -49,6 +50,8 @@ namespace ACAT.Extensions.UI.Dialogs "WindowMoveResizeScannerForm")] public partial class WindowMoveResizeScannerForm : GenericScannerForm, IDialogPanel { + private readonly ILogger _logger; + /// /// Used to invoke methods and properties in this class /// @@ -64,6 +67,7 @@ public partial class WindowMoveResizeScannerForm : GenericScannerForm, IDialogPa /// public WindowMoveResizeScannerForm() : base() { + _logger = LoggingConfiguration.CreateLogger(); InitializeComponent(); _invoker = new ExtensionInvoker(this); @@ -138,13 +142,13 @@ public override bool HandleInitialize(StartupArg startupArg) /// public void OnButtonActuated(Widget widget) { - Log.Debug("**Actuate** " + widget.UIControl.Name + " Value: " + widget.Value); + _logger.LogDebug("**Actuate** {WidgetName} Value: {WidgetValue}", widget.UIControl.Name, widget.Value); var value = widget.Value; if (String.IsNullOrEmpty(value)) { - Log.Debug("OnButtonActuated() -- received actuation from empty widget!"); + _logger.LogDebug("OnButtonActuated() -- received actuation from empty widget!"); return; } @@ -179,7 +183,7 @@ public void OnButtonActuated(Widget widget) break; default: - Log.Debug("OnButtonActuated() -- unhandled widget actuation!"); + _logger.LogDebug("OnButtonActuated() -- unhandled widget actuation!"); break; } })); diff --git a/src/Extensions/ACAT.Extensions.UI/Scanners/CursorNavigationScanner.cs b/src/Extensions/ACAT.Extensions.UI/Scanners/CursorNavigationScanner.cs index 3cc843ef..82e5277b 100644 --- a/src/Extensions/ACAT.Extensions.UI/Scanners/CursorNavigationScanner.cs +++ b/src/Extensions/ACAT.Extensions.UI/Scanners/CursorNavigationScanner.cs @@ -25,6 +25,7 @@ using ACAT.Core.WidgetManagement; using ACAT.Extension; using ACAT.Extension.CommandHandlers; +using Microsoft.Extensions.Logging; using System; using System.Security.Permissions; using System.Windows.Forms; @@ -41,6 +42,8 @@ namespace ACAT.Extensions.UI.Scanners "Cursor Navigation Scanner")] public partial class CursorNavigationScanner : Form, IScannerPanel, ISupportsStatusBar { + private readonly ILogger _logger; + /// /// Dispatcher to handle execution of commands /// @@ -61,6 +64,7 @@ public partial class CursorNavigationScanner : Form, IScannerPanel, ISupportsSta /// public CursorNavigationScanner() { + _logger = LoggingConfiguration.CreateLogger(); _scannerCommon = new ScannerCommon(this); InitializeComponent(); @@ -199,7 +203,7 @@ public void OnFocusChanged(WindowActivityMonitorInfo monitorInfo) /// public void OnPause() { - Log.Verbose(); + _logger.LogTrace("OnPause"); _scannerCommon.OnPause(); } @@ -219,7 +223,7 @@ public bool OnQueryPanelChange(PanelRequestEventArgs eventArg) /// public void OnResume() { - Log.Verbose(); + _logger.LogTrace("OnResume"); _scannerCommon.OnResume(); } @@ -319,7 +323,7 @@ private void KeyStateTracker_EvtKeyStateChanged() } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, "Error in KeyStateTracker_EvtKeyStateChanged"); } } diff --git a/src/Extensions/ACAT.Extensions.UI/Scanners/DashboardAppScanner.cs b/src/Extensions/ACAT.Extensions.UI/Scanners/DashboardAppScanner.cs index 1ad460e3..601af1af 100644 --- a/src/Extensions/ACAT.Extensions.UI/Scanners/DashboardAppScanner.cs +++ b/src/Extensions/ACAT.Extensions.UI/Scanners/DashboardAppScanner.cs @@ -14,6 +14,7 @@ using ACAT.Extension.UI; using ACAT.Extension.UI.ScannerForms; using ACAT.Extensions.UI.UserControls.Toolbars; +using Microsoft.Extensions.Logging; using System; using System.ComponentModel; using System.Drawing; @@ -27,6 +28,7 @@ namespace ACAT.Extensions.UI.Scanners [DesignerCategory("code")] public partial class DashboardAppScanner : GenericScannerForm { + private readonly ILogger _logger; private TableLayoutPanel panelDashboardControls; private TableLayoutPanel panelTopToolbar; private TableLayoutPanel ScannerBorder; @@ -35,11 +37,12 @@ public partial class DashboardAppScanner : GenericScannerForm public DashboardAppScanner() : base() { + _logger = LoggingConfiguration.CreateLogger(); _dispatcher = new DashboardAppDispatcher(this); _launchAppAgent = Context.AppAgentMgr.GetFunctionalAgentByName("LaunchAppAgent") as IFunctionalAgent; if (_launchAppAgent == null) { - Log.Error("LaunchAppAgent not found. Ensure it is registered in the ACAT configuration."); + _logger.LogError("LaunchAppAgent not found. Ensure it is registered in the ACAT configuration."); } } @@ -138,7 +141,7 @@ protected override void InitializeComponent() if (e.Control is UserControl userControl) { currentPanel = userControl; - Log.Debug($"Current panel set to: {currentPanel.GetType().Name}"); + _logger.LogDebug("Current panel set to: {PanelName}", currentPanel.GetType().Name); } }; } @@ -207,14 +210,14 @@ public bool ShowTalkPanel(WordPredictionModes mode) var form = PanelManager.Instance.CreatePanel("TalkApplicationScanner", startupArg); if (form == null) { - Log.Error("Could not create TalkApplicationScanner panel."); + _logger.LogError("Could not create TalkApplicationScanner panel."); return false; } var agent = Context.AppAgentMgr.GetAgentByName("Talk Application Agent"); if (agent == null) { - Log.Error("Talk Application Agent not found. Ensure it is registered in the ACAT configuration."); + _logger.LogError("Talk Application Agent not found. Ensure it is registered in the ACAT configuration."); form.Dispose(); return false; } @@ -230,7 +233,7 @@ public bool ShowTalkPanel(WordPredictionModes mode) } catch (Exception ex) { - Log.Exception(ex.Message); + _logger.LogError(ex, "Error showing talk panel"); return false; } //finally @@ -246,7 +249,7 @@ public bool ShowTalkPanel(WordPredictionModes mode) public bool HandleTalkAppRequest(string Command) { - Log.Debug($"Handling Talk App Request: {Command}"); + _logger.LogDebug("Handling Talk App Request: {Command}", Command); ScannerCommon.UserControlManager.StopTopLevelAnimation(); this.Hide(); @@ -266,7 +269,7 @@ public bool HandleTalkAppRequest(string Command) else { - Log.Error($"Unknown command: {Command}"); + _logger.LogError("Unknown command: {Command}", Command); return false; } @@ -312,6 +315,8 @@ private void InitializeTopToolbar() } protected class DashboardAppCommandHandler : RunCommandHandler { + private readonly ILogger _logger; + public class CommandHandlerArgs :EventArgs { public CommandHandlerArgs(String command) @@ -326,11 +331,14 @@ public override string ToString() } } - public DashboardAppCommandHandler(String cmd) : base(cmd) { } + public DashboardAppCommandHandler(String cmd) : base(cmd) + { + _logger = LoggingConfiguration.CreateLogger(); + } public override bool Execute(ref bool handled) { - Log.Info($"Executing command: {Command}"); + _logger.LogInformation("Executing command: {Command}", Command); var form = Dispatcher.Scanner.Form as DashboardAppScanner; handled = Command switch @@ -353,7 +361,7 @@ public override bool Execute(ref bool handled, object source = null) form.ScannerCommon.UserControlManager.StopTopLevelAnimation(); form.Visible = false; - Log.Info($"Executing command: {Command} from source: {source?.GetType().Name}"); + form._logger.LogInformation("Executing command: {Command} from source: {SourceType}", Command, source?.GetType().Name); switch (Command) { diff --git a/src/Extensions/ACAT.Extensions.UI/Scanners/TalkApplicationScanner.cs b/src/Extensions/ACAT.Extensions.UI/Scanners/TalkApplicationScanner.cs index b16e910f..77e3dded 100644 --- a/src/Extensions/ACAT.Extensions.UI/Scanners/TalkApplicationScanner.cs +++ b/src/Extensions/ACAT.Extensions.UI/Scanners/TalkApplicationScanner.cs @@ -13,6 +13,7 @@ using ACAT.Extension.UI; using ACAT.Extension.UI.ScannerForms; using ACATResources; +using Microsoft.Extensions.Logging; using System; using System.Security.Permissions; using System.Windows.Forms; @@ -28,11 +29,13 @@ public partial class TalkApplicationScanner : Form public partial class TalkApplicationScanner : GenericScannerForm, ISupportsStatusBar //*/ { + private readonly ILogger _logger; private TalkWindowTextBoxPhraseModeUserControl _textBoxPhraseModeUserControl; private TextBox _textBoxTalkWindow; private TalkWindowTextBoxUserControl _textBoxUserControl; public TalkApplicationScanner() : base() { + _logger = LoggingConfiguration.CreateLogger(); _dispatcher = new TalkAppDispatcher(this); } @@ -367,7 +370,7 @@ private void TextBoxTalkWindowOnKeyPress(object sender, KeyPressEventArgs keyPre } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, "Error in speak"); } } @@ -375,9 +378,9 @@ private void textToSpeech(String text) { if (!String.IsNullOrEmpty(text)) { - Log.Debug("*** TTS *** : " + text); + _logger.LogDebug("*** TTS *** : {Text}", text); TTSManager.Instance.ActiveEngine.Speak(text); - Log.Debug("*** TTS *** : sent text!"); + _logger.LogDebug("*** TTS *** : sent text!"); AuditLog.Audit(new AuditEventTextToSpeech(TTSManager.Instance.ActiveEngine.Descriptor.Name)); } @@ -389,7 +392,7 @@ private void ttsAndLearn(String text) { textToSpeech(text); - Log.Debug("tts " + text); + _logger.LogDebug("tts {Text}", text); if (WordPredictionManager.Instance.ActiveWordPredictor.SupportsLearning) { @@ -407,7 +410,7 @@ private void ttsAndLearn(String text) WordPredictionManager.Instance.ActiveWordPredictor.Learn(text, WordPredictorMessageTypes.LearnCanned); break; } - Log.Debug("Learn " + text); + _logger.LogDebug("Learn {Text}", text); WordPredictionManager.Instance.ActiveWordPredictor.Learn(text, WordPredictorMessageTypes.LearnSentence); } } @@ -442,12 +445,11 @@ public TalkApplicationCommandHandler(String cmd) : base(cmd) { } public override bool Execute(ref bool handled) { - Log.Info("Inside Talk Application Scanner TalkApplicationCommandHandler for command: " + Command); + var form = Dispatcher.Scanner.Form as TalkApplicationScanner; + form._logger.LogInformation("Inside Talk Application Scanner TalkApplicationCommandHandler for command: {Command}", Command); handled = true; - var form = Dispatcher.Scanner.Form as TalkApplicationScanner; - switch (Command) { case "CmdAutocompleteWithFirstWord": diff --git a/src/Extensions/ACAT.Extensions.UI/Scanners/YesNoResponseScanner.cs b/src/Extensions/ACAT.Extensions.UI/Scanners/YesNoResponseScanner.cs index a9137267..b0488b21 100644 --- a/src/Extensions/ACAT.Extensions.UI/Scanners/YesNoResponseScanner.cs +++ b/src/Extensions/ACAT.Extensions.UI/Scanners/YesNoResponseScanner.cs @@ -22,6 +22,7 @@ using ACAT.Core.WidgetManagement; using ACAT.Extension.CommandHandlers; using ACAT.Extension.UI; +using Microsoft.Extensions.Logging; using System; using System.Security.Permissions; using System.Windows.Forms; @@ -33,6 +34,8 @@ namespace ACAT.Extensions.UI.Menus "Yes No Response Scanner")] public partial class YesNoResponseScanner : Form, IScannerPanel, IExtension { + private readonly ILogger _logger; + /// /// Represents the widget of this form /// @@ -88,6 +91,7 @@ public partial class YesNoResponseScanner : Form, IScannerPanel, IExtension /// Title of the scanner public YesNoResponseScanner(String panelClass, String panelTitle) { + _logger = LoggingConfiguration.CreateLogger(); scannerCommon = new ScannerCommon(this); InitializeComponent(); @@ -166,7 +170,7 @@ protected override CreateParams CreateParams { get { - Log.Verbose(); + _logger.LogTrace("CreateParams"); return Windows.SetFormStyles(base.CreateParams); } } @@ -205,7 +209,7 @@ public ExtensionInvoker GetInvoker() /// true on success public bool Initialize(StartupArg startupArg) { - Log.Verbose(); + _logger.LogTrace("Initialize"); PanelClass = startupArg.PanelClass; startupCommandArg = startupArg.Arg; this.startupArg = startupArg; @@ -237,7 +241,7 @@ public void OnFocusChanged(WindowActivityMonitorInfo monitorInfo) /// public virtual void OnPause() { - Log.Verbose(); + _logger.LogTrace("OnPause"); scannerCommon.OnPause(); } @@ -257,7 +261,7 @@ public bool OnQueryPanelChange(PanelRequestEventArgs arg) /// public virtual void OnResume() { - Log.Verbose(); + _logger.LogTrace("OnResume"); scannerCommon.OnResume(); } diff --git a/src/Extensions/ACAT.Extensions.UI/Scanners/YesNoScanner.cs b/src/Extensions/ACAT.Extensions.UI/Scanners/YesNoScanner.cs index 0555c17e..95a48612 100644 --- a/src/Extensions/ACAT.Extensions.UI/Scanners/YesNoScanner.cs +++ b/src/Extensions/ACAT.Extensions.UI/Scanners/YesNoScanner.cs @@ -24,6 +24,7 @@ using ACAT.Core.WidgetManagement; using ACAT.Extension.CommandHandlers; using ACAT.Extension.UI; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Windows.Forms; @@ -41,6 +42,8 @@ namespace ACAT.Extensions.UI.Menus "Yes No Scanner")] public partial class YesNoScanner : Form, IScannerPanel, IExtension { + private readonly ILogger _logger; + /// /// Represents the widget of this form /// @@ -98,6 +101,7 @@ public partial class YesNoScanner : Form, IScannerPanel, IExtension /// Title of the scanner public YesNoScanner(String panelClass, String panelTitle) { + _logger = LoggingConfiguration.CreateLogger(); scannerCommon = new ScannerCommon(this); InitializeComponent(); @@ -195,7 +199,7 @@ protected override CreateParams CreateParams { get { - Log.Verbose(); + _logger.LogTrace("CreateParams"); return Windows.SetFormStyles(base.CreateParams); } } @@ -234,7 +238,7 @@ public ExtensionInvoker GetInvoker() /// true on success public bool Initialize(StartupArg startupArg) { - Log.Verbose(); + _logger.LogTrace("Initialize"); PanelClass = startupArg.PanelClass; startupCommandArg = startupArg.Arg; this.startupArg = startupArg; @@ -266,7 +270,7 @@ public void OnFocusChanged(WindowActivityMonitorInfo monitorInfo) /// public virtual void OnPause() { - Log.Verbose(); + _logger.LogTrace("OnPause"); scannerCommon.OnPause(); } @@ -286,7 +290,7 @@ public bool OnQueryPanelChange(PanelRequestEventArgs arg) /// public virtual void OnResume() { - Log.Verbose(); + _logger.LogTrace("OnResume"); scannerCommon.OnResume(); } diff --git a/src/Extensions/ACAT.Extensions.UI/UserControls/SentencePredictionUserControl.cs b/src/Extensions/ACAT.Extensions.UI/UserControls/SentencePredictionUserControl.cs index 5b4b05fc..412608bd 100644 --- a/src/Extensions/ACAT.Extensions.UI/UserControls/SentencePredictionUserControl.cs +++ b/src/Extensions/ACAT.Extensions.UI/UserControls/SentencePredictionUserControl.cs @@ -21,6 +21,7 @@ using ACAT.Core.WordPredictorManagement.Interfaces; using ACAT.Extension.UI; using ACAT.Extension.UI.UserControls; +using Microsoft.Extensions.Logging; using System; namespace ACAT.Extensions.UI.UserControls @@ -30,10 +31,12 @@ namespace ACAT.Extensions.UI.UserControls "User Control for Sentence Prediction")] public partial class SentencePredictionUserControl : KeyboardUserControl { + private readonly ILogger _logger; private UserControlWordPredictionCommon _userControlWordPredictionCommon; public SentencePredictionUserControl() { + _logger = LoggingConfiguration.CreateLogger(); InitializeComponent(); } @@ -73,9 +76,9 @@ private void textToSpeech(String text) { if (!String.IsNullOrEmpty(text)) { - Log.Debug("*** TTS *** : " + text); + _logger.LogDebug("*** TTS *** : {Text}", text); TTSManager.Instance.ActiveEngine.Speak(text); - Log.Debug("*** TTS *** : sent text!"); + _logger.LogDebug("*** TTS *** : sent text!"); AuditLog.Audit(new AuditEventTextToSpeech(TTSManager.Instance.ActiveEngine.Descriptor.Name)); } diff --git a/src/Extensions/BCI/ACAT.Extensions.BCI.UI/UserControls/PhrasesUserControlBCI.cs b/src/Extensions/BCI/ACAT.Extensions.BCI.UI/UserControls/PhrasesUserControlBCI.cs index 44bebf18..95fb1e47 100644 --- a/src/Extensions/BCI/ACAT.Extensions.BCI.UI/UserControls/PhrasesUserControlBCI.cs +++ b/src/Extensions/BCI/ACAT.Extensions.BCI.UI/UserControls/PhrasesUserControlBCI.cs @@ -25,6 +25,7 @@ using ACAT.Core.WordPredictorManagement; using ACAT.Core.WordPredictorManagement.Interfaces; using ACAT.Extension.UI; +using Microsoft.Extensions.Logging; using System; using System.Windows.Forms; @@ -35,13 +36,15 @@ namespace ACAT.Extensions.BCI.UI.UserControls "User Control for Sentence Prediction BCI")] public partial class PhrasesUserControlBCI : UserControl, IUserControl { + private readonly ILogger _logger; private static String _formConfigFilePath = ""; private static UserControlConfigMapEntry _mapEntry; private UserControlKeyboardCommon _keyboardCommon; IScannerPanel _scanner; private UserControlWordPredictionCommon _sentencePredictionCommon; - public PhrasesUserControlBCI() + public PhrasesUserControlBCI(ILogger logger = null) { + _logger = logger ?? LoggerFactory.GetLogger(); InitializeComponent(); } @@ -152,9 +155,9 @@ private void textToSpeech(String text) { if (!String.IsNullOrEmpty(text)) { - Log.Debug("*** TTS *** : " + text); + _logger.LogDebug("*** TTS *** : " + text); TTSManager.Instance.ActiveEngine.Speak(text); - Log.Debug("*** TTS *** : sent text!"); + _logger.LogDebug("*** TTS *** : sent text!"); AuditLog.Audit(new AuditEventTextToSpeech(TTSManager.Instance.ActiveEngine.Descriptor.Name)); } diff --git a/src/Extensions/BCI/ACAT.Extensions.BCI.UI/UserControls/TTSYesNoUserControlBCI.cs b/src/Extensions/BCI/ACAT.Extensions.BCI.UI/UserControls/TTSYesNoUserControlBCI.cs index 99c5cd83..a71971dc 100644 --- a/src/Extensions/BCI/ACAT.Extensions.BCI.UI/UserControls/TTSYesNoUserControlBCI.cs +++ b/src/Extensions/BCI/ACAT.Extensions.BCI.UI/UserControls/TTSYesNoUserControlBCI.cs @@ -19,6 +19,7 @@ using ACAT.Core.UserControlManagement.Interfaces; using ACAT.Core.Utility; using ACAT.Core.WidgetManagement; +using Microsoft.Extensions.Logging; using System; using System.Windows.Forms; @@ -29,12 +30,14 @@ namespace ACAT.Extensions.BCI.UI.UserControls "User Control keyboard BCI")] public partial class TTSYesNoUserControlBCI : UserControl, IUserControl { + private readonly ILogger _logger; private static String _formConfigFilePath = ""; private static UserControlConfigMapEntry _mapEntry; private UserControlKeyboardCommon _keyboardCommon; - public TTSYesNoUserControlBCI() + public TTSYesNoUserControlBCI(ILogger logger = null) { + _logger = logger ?? LoggerFactory.GetLogger(); InitializeComponent(); } @@ -129,9 +132,9 @@ private void textToSpeech(String text) { if (!String.IsNullOrEmpty(text)) { - Log.Debug("*** TTS *** : " + text); + _logger.LogDebug("*** TTS *** : " + text); TTSManager.Instance.ActiveEngine.Speak(text); - Log.Debug("*** TTS *** : sent text!"); + _logger.LogDebug("*** TTS *** : sent text!"); AuditLog.Audit(new AuditEventTextToSpeech(TTSManager.Instance.ActiveEngine.Descriptor.Name)); } diff --git a/src/Extensions/BCI/ACAT.Extensions.BCI.UI/UserControls/TTSYesNoUserControlBCI2.cs b/src/Extensions/BCI/ACAT.Extensions.BCI.UI/UserControls/TTSYesNoUserControlBCI2.cs index b10c455b..a560f504 100644 --- a/src/Extensions/BCI/ACAT.Extensions.BCI.UI/UserControls/TTSYesNoUserControlBCI2.cs +++ b/src/Extensions/BCI/ACAT.Extensions.BCI.UI/UserControls/TTSYesNoUserControlBCI2.cs @@ -19,6 +19,7 @@ using ACAT.Core.UserControlManagement.Interfaces; using ACAT.Core.Utility; using ACAT.Core.WidgetManagement; +using Microsoft.Extensions.Logging; using System; using System.Windows.Forms; @@ -29,12 +30,14 @@ namespace ACAT.Extensions.BCI.UI.UserControls "User Control keyboard BCI")] public partial class TTSYesNoUserControlBCI2 : UserControl, IUserControl { + private readonly ILogger _logger; private static String _formConfigFilePath = ""; private static UserControlConfigMapEntry _mapEntry; private UserControlKeyboardCommon _keyboardCommon; - public TTSYesNoUserControlBCI2() + public TTSYesNoUserControlBCI2(ILogger logger = null) { + _logger = logger ?? LoggerFactory.GetLogger(); InitializeComponent(); } @@ -129,9 +132,9 @@ private void textToSpeech(String text) { if (!String.IsNullOrEmpty(text)) { - Log.Debug("*** TTS *** : " + text); + _logger.LogDebug("*** TTS *** : " + text); TTSManager.Instance.ActiveEngine.Speak(text); - Log.Debug("*** TTS *** : sent text!"); + _logger.LogDebug("*** TTS *** : sent text!"); AuditLog.Audit(new AuditEventTextToSpeech(TTSManager.Instance.ActiveEngine.Descriptor.Name)); } diff --git a/src/Extensions/BCI/Actuators/EEGProcessing/Utilities/FileReader.cs b/src/Extensions/BCI/Actuators/EEGProcessing/Utilities/FileReader.cs index fe5eb04f..e09fdccb 100644 --- a/src/Extensions/BCI/Actuators/EEGProcessing/Utilities/FileReader.cs +++ b/src/Extensions/BCI/Actuators/EEGProcessing/Utilities/FileReader.cs @@ -13,6 +13,7 @@ using ACAT.Core.UserManagement; using ACAT.Core.Utility; using ACAT.Extensions.BCI.Actuators.EEG.EEGSettings; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.IO; @@ -22,11 +23,14 @@ namespace ACAT.Extensions.BCI.Actuators.EEG.EEGProcessing.Utilities { internal class FileReader { + private readonly ILogger _logger; + /// /// Constructor: read settings /// - public FileReader() + public FileReader(ILogger logger = null) { + _logger = logger ?? LoggerFactory.GetLogger(); } /// @@ -106,7 +110,7 @@ public List ReadMarkersFromFile(string filePathMarkers = "", string initDir } else { - Log.Debug("Markers file doesn't exist"); + _logger.LogDebug("Markers file doesn't exist"); } return markerValues; } @@ -202,12 +206,12 @@ public void ReadEEGDataFromFile(out double[,] rawData, out int[] triggerSignal, } else { - Log.Debug("EEG file doesn't exist"); + _logger.LogDebug("EEG file doesn't exist"); } } catch (Exception e) { - Log.Exception(e.ToString()); + _logger.LogError(e, e.ToString()); } } } diff --git a/src/Extensions/BCI/Actuators/EEGUtilities/SerialComm.cs b/src/Extensions/BCI/Actuators/EEGUtilities/SerialComm.cs index a3f61b01..a8b7ca69 100644 --- a/src/Extensions/BCI/Actuators/EEGUtilities/SerialComm.cs +++ b/src/Extensions/BCI/Actuators/EEGUtilities/SerialComm.cs @@ -8,6 +8,7 @@ //////////////////////////////////////////////////////////////////////////// using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using Microsoft.Win32; using System; using System.Collections.Generic; @@ -21,13 +22,15 @@ namespace ACAT.Extensions.BCI.Actuators.EEG.EEGUtils { internal class SerialComm { + private readonly ILogger _logger; private const int DefaultBaudRate = 115200; private long _error = 0; private readonly string _portName; private SerialPort _serialPort; - public SerialComm(String portName) + public SerialComm(String portName, ILogger logger = null) { + _logger = logger ?? LoggerFactory.GetLogger(); _portName = portName; } @@ -185,7 +188,7 @@ private void DataReceivedCallback(IAsyncResult result) { if (!errorOccurred) { - Log.Debug("OPTSEN: Callback Error in data received callback: " + ex.Message); + _logger.LogDebug("OPTSEN: Callback Error in data received callback: " + ex.Message); setError(); notifySerialPortDataReceiveError(ex.Message); } @@ -210,7 +213,7 @@ private void serialCom_DataReceived(object sender, SerialDataReceivedEventArgs e { if (!errorOccurred) { - Log.Debug("OPTSEN: BeginRead Error in data received callback: " + ex.Message); + _logger.LogDebug("OPTSEN: BeginRead Error in data received callback: " + ex.Message); notifySerialPortDataReceiveError(ex.Message); setError(); } diff --git a/src/Extensions/BCI/Actuators/gTec_SensorUI/SensorForm.cs b/src/Extensions/BCI/Actuators/gTec_SensorUI/SensorForm.cs index 045f14da..0b3449ea 100644 --- a/src/Extensions/BCI/Actuators/gTec_SensorUI/SensorForm.cs +++ b/src/Extensions/BCI/Actuators/gTec_SensorUI/SensorForm.cs @@ -13,6 +13,7 @@ using ACAT.Core.PanelManagement; using ACAT.Core.Utility; using ACAT.Extensions.BCI.Actuators.EEG.EEGDataAcquisition; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Drawing; @@ -27,6 +28,8 @@ namespace ACAT.Extensions.BCI.Actuators.gTecSensorUI /// public partial class SensorForm : Form { + private readonly ILogger _logger; + /// /// Variable storing connection manager for gTec BCI device /// @@ -110,8 +113,9 @@ public partial class SensorForm : Form public UserControl _currentUserControlShown; // Form which acts as parent for / base for all possible user controls displayed during testing process - public SensorForm(DAQ_gTecBCI gTecBCI) + public SensorForm(DAQ_gTecBCI gTecBCI, ILogger logger) { + _logger = logger; InitializeComponent(); this.WindowState = FormWindowState.Maximized; @@ -186,7 +190,7 @@ public SensorForm(DAQ_gTecBCI gTecBCI) /// public void updateOnboardingStatus(OnboardingUserState state, Dictionary resultParams) { - Log.Debug("SensorForm | updateOnboardingStatus | state: " + state.ToString()); + _logger.LogDebug("SensorForm | updateOnboardingStatus | state: " + state.ToString()); UserControl newUserControl = null; switch (state) @@ -386,11 +390,11 @@ private void startStopProcessDataTimer(bool startProcessDataTimer, OnboardingUse } timerProcessData.Start(); - Log.Debug("startStopProcessDataTimer | Started timerProcessData"); + _logger.LogDebug("startStopProcessDataTimer | Started timerProcessData"); } catch (Exception e) { - Log.Exception("startStopProcessDataTimer | Exception: " + e.ToString()); + _logger.LogError(e, "startStopProcessDataTimer | Exception: {Exception}", e.ToString()); } } else @@ -407,7 +411,7 @@ private void startStopProcessDataTimer(bool startProcessDataTimer, OnboardingUse } catch (Exception e) { - Log.Exception("startStopProcessDataTimer | Exception: " + e.ToString()); + _logger.LogError(e, "startStopProcessDataTimer | Exception: {Exception}", e.ToString()); } } } @@ -423,7 +427,7 @@ private void ProcessDataSignalCheck_Tick(object sender, EventArgs e) // Check flag to stop this particular timer if (_stopTimers || GTecDeviceTester._endSignalCheckTimer) { - Log.Debug("ProcessDataSignalCheck_Tick | _stopTimers | GTecDeviceTester._endSignalCheckTimer"); + _logger.LogDebug("ProcessDataSignalCheck_Tick | _stopTimers | GTecDeviceTester._endSignalCheckTimer"); startStopProcessDataTimer(false, OnboardingUserState.ExitBCITesting); return; } @@ -459,7 +463,7 @@ private void Handle_FormCLosing(object sender, FormClosingEventArgs e) // Only exit if ExitOnboardingEarly flag has been set (user selected Exit button) if (!ExitOnboardingEarly) { - Log.Debug("User has requested to close form (Alt + F4) - ignore"); + _logger.LogDebug("User has requested to close form (Alt + F4) - ignore\"); e.Cancel = true; closeReasonIsUserClosing = true; } @@ -532,7 +536,7 @@ private void buttonRetest_Click(object sender, EventArgs e) /// private void modifyUserControlsForDebugMode() { - Log.Debug("SensorForm | modifyUserControlsForDebugMode"); + _logger.LogDebug("SensorForm | modifyUserControlsForDebugMode"); _userControlTestBCIConnections.buttonExit_userControlTestBCIConnections.AutoSize = true; _userControlTestBCIConnections.buttonExit_userControlTestBCIConnections.Font = new Font("Montserrat Medium", 13F); diff --git a/src/Extensions/BCI/Actuators/gTec_SensorUI/UserControlBCISignalCheck.cs b/src/Extensions/BCI/Actuators/gTec_SensorUI/UserControlBCISignalCheck.cs index ed8dac5d..6a82ceb6 100644 --- a/src/Extensions/BCI/Actuators/gTec_SensorUI/UserControlBCISignalCheck.cs +++ b/src/Extensions/BCI/Actuators/gTec_SensorUI/UserControlBCISignalCheck.cs @@ -18,6 +18,7 @@ using ACAT.Extensions.BCI.Common.BCIControl; using Accord.Math; using brainflow; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Drawing; @@ -33,6 +34,8 @@ namespace ACAT.Extensions.BCI.Actuators.gTecSensorUI /// public partial class UserControlBCISignalCheck : UserControl { + private readonly ILogger _logger; + private readonly String _htmlText = "\r\n\r\n \r\n \r\n \r\n \r\n " + "

\r\n" + @@ -142,8 +145,9 @@ public enum BCISignalCheckMode /// /// /// - public UserControlBCISignalCheck() + public UserControlBCISignalCheck(ILogger logger) { + _logger = logger; InitializeComponent(); buttonNext_userControlBCISignalCheck.Enabled = true; @@ -434,7 +438,7 @@ public void ProcessDataSignalCheck(double[,] data, double[,] filteredData) } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, "Exception in ProcessDataSignalCheck"); } } @@ -493,7 +497,7 @@ private void updateRailingTestResult(int chIdx, int railingResultPercentage, boo } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, "Exception in setElectrodeCapMapColors"); } } @@ -512,7 +516,7 @@ public void changeSignalCheckMode(BCISignalCheckMode mode) } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, "Exception in tabControlElectrodeQuality_SelectedIndexChanged"); } } @@ -563,7 +567,7 @@ private void updateSignalChart(int channelIndex, double[] samples, bool scale_pl } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, "Exception in addChartToScreen"); } } @@ -621,7 +625,7 @@ private static bool AppendDataToBuffer2(double[,] data, double[,] inBuffer, int } catch (Exception e) { - Log.Exception(e.Message); + _logger.LogError(e, "Exception in removeColumnsFromChan: {Message}", e.Message); } return result; } @@ -770,7 +774,7 @@ public void handle125Scaling() } catch (Exception ex) { - Log.Exception(ex.Message); + _logger.LogError(e, "Exception in ProcessDataSignalCheck: {Message}", e.Message); } } } diff --git a/src/Extensions/BCI/Actuators/gTec_SensorUI/UserControlErrorBluetoothDisconnected.cs b/src/Extensions/BCI/Actuators/gTec_SensorUI/UserControlErrorBluetoothDisconnected.cs index b15b5fa4..ab0f015a 100644 --- a/src/Extensions/BCI/Actuators/gTec_SensorUI/UserControlErrorBluetoothDisconnected.cs +++ b/src/Extensions/BCI/Actuators/gTec_SensorUI/UserControlErrorBluetoothDisconnected.cs @@ -13,6 +13,7 @@ using ACAT.Core.Utility; using ACAT.Extensions.BCI.Actuators.EEG.EEGDataAcquisition; using ACAT.Extensions.BCI.Actuators.EEG.EEGSettings; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; @@ -27,6 +28,8 @@ namespace ACAT.Extensions.BCI.Actuators.gTecSensorUI /// public partial class UserControlErrorBluetoothDisconnected : UserControl { + private readonly ILogger _logger; + // Timer to update the lists of paired / unpaired devices private Timer _updateTimer; @@ -36,8 +39,9 @@ public partial class UserControlErrorBluetoothDisconnected : UserControl ///

/// Constructor for user control which handles Unicorn bluetooth device connection /// - public UserControlErrorBluetoothDisconnected() + public UserControlErrorBluetoothDisconnected(ILogger logger) { + _logger = logger; InitializeComponent(); // Disable Next button until something in list is selected @@ -70,7 +74,7 @@ private void ListViewDevices_SelectedIndexChanged(object sender, EventArgs e) { BCIActuatorSettings.Settings.GTecDeviceName = selectedDevice; BCIActuatorSettings.Save(); - Log.Debug("Saved BCIGtecActuatorSettings.Settings.GTecDeviceName to ACAT settings: " + BCIActuatorSettings.Settings.GTecDeviceName); + _logger.LogDebug("Saved BCIGtecActuatorSettings.Settings.GTecDeviceName to ACAT settings: " + BCIActuatorSettings.Settings.GTecDeviceName); } } @@ -94,7 +98,7 @@ public void startStopUpdateBluetoothListTimer(bool start) } catch (Exception e) { - Log.Exception("startStopUpdateBluetoothListTimer | Exception: " + e.ToString()); + _logger.LogError(e, "startStopUpdateBluetoothListTimer | Exception when starting: {Exception}", e.ToString()); } } else @@ -112,7 +116,7 @@ public void startStopUpdateBluetoothListTimer(bool start) } catch (Exception e) { - Log.Exception("startStopUpdateBluetoothListTimer | Exception: " + e.ToString()); + _logger.LogError(e, "startStopUpdateBluetoothListTimer | Exception: {Exception}", e.ToString()); } } } @@ -143,7 +147,7 @@ private void UpdateTimer_Tick(object sender, EventArgs e) /// Any extra params sent with bluetooth event request public void bluetoothResultHandler(DAQ_gTecBCI.BluetoothEvent bluetoothEvent, Dictionary eventParams) { - Log.Debug("UserControlErrorBluetoothDisconnected | bluetoothResultHandler | bluetoothEvent: " + bluetoothEvent.ToString()); + _logger.LogDebug("UserControlErrorBluetoothDisconnected | bluetoothResultHandler | bluetoothEvent: " + bluetoothEvent.ToString()); if (!this.IsHandleCreated || this.IsDisposed) { return; } diff --git a/src/Extensions/BCI/Actuators/gTec_SensorUI/Utils.cs b/src/Extensions/BCI/Actuators/gTec_SensorUI/Utils.cs index 14381b0d..db86bac5 100644 --- a/src/Extensions/BCI/Actuators/gTec_SensorUI/Utils.cs +++ b/src/Extensions/BCI/Actuators/gTec_SensorUI/Utils.cs @@ -1,5 +1,6 @@ using ACAT.Core.Utility; using ACATResources; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Windows.Forms; @@ -8,11 +9,13 @@ namespace ACAT.Extensions.BCI.Actuators.gTecSensorUI { internal class Utils { + private static readonly ILogger _logger = LoggerFactory.GetLogger(); + internal static void HandleHelpNavigaion(WebBrowserNavigatingEventArgs e) { var str = e.Url.ToString(); - Log.Debug("Url is [" + str + "]"); + _logger.LogDebug("Url is [" + str + "]"); if (str.ToLower().Contains("blank")) { diff --git a/src/Extensions/BCI/Actuators/gTec_SensorUI/gTecDeviceTester.cs b/src/Extensions/BCI/Actuators/gTec_SensorUI/gTecDeviceTester.cs index b90937da..75d56ebd 100644 --- a/src/Extensions/BCI/Actuators/gTec_SensorUI/gTecDeviceTester.cs +++ b/src/Extensions/BCI/Actuators/gTec_SensorUI/gTecDeviceTester.cs @@ -16,6 +16,7 @@ using ACAT.Extensions.BCI.Actuators.EEG.EEGDataAcquisition; using ACAT.Extensions.BCI.Actuators.EEG.EEGSettings; using ACATResources; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Threading; @@ -29,6 +30,7 @@ namespace ACAT.Extensions.BCI.Actuators.gTecSensorUI /// public class GTecDeviceTester { + private readonly ILogger _logger; public DAQ_gTecBCI gTecBCI = null; /// @@ -123,8 +125,9 @@ public static bool GtecDeviceAvailable /// Tests BCI devices - connections to the hw and data quality /// Displays errors accordingly - After an error, starts at the beginning of the process (testing device connections) /// - public GTecDeviceTester() + public GTecDeviceTester(ILogger logger) { + _logger = logger; // Do not call init function here // Call init function after creating object of this class and linking any necessary event handler (ex: EvtBCIDeviceTestingCompleted) @@ -136,14 +139,14 @@ public GTecDeviceTester() /// public void initialize() { - Log.Debug("gTecDeviceTester | initialize"); + _logger.LogDebug("gTecDeviceTester | initialize"); gTecBCI = (DAQ_gTecBCI)DAQFactory.CreateDAQ(DAQDeviceType.GTecBCI); // Close main form if for some reason it's opened at this point if (_mainForm != null && _mainForm.IsDisposed == false) { - Log.Debug("gTecDeviceTester | _mainForm != null && _mainForm.IsDisposed == false"); + _logger.LogDebug("gTecDeviceTester | _mainForm != null && _mainForm.IsDisposed == false"); _mainForm.Close(); _mainForm.Dispose(); } @@ -155,7 +158,7 @@ public void initialize() } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, "Exception getting Testing_UseSensor setting"); } // If flag set to exit onboarding early, then send event EvtBCIDeviceTestingCompleted and do not continue this function @@ -217,7 +220,7 @@ public void initialize() /// Any extra params sent with bluetooth event request public void bluetoothResultHandler(DAQ_gTecBCI.BluetoothEvent bluetoothEvent, Dictionary eventParams) { - Log.Debug("gTecDeviceTester | bluetoothResultHandler | bluetoothEvent: " + bluetoothEvent.ToString() + " | _currentOnboardingUserState: " + _currentOnboardingUserState.ToString()); + _logger.LogDebug("gTecDeviceTester | bluetoothResultHandler | bluetoothEvent: " + bluetoothEvent.ToString() + " | _currentOnboardingUserState: " + _currentOnboardingUserState.ToString()); switch (bluetoothEvent) { @@ -232,7 +235,7 @@ public void bluetoothResultHandler(DAQ_gTecBCI.BluetoothEvent bluetoothEvent, Di } catch (Exception ex) { - Log.Exception("gTecDeviceTester | bluetoothResultHandler | Exception: " + ex.Message); + _logger.LogError(ex, "gTecDeviceTester | bluetoothResultHandler | Exception: {Message}", ex.Message); } // We were seeing if device could be connected to from the start of the testing process @@ -277,7 +280,7 @@ public void bluetoothResultHandler(DAQ_gTecBCI.BluetoothEvent bluetoothEvent, Di // public async Task startBCIDeviceTesting(int initialDelaySec = 0) { - Log.Debug("gTecDeviceTester | startBCIDeviceTesting | initialDelaySec: " + initialDelaySec.ToString()); + _logger.LogDebug("gTecDeviceTester | startBCIDeviceTesting | initialDelaySec: " + initialDelaySec.ToString()); // Extra time to wait before actually starting testing process (a lot of testing functions can return immediately, so this is for user experience) if (initialDelaySec > 0) @@ -336,7 +339,7 @@ private void updateOnboardingStatus(OnboardingUserState state, Dictionary private void buttonNextHandler(String buttonNextName) { - Log.Debug("gTecDeviceTester | buttonNextHandler | buttonNextName: " + buttonNextName); + _logger.LogDebug("gTecDeviceTester | buttonNextHandler | buttonNextName: " + buttonNextName); switch (buttonNextName) { // Next button clicked from UserControlBluetoothDisconnected @@ -443,14 +446,14 @@ private void buttonNextHandler(String buttonNextName) bool userPassedLastSignalQualityCheck = BCIActuatorSettings.Settings.SignalQuality_PassedLastOverallQualityCheck; if (userPassedLastSignalQualityCheck) { - Log.Debug("User passed most recent signal quality check"); + _logger.LogDebug("User passed most recent signal quality check"); exitBCIOnboarding = true; } // Check if testing parameter set to ignore signal quality check result if (BCIActuatorSettings.Settings.Testing_IgnoreSignalTestResultDuringOnboarding) { - Log.Debug("BCIGtecActuatorSettings.Testing_IgnoreSignalTestResultDuringOnboarding = true"); + _logger.LogDebug("BCIGtecActuatorSettings.Testing_IgnoreSignalTestResultDuringOnboarding = true"); exitBCIOnboarding = true; if (!userPassedLastSignalQualityCheck) @@ -625,7 +628,7 @@ public void Exit(bool lostConnection) /// private void _mainForm_EvtFormClosed(object sender, FormClosedEventArgs e) { - Log.Debug("gTecDeviceTester | _mainForm_EvtFormClosed"); + _logger.LogDebug("gTecDeviceTester | _mainForm_EvtFormClosed"); } /// @@ -668,7 +671,7 @@ private void _mainForm_EvtButtonExitClicked_DEBUG(object sender) } catch (Exception e) { - Log.Exception("_mainForm_EvtButtonExitClicked_DEBUG exception: " + e.ToString()); + _logger.LogError(e, "_mainForm_EvtButtonExitClicked_DEBUG exception: {Exception}", e.ToString()); } } } diff --git a/src/Extensions/BCI/Actuators/openBCI_SensorUI/OpenBCIDeviceTester.cs b/src/Extensions/BCI/Actuators/openBCI_SensorUI/OpenBCIDeviceTester.cs index 9eeb089a..539e8e63 100644 --- a/src/Extensions/BCI/Actuators/openBCI_SensorUI/OpenBCIDeviceTester.cs +++ b/src/Extensions/BCI/Actuators/openBCI_SensorUI/OpenBCIDeviceTester.cs @@ -18,6 +18,7 @@ using ACAT.Extensions.BCI.Actuators.EEG.EEGSettings; using ACAT.Extensions.BCI.Actuators.EEG.EEGUtils; using ACATResources; +using Microsoft.Extensions.Logging; using System; using System.Diagnostics; using System.Drawing; @@ -32,6 +33,8 @@ namespace ACAT.Extensions.BCI.Actuators.openBCISensorUI /// public class OpenBCIDeviceTester { + private readonly ILogger _logger; + /// /// Variables representing all the different states in testing process (state machine) /// diff --git a/src/Extensions/BCI/Actuators/openBCI_SensorUI/UserControlBCIErrorOpticalSensor.cs b/src/Extensions/BCI/Actuators/openBCI_SensorUI/UserControlBCIErrorOpticalSensor.cs index 79ce9ced..08dc6c4f 100644 --- a/src/Extensions/BCI/Actuators/openBCI_SensorUI/UserControlBCIErrorOpticalSensor.cs +++ b/src/Extensions/BCI/Actuators/openBCI_SensorUI/UserControlBCIErrorOpticalSensor.cs @@ -13,6 +13,7 @@ using ACAT.Core.Utility; using ACAT.Extensions.BCI.Actuators.EEG.EEGSettings; using ACATResources; +using Microsoft.Extensions.Logging; using System; using System.IO; using System.Linq; @@ -26,6 +27,7 @@ namespace ACAT.Extensions.BCI.Actuators.openBCISensorUI /// public partial class UserControlBCIErrorOpticalSensor : UserControl { + private readonly ILogger _logger; /// /// Unique ID for this step /// @@ -58,8 +60,9 @@ public partial class UserControlBCIErrorOpticalSensor : UserControl /// /// User Control Form for the output signals from sensor /// - public UserControlBCIErrorOpticalSensor(String stepId) + public UserControlBCIErrorOpticalSensor(String stepId, ILogger logger = null) { + _logger = logger ?? LoggerFactory.GetLogger(); InitializeComponent(); _stepId = stepId; @@ -147,7 +150,7 @@ public void updateOpticalSensorDataPlot(double[] newData) } catch (Exception e) { - Log.Exception(e); + _logger.LogError(e, e.ToString()); } } diff --git a/src/Extensions/BCI/Actuators/openBCI_SensorUI/Utils.cs b/src/Extensions/BCI/Actuators/openBCI_SensorUI/Utils.cs index 37fd00d3..9ab1872a 100644 --- a/src/Extensions/BCI/Actuators/openBCI_SensorUI/Utils.cs +++ b/src/Extensions/BCI/Actuators/openBCI_SensorUI/Utils.cs @@ -1,5 +1,6 @@ using ACAT.Core.Utility; using ACATResources; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Windows.Forms; @@ -8,11 +9,13 @@ namespace ACAT.Extensions.BCI.Actuators.openBCISensorUI { internal class Utils { + private static readonly ILogger _logger = LoggerFactory.GetLogger(); + internal static void HandleHelpNavigaion(WebBrowserNavigatingEventArgs e) { var str = e.Url.ToString(); - Log.Debug("Url is [" + str + "]"); + _logger.LogDebug("Url is [" + str + "]"); if (str.ToLower().Contains("blank")) { diff --git a/src/Extensions/BCI/Common/AnimationSharp/AnimationSharpManagerV2.cs b/src/Extensions/BCI/Common/AnimationSharp/AnimationSharpManagerV2.cs index fddba958..d703bedc 100644 --- a/src/Extensions/BCI/Common/AnimationSharp/AnimationSharpManagerV2.cs +++ b/src/Extensions/BCI/Common/AnimationSharp/AnimationSharpManagerV2.cs @@ -1,4 +1,4 @@ -//////////////////////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////////////////// // // Copyright 2013-2019; 2023 Intel Corporation // SPDX-License-Identifier: Apache-2.0 @@ -19,6 +19,7 @@ using ACAT.Extensions.BCI.Common.BCIControl; using ACATResources; +using Microsoft.Extensions.Logging; using SharpDX.Direct2D1; using SharpDX.Direct3D11; using SharpDX.DirectWrite; @@ -40,6 +41,7 @@ namespace ACAT.Extensions.BCI.Common.AnimationSharp /// public class AnimationSharpManagerV2 { + private readonly ILogger _logger; /// /// Current active Keyboard Layout /// @@ -575,7 +577,7 @@ public void CancelCalibration() try { AbortTimers(); } catch (Exception ex) - { Log.Debug("BCI LOG | Error in BCI CancelCalibration(): " + ex.Message); } + { _logger.LogDebug("BCI LOG | Error in BCI CancelCalibration(): " + ex.Message); } CloseSequencesLog(); _sessionMode = BCIModes.TYPING; ChangeColorButtons(_flashingSequenceBoxList[0].ToList(), false, true, 0); @@ -656,7 +658,7 @@ public void CreateSequencesLog(string path, string name = null) } catch (Exception ex) { - Log.Debug("BCI LOG | Exception in CreateSequencesLog() " + ex.Message); + _logger.LogDebug("BCI LOG | Exception in CreateSequencesLog() " + ex.Message); } } @@ -683,7 +685,7 @@ public void DrawMainLayout() } catch (Exception es) { - Log.Exception("BCI LOG | Exception sharpDX in DrawMainLayout() " + es.Message); + _logger.LogError("BCI LOG | Exception sharpDX in DrawMainLayout() " + es.Message); } } @@ -720,7 +722,7 @@ public void Init(Form form) } catch (Exception ex) { - Log.Exception("BCI LOG | Exception occurred during initialization: " + ex.Message); + _logger.LogError("BCI LOG | Exception occurred during initialization: " + ex.Message); return; } @@ -784,7 +786,7 @@ public void OnFormClosing() catch (Exception es) { AbortTimers(); - Log.Debug("BCI LOG | Exception occurred during closing SharpDX: " + es.Message); + _logger.LogDebug("BCI LOG | Exception occurred during closing SharpDX: " + es.Message); } DisposeObjects(); } @@ -847,7 +849,7 @@ public void ResumeAfterPause() if (SuspendAnimations) { _requestProbabilities = true; - try { AbortTimers(); } catch (Exception ex) { Log.Debug("BCI LOG | Exception ResumeAfterPause: " + ex.Message); } + try { AbortTimers(); } catch (Exception ex) { _logger.LogDebug("BCI LOG | Exception ResumeAfterPause: " + ex.Message); } Reset(); } } @@ -906,7 +908,7 @@ public void SetDataObjectsSharpDX(Dictionary, string> boxesData, L } catch (Exception) { - //Log.Exception("BCI LOG | Exception _rectProbBarsBox: " + es.Message); + //_logger.LogError("BCI LOG | Exception _rectProbBarsBox: " + es.Message); } indexBox += 1; } @@ -1002,14 +1004,14 @@ private async Task ActuateWidgetFromID(int id) } catch (Exception ex) { - Log.Exception("BCI LOG | Error actuating Button: " + ex.Message); + _logger.LogError("BCI LOG | Error actuating Button: " + ex.Message); } await Task.Delay(1); } private void ActuatorRequestEndCalibration() { - Log.Debug("BCI LOG | EndCalibration | Section " + _ScanningSection); + _logger.LogDebug("BCI LOG | EndCalibration | Section " + _ScanningSection); CloseSequencesLog(); RequestToUpdateTextBox(AnimationManagerUtils.StatusMessageAnalyzingCalibrationData + " . ."); var bciCalibrationEnd = new BCICalibrationEnd(); @@ -1034,7 +1036,7 @@ private void ActuatorRequestEndCalibration() } catch (Exception es) { - Log.Exception("BCI LOG | Exception occurred during request to Actuator in ENDCAL: " + es.Message); + _logger.LogError("BCI LOG | Exception occurred during request to Actuator in ENDCAL: " + es.Message); } var strCalEnd = bciCalibrationEnd; _actuator?.IoctlRequest((int)OpCodes.CalibrationEnd, strCalEnd); @@ -1087,7 +1089,7 @@ private void ActuatorRequestEndRepetitionCalibration() } catch (Exception es) { - Log.Exception("BCI LOG | Exception occurred during request to Actuator in CAl: " + es.Message); + _logger.LogError("BCI LOG | Exception occurred during request to Actuator in CAl: " + es.Message); } var strCalRepEnd = bciCalibrationInput; _actuator?.IoctlRequest((int)OpCodes.CalibrationEndRepetition, strCalRepEnd); @@ -1117,7 +1119,7 @@ private void ActuatorRequestEndRepetitionTyping() } catch (Exception es) { - Log.Exception("BCI LOG | Exception occurred during request to Actuator in TYPE 3: " + es.Message); + _logger.LogError("BCI LOG | Exception occurred during request to Actuator in TYPE 3: " + es.Message); } } else @@ -1140,14 +1142,14 @@ private void ActuatorRequestEndRepetitionTyping() } catch (Exception es) { - Log.Exception("BCI LOG | Exception occurred during request to Actuator in TYPE 1: " + es.Message); + _logger.LogError("BCI LOG | Exception occurred during request to Actuator in TYPE 1: " + es.Message); } } bciTypingRepetitionEnd.ScanningSection = _ScanningSection; } catch (Exception es) { - Log.Exception("BCI LOG | Exception occurred during request to Actuator in TYPE: " + es.Message); + _logger.LogError("BCI LOG | Exception occurred during request to Actuator in TYPE: " + es.Message); } var strTypRepEnd = bciTypingRepetitionEnd; _actuator?.IoctlRequest((int)OpCodes.TypingEndRepetition, strTypRepEnd); @@ -1160,7 +1162,7 @@ private void ActuatorRequestMarker(string data) private void ActuatorRequestTriggerTestFinish() { - Log.Debug("BCI LOG | TriggerTestFinish "); + _logger.LogDebug("BCI LOG | TriggerTestFinish "); _triggerTestActive = false; Thread.Sleep(200); _actuator?.IoctlRequest((int)OpCodes.TriggerTestStop, string.Empty); @@ -1216,7 +1218,7 @@ private void ActuatorRequestValueProbs() } catch (Exception ex) { - Log.Exception("BCI LOG | Exception in ActuatorRequestValueProbs: " + ex.Message); + _logger.LogError("BCI LOG | Exception in ActuatorRequestValueProbs: " + ex.Message); } } @@ -1230,7 +1232,7 @@ private void ActuatorResponseCalibrationEndRepetitionResult(object response) } catch (Exception ex) { - Log.Exception("BCI LOG | Exception in ActuatorResponseCalibrationEndRepetitionResult: " + ex.Message); + _logger.LogError("BCI LOG | Exception in ActuatorResponseCalibrationEndRepetitionResult: " + ex.Message); SensorErrorState = new BCIError() { ErrorCode = BCIErrorCodes.OpticalSensorError_UnknownException, ErrorMessage = StringResources.SensorError }; AnimationManagerUtils.StatusSignal = SignalStatus.SIGNAL_KO; } @@ -1238,7 +1240,7 @@ private void ActuatorResponseCalibrationEndRepetitionResult(object response) private void ActuatorResponseCalibrationResult(object response) { - Log.Debug("BCI LOG | CalibrationResult | AUC " + _AUC + " | Section " + _ScanningSection); + _logger.LogDebug("BCI LOG | CalibrationResult | AUC " + _AUC + " | Section " + _ScanningSection); var bciCalibrationResult = response as BCICalibrationResult; _AUC = bciCalibrationResult.AUC; if (bciCalibrationResult.CalibrationSuccessful)//Flags to let know the timer thread once is at the final process to do either one or the other event trigger @@ -1252,7 +1254,7 @@ private void ActuatorResponseSendParameters(object response) { try { - Log.Debug("BCI LOG | SendParameters | Section " + _ScanningSection); + _logger.LogDebug("BCI LOG | SendParameters | Section " + _ScanningSection); var bciParameters = response as BCIParameters; _DelayToGetReady = bciParameters.Scanning_DelayToGetReady; _MinimumProgressBarsValue = (bciParameters.MinProbablityToDisplayBarOnTyping); @@ -1290,7 +1292,7 @@ private void ActuatorResponseSendParameters(object response) } catch (Exception ex) { - Log.Exception("BCI LOG | ActuatorResponseSendParameters | Exception | " + ex.Message); + _logger.LogError("BCI LOG | ActuatorResponseSendParameters | Exception | " + ex.Message); _CalibrationTargetCount = 60; _CalibrationIterationsPerTarget = 2; } @@ -1298,12 +1300,12 @@ private void ActuatorResponseSendParameters(object response) private void ActuatorResponseStartSessionResult(object response) { - Log.Debug("BCI LOG | StartSessionResult | Section " + _ScanningSection); + _logger.LogDebug("BCI LOG | StartSessionResult | Section " + _ScanningSection); var bciSessionResult = response as BCIStartSessionResult; SensorErrorState = bciSessionResult.Error; CreateSequencesLog(bciSessionResult.SessionDirectory); - Log.Debug("BCI LOG | Scanning Log created in: | Path " + bciSessionResult.SessionDirectory); - Log.Debug("BCI LOG | bciSessionResult.Error | Status " + bciSessionResult.Error); + _logger.LogDebug("BCI LOG | Scanning Log created in: | Path " + bciSessionResult.SessionDirectory); + _logger.LogDebug("BCI LOG | bciSessionResult.Error | Status " + bciSessionResult.Error); //_readStartSessionResult flag is for Eyes/Clsoed Calibration form that also has the start session request with this we avoid the event handler to run scanning when Eyes Form is active and here has the event subscribed active if (_readStartSessionResult && !_triggerTestActive) { @@ -1323,7 +1325,7 @@ private void ActuatorResponseTriggerTestResult(object response) { var bciTriggerTestResult = response as BCITriggerTestResult; CloseSequencesLog(); - Log.Debug("BCI LOG | TriggerTestResult | DutyCycleAvg " + bciTriggerTestResult.DutyCycleAvg.ToString()); + _logger.LogDebug("BCI LOG | TriggerTestResult | DutyCycleAvg " + bciTriggerTestResult.DutyCycleAvg.ToString()); //Trigger event to call a UI message box from a higher level _mainForm.Invoke(new MethodInvoker(delegate { @@ -1495,7 +1497,7 @@ private void ChangeColorButtons(List buttonIDs, bool highlightOn, bool useE } catch (Exception es) { - Log.Exception("BCI LOG | Exception sharpDX ChangeColorButtons: " + es.Message); + _logger.LogError("BCI LOG | Exception sharpDX ChangeColorButtons: " + es.Message); } } @@ -1535,7 +1537,7 @@ private void ChangeColorButtonsSequence(List buttonIDs, SolidColorBrush col } catch (Exception ex) { - Log.Exception("BCI LOG | Exception sharpDX ChangeColorButtonsSequence: " + ex.Message); + _logger.LogError("BCI LOG | Exception sharpDX ChangeColorButtonsSequence: " + ex.Message); } } @@ -1637,7 +1639,7 @@ private void DrawFocalPointsFor(BCIModes bCIModes) } catch (Exception ex) { - Log.Exception("BCI LOG | Exception sharpDX DrawFocalPointsFor: " + ex.Message); + _logger.LogError("BCI LOG | Exception sharpDX DrawFocalPointsFor: " + ex.Message); } } @@ -1698,7 +1700,7 @@ private void DrawMatrix() } catch (Exception ex) { - Log.Exception("BCI LOG | Exception sharpDX in DrawMatrix: " + ex.Message); + _logger.LogError("BCI LOG | Exception sharpDX in DrawMatrix: " + ex.Message); } } @@ -1737,7 +1739,7 @@ private void EnsureTimersAreStoped() } catch (Exception ex) { - Log.Exception("BCI LOG | Exception in EnsureTimersAreStoped: " + ex.Message); + _logger.LogError("BCI LOG | Exception in EnsureTimersAreStoped: " + ex.Message); } } @@ -1803,7 +1805,7 @@ private ButtonsData FindButtomFromId(int id) } catch (Exception es) { - Log.Exception("BCI LOG | Exception occurred findButtomFromId: " + es.Message); + _logger.LogError("BCI LOG | Exception occurred findButtomFromId: " + es.Message); return new ButtonsData(); } } @@ -1832,7 +1834,7 @@ private int FindIndexFromID(int id) } catch (Exception es) { - Log.Exception("BCI LOG | Exception findIndexFromID: " + es.Message); + _logger.LogError("BCI LOG | Exception findIndexFromID: " + es.Message); } } return 0; @@ -1948,7 +1950,7 @@ private bool PlayBoxSequences() } catch (Exception ex) { - Log.Exception("BCI LOG | Error in isBoxEmpty: " + ex.Message); + _logger.LogError("BCI LOG | Error in isBoxEmpty: " + ex.Message); return true; } } @@ -2134,7 +2136,7 @@ private void Reset(bool delayAfterLayoutChange = false) } catch (Exception er) { - Log.Exception("BCI LOG | Exception setDataObjectsSharpDX: " + er.Message); + _logger.LogError("BCI LOG | Exception setDataObjectsSharpDX: " + er.Message); } _UpdateButtonsStrings = true; Thread.Sleep(250); @@ -2174,7 +2176,7 @@ private async Task ResetWaitingDelay() } catch (Exception ex) { - Log.Exception("BCI LOG | Exception in ResetWaitingDelay: " + ex.Message); + _logger.LogError("BCI LOG | Exception in ResetWaitingDelay: " + ex.Message); } await Task.Delay(200); DrawMainLayout(); @@ -2281,7 +2283,7 @@ private void SetValueProbabilityBars() } catch (Exception es) { - Log.Exception("BCI LOG | Exception occurred during Drawing progress bars probs: " + es.Message); + _logger.LogError("BCI LOG | Exception occurred during Drawing progress bars probs: " + es.Message); } } if (_showProbabilityIndicator) @@ -2296,7 +2298,7 @@ private void SetValueProbabilityBars() } catch (Exception es) { - Log.Exception("BCI LOG | Exception occurred during Drawing progress bars: " + es.Message); + _logger.LogError("BCI LOG | Exception occurred during Drawing progress bars: " + es.Message); } } @@ -2670,9 +2672,9 @@ private void TrialTimer_Tick(object sender, MicroTimerEventArgs e) _trialTimer.Stop(); if (SensorErrorState.ErrorCode != BCIErrorCodes.Status_Ok)//if and error was returned then it wont continue with animations { - Log.Debug("BCI LOG | Error entered in loop | ErrorCode: " + SensorErrorState.ErrorCode); + _logger.LogDebug("BCI LOG | Error entered in loop | ErrorCode: " + SensorErrorState.ErrorCode); SoundManager.playSound(SoundManager.SoundType.CaregiverAttention); - Log.Debug("BCI LOG | SoundManager.playSound "); + _logger.LogDebug("BCI LOG | SoundManager.playSound "); /*while (true) { Thread.Sleep(500); @@ -2699,7 +2701,7 @@ private void TrialTimer_Tick(object sender, MicroTimerEventArgs e) } catch (Exception ex) { - Log.Exception("BCI LOG | Error in _endCalibration: " + ex.Message); + _logger.LogError("BCI LOG | Error in _endCalibration: " + ex.Message); } } if (_repeatCalibration) @@ -2717,7 +2719,7 @@ private void TrialTimer_Tick(object sender, MicroTimerEventArgs e) } catch (Exception ex) { - Log.Exception("BCI LOG | Exception TrialTimer_Tick: " + ex.Message); + _logger.LogError("BCI LOG | Exception TrialTimer_Tick: " + ex.Message); } } @@ -2769,7 +2771,7 @@ private void TriggerTestTimer_Tick(object sender, MicroTimerEventArgs e) } catch (Exception ex) { - Log.Exception("BCI LOG | Exception TriggerTestTimer_Tick: " + ex.Message); + _logger.LogError("BCI LOG | Exception TriggerTestTimer_Tick: " + ex.Message); } } @@ -2843,7 +2845,7 @@ private async Task UpdateStringsFromButtons() } catch (Exception es) { - Log.Exception("BCI LOG | Exception occurred during updating strings from buttons: " + es.Message); + _logger.LogError("BCI LOG | Exception occurred during updating strings from buttons: " + es.Message); await Task.Delay(2000); } } @@ -2857,8 +2859,8 @@ private void ValidateSensorErrorState(BCIError bCIError) if (bCIError.ErrorCode != BCIErrorCodes.Status_Ok) { RequestToUpdateTextBox(bCIError.ErrorMessage + " ( Error Code: " + (int)bCIError.ErrorCode + " )"); - Log.Debug("BCI LOG | ErrorCode received " + (int)bCIError.ErrorCode); - Log.Debug("BCI LOG | ErrorMessage received " + bCIError.ErrorMessage); + _logger.LogDebug("BCI LOG | ErrorCode received " + (int)bCIError.ErrorCode); + _logger.LogDebug("BCI LOG | ErrorMessage received " + bCIError.ErrorMessage); } } diff --git a/src/Extensions/BCI/Common/AnimationSharp/Utility/AnimationManagerUtils.cs b/src/Extensions/BCI/Common/AnimationSharp/Utility/AnimationManagerUtils.cs index 63250dbb..139c08b4 100644 --- a/src/Extensions/BCI/Common/AnimationSharp/Utility/AnimationManagerUtils.cs +++ b/src/Extensions/BCI/Common/AnimationSharp/Utility/AnimationManagerUtils.cs @@ -1,4 +1,4 @@ -//////////////////////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////////////////// // // Copyright 2013-2019; 2023 Intel Corporation // SPDX-License-Identifier: Apache-2.0 @@ -11,6 +11,7 @@ using ACAT.Core.WidgetManagement; using ACAT.Core.WidgetManagement.Interfaces; using ACAT.Extensions.BCI.Common.BCIControl; +using Microsoft.Extensions.Logging; using SharpDX.Direct2D1; using System; using System.Collections.Generic; @@ -26,6 +27,7 @@ namespace ACAT.Extensions.BCI.Common.AnimationSharp.Utility /// public class AnimationManagerUtils { + private static readonly ILogger _logger = LoggerFactory.GetLogger(); /// /// String messages for BCI /// @@ -103,7 +105,7 @@ public static List[] ExtractButtonText(List controls, string co } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, ex.ToString()); } configNodes = null; return btnStringsAll; @@ -157,7 +159,7 @@ public static List[] GetBoxWidgets(List widgets, string configFi } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, ex.ToString()); } configNodes = null; return widgetsBox; @@ -185,7 +187,7 @@ public static List[] GetBoxWidgetsList(KeyValuePair, strin } catch (Exception ex) { - Log.Exception("Error in GetBoxWidgetsList: " + ex.Message); + _logger.LogError("Error in GetBoxWidgetsList: " + ex.Message); return new List[totalAmountOfBoxes]; } return widgets; @@ -213,7 +215,7 @@ public static List[] GetButtonDataList(KeyValuePair, } catch (Exception ex) { - Log.Exception("Error in GetButtonDataList: " + ex.Message); + _logger.LogError("Error in GetButtonDataList: " + ex.Message); return new List[totalAmountOfBoxes]; } return buttonDataList; @@ -287,7 +289,7 @@ public static List[] GetButtonsOffsetList(KeyValuePair, strin } catch (Exception ex) { - Log.Exception("Error in GetButtonsOffsetList: " + ex.Message); + _logger.LogError("Error in GetButtonsOffsetList: " + ex.Message); return new List[totalAmountOfBoxes]; } return offsetStrings; @@ -319,7 +321,7 @@ public static List[] GetButtonsStringsList(Dictionary, str } catch (Exception ex) { - Log.Exception("Error in GetButtonsStringsList: " + ex.Message); + _logger.LogError("Error in GetButtonsStringsList: " + ex.Message); return new List[totalAmountOfBoxes]; } return buttonsStringsList; @@ -406,7 +408,7 @@ public static List[] GetControlsBtns(KeyValuePair[totalAmountOfBoxes]; flashingSequenceList = new List[totalAmountOfBoxes]; return new List[totalAmountOfBoxes]; @@ -449,7 +451,7 @@ public static List[] GetControlsButtons(List cont } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, ex.ToString()); } configNodes = null; return ctrlBtnsAll; @@ -486,7 +488,7 @@ public static List[] GetFlashingSequenceIDBoxList(List[] widgetsDat } catch (Exception ex) { - Log.Exception("Error in GetFlashingSequenceIDBoxList: " + ex.Message); + _logger.LogError("Error in GetFlashingSequenceIDBoxList: " + ex.Message); return new List[totalAmountOfBoxes]; } return flashingSequenceIDBoxList; @@ -524,7 +526,7 @@ public static Dictionary GetLettersProbs(List } catch (Exception es) { - Log.Exception("Exception geting values probs " + es); + _logger.LogError("Exception geting values probs " + es); } return nextProbs; } @@ -579,7 +581,7 @@ public static Dictionary GetLettersProbs(List controls, boo } catch (Exception ex) { - Log.Exception("Exception in getLettersProbs: " + ex.Message.ToString()); + _logger.LogError("Exception in getLettersProbs: " + ex.Message.ToString()); return _ = new Dictionary(); } return nextProbs; @@ -642,7 +644,7 @@ public static List[] GetMatrixButtons(List controls, Rende } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, ex.ToString()); } configNodes = null; return matrixButtonList; @@ -685,7 +687,7 @@ public static List[] GetOffset(List widgets, string configFilePath, } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, ex.ToString()); } configNodes = null; return offsets; @@ -770,7 +772,7 @@ public static List[] GetSequences(List controls, string configFi } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, ex.ToString()); } configNodes = null; return flashingSeqAll; @@ -838,7 +840,7 @@ public static Dictionary GetWordsProbs(List c } catch (Exception es) { - Log.Exception("Exception geting values probs " + es); + _logger.LogError("Exception geting values probs " + es); } return nextProbs; } diff --git a/src/Extensions/BCI/Common/AnimationSharp/Utility/BCIUtils.cs b/src/Extensions/BCI/Common/AnimationSharp/Utility/BCIUtils.cs index 7f2bbddf..8d3379ca 100644 --- a/src/Extensions/BCI/Common/AnimationSharp/Utility/BCIUtils.cs +++ b/src/Extensions/BCI/Common/AnimationSharp/Utility/BCIUtils.cs @@ -7,6 +7,7 @@ using ACAT.Core.Utility; using ACAT.Extensions.BCI.Common.BCIControl; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; @@ -16,6 +17,14 @@ namespace ACAT.Extensions.BCI.Common.AnimationSharp.Utility { public class BCIUtils { + private readonly ILogger _logger; + private readonly ILogger _logger; + + public BCIUtils(ILogger logger = null) + { + _logger = logger ?? LoggerFactory.GetLogger(); + } + /// /// Array of ID to be used as targe for calibration /// @@ -94,7 +103,7 @@ public string GetEntryLogStr(BCIModes bCIModes, BCIScanSections bCIScanSections, } catch (Exception es) { - Log.Exception("Error no highlight log saved: " + es); + _logger.LogError(es, "Error no highlight log saved: " + es); } return sb.ToString(); } diff --git a/src/Extensions/BCI/Common/AnimationSharp/Utility/CachedLogBCI.cs b/src/Extensions/BCI/Common/AnimationSharp/Utility/CachedLogBCI.cs index 68d9a381..56bd830a 100644 --- a/src/Extensions/BCI/Common/AnimationSharp/Utility/CachedLogBCI.cs +++ b/src/Extensions/BCI/Common/AnimationSharp/Utility/CachedLogBCI.cs @@ -6,6 +6,7 @@ //////////////////////////////////////////////////////////////////////////// using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.IO; @@ -18,6 +19,7 @@ namespace ACAT.Extensions.BCI.Common.AnimationSharp.Utility /// public class CachedLogBCI { + private readonly ILogger _logger; /// /// Full path to the log file /// @@ -35,8 +37,9 @@ public class CachedLogBCI /// private readonly string LogFileName; - public CachedLogBCI(string baseFileName, string baseDirPath = null) + public CachedLogBCI(string baseFileName, string baseDirPath = null, ILogger logger = null) { + _logger = logger ?? LoggerFactory.GetLogger(); if (!string.IsNullOrEmpty(baseFileName)) { LogFileName = baseFileName + ".csv"; @@ -98,7 +101,7 @@ private void Save(string logFilePath, StreamWriter streamWriter) } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex, ex.ToString()); } finally { diff --git a/src/Extensions/BCI/Common/AnimationSharp/Utility/SharpDXUtils.cs b/src/Extensions/BCI/Common/AnimationSharp/Utility/SharpDXUtils.cs index 12ec26be..7ed4ff2f 100644 --- a/src/Extensions/BCI/Common/AnimationSharp/Utility/SharpDXUtils.cs +++ b/src/Extensions/BCI/Common/AnimationSharp/Utility/SharpDXUtils.cs @@ -1,4 +1,4 @@ -//////////////////////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////////////////// // // Copyright 2013-2019; 2023 Intel Corporation // SPDX-License-Identifier: Apache-2.0 @@ -9,6 +9,7 @@ using ACAT.Core.WidgetManagement; using ACAT.Core.WidgetManagement.Interfaces; using ACAT.Extensions.BCI.Common.BCIControl; +using Microsoft.Extensions.Logging; using SharpDX.Direct2D1; using SharpDX.DirectWrite; using SharpDX.Mathematics.Interop; @@ -23,6 +24,7 @@ namespace ACAT.Extensions.BCI.Common.AnimationSharp.Utility { public class SharpDXUtils { + private static readonly ILogger _logger = LoggerFactory.GetLogger(); /// /// Get the border color from the Theme xml file /// @@ -100,7 +102,7 @@ public static List[] GetListButtonTextFormat(KeyValuePair[totalAmountOfBoxes]; } return buttonTextFormatList; @@ -144,7 +146,7 @@ public static List[] GetRecButtons(List controls, string } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, ex.ToString()); } configNodes = null; return rectBtns; @@ -188,7 +190,7 @@ public static Dictionary[] GetRecProbabilityBars(List GetRecProbabilityBarsBox(List[] GetRecRoundButtons(List controls } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, ex.ToString()); } configNodes = null; return rectBtns; @@ -312,7 +314,7 @@ public static List[] GetRectanglesButtonsList(KeyValuePair[totalAmountOfBoxes]; } return rectanglesButtonsList; @@ -340,7 +342,7 @@ public static List[] GetRectanglesButtonsRoundList(KeyValuePai } catch (Exception ex) { - Log.Exception("Error in GetRectanglesButtonsRoundList: " + ex.Message); + _logger.LogError("Error in GetRectanglesButtonsRoundList: " + ex.Message); return new List[totalAmountOfBoxes]; } return rectanglesButtonsRoundList; @@ -386,7 +388,7 @@ public static RawRectangleF GetRectanglesCRG(Dictionary, string> b } catch (Exception ex) { - Log.Exception("Error in GetRectanglesCRG: " + ex.Message); + _logger.LogError("Error in GetRectanglesCRG: " + ex.Message); return rectangleExtraButtonCRG; } return rectangleExtraButtonCRG; @@ -418,7 +420,7 @@ public static RawRectangleF GetRectanglesTriggerBox(Dictionary, st } catch (Exception ex) { - Log.Exception("Error in GetRectanglesTriggerBox: " + ex.Message); + _logger.LogError("Error in GetRectanglesTriggerBox: " + ex.Message); return rectangleExtraButton; } return rectangleExtraButton; @@ -488,7 +490,7 @@ public static List[] GetTextFormat(List widgets, string conf } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, ex.ToString()); } configNodes = null; return textFormats; @@ -511,7 +513,7 @@ public static TextFormat GetTextFormatCRG(List widgets, SharpDX.DirectWr } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, ex.ToString()); textFormatCRG = GetDefaultButtonTextFormat(directWriteFactory, TextAlignment.Center); } return textFormatCRG; diff --git a/src/Extensions/BCI/Common/BCIInterfaceUtilities/CalibrationEyesSettingsForm.cs b/src/Extensions/BCI/Common/BCIInterfaceUtilities/CalibrationEyesSettingsForm.cs index 80c4fe79..fd8b6127 100644 --- a/src/Extensions/BCI/Common/BCIInterfaceUtilities/CalibrationEyesSettingsForm.cs +++ b/src/Extensions/BCI/Common/BCIInterfaceUtilities/CalibrationEyesSettingsForm.cs @@ -10,6 +10,7 @@ using ACAT.Core.Utility; using ACAT.Extensions.BCI.Common.BCIControl; using ACATResources; +using Microsoft.Extensions.Logging; using System; using System.Text.RegularExpressions; using System.Threading; @@ -32,6 +33,11 @@ public partial class CalibrationEyesSettingsForm : Form public ResultParams ResultParameters = new(); + /// + /// Logger instance + /// + private readonly ILogger _logger; + /// /// Main object of the actuator /// @@ -59,8 +65,9 @@ public partial class CalibrationEyesSettingsForm : Form #endregion Properties - public CalibrationEyesSettingsForm() + public CalibrationEyesSettingsForm(ILogger logger) { + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); InitializeComponent(); this.WindowState = FormWindowState.Maximized; Screen primaryScreen = Screen.PrimaryScreen; @@ -181,7 +188,7 @@ private void textBoxInterval_TextChanged(object sender, EventArgs e) } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex, "Error parsing interval value"); _TempInterval = 5000; textBoxInterval.Text = _TempInterval.ToString(); } @@ -204,7 +211,7 @@ private void textBoxReps_TextChanged(object sender, EventArgs e) } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex, "Error parsing repetitions value"); _TempMaxRepetitions = 10; textBoxReps.Text = _TempMaxRepetitions.ToString(); } @@ -250,7 +257,7 @@ private void OnFormClosing() } catch (Exception ex) { - Log.Exception("Error in EyesSettingsForm: " + ex.Message); + _logger.LogError(ex, "Error in EyesSettingsForm"); } if (_bciActuator != null) { @@ -295,7 +302,7 @@ private bool TextChangedInput(TextBox textBox) } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex, "Error in TextChangedInput"); } return inputReplace; } diff --git a/src/Extensions/BCI/Common/BCIInterfaceUtilities/ConfirmBoxCalibrationModes.cs b/src/Extensions/BCI/Common/BCIInterfaceUtilities/ConfirmBoxCalibrationModes.cs index cea5f029..6f913e18 100644 --- a/src/Extensions/BCI/Common/BCIInterfaceUtilities/ConfirmBoxCalibrationModes.cs +++ b/src/Extensions/BCI/Common/BCIInterfaceUtilities/ConfirmBoxCalibrationModes.cs @@ -11,6 +11,7 @@ using ACAT.Core.WidgetManagement; using ACAT.Extensions.BCI.Common.BCIControl; using ACATResources; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Drawing; @@ -28,6 +29,11 @@ namespace ACAT.Extensions.BCI.Common.BCIInterfaceUtilities public partial class ConfirmBoxCalibrationModes : Form { #region Properties + /// + /// Logger instance + /// + private readonly ILogger _logger; + /// /// Main object of the actuator /// @@ -73,8 +79,9 @@ public partial class ConfirmBoxCalibrationModes : Form /// /// Confirm Box with multiple results /// - public ConfirmBoxCalibrationModes() + public ConfirmBoxCalibrationModes(ILogger logger) { + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); InitializeComponent(); Load += ConfirmBoxCalibrationModes_Load; @@ -140,7 +147,7 @@ private void ButtonBeginACAT_Click(object sender, EventArgs e) private void ButtonCalibrate_Click(object sender, EventArgs e) { - Log.Debug("BCI LOG | Mode Selected: " + _scanSectionsSelected); + _logger.LogDebug("BCI LOG | Mode Selected: {ScanSection}", _scanSectionsSelected); _ = new BCISimpleParameters(); try { @@ -149,7 +156,7 @@ private void ButtonCalibrate_Click(object sender, EventArgs e) switch (scannerRoundedButtonControl.Name) { case var _ when scannerRoundedButtonControl.Name.Contains("Box"): - Log.Debug("BCI LOG | Calibrate Button Selected: " + BCIScanSections.Box); + _logger.LogDebug("BCI LOG | Calibrate Button Selected: {Section}", BCIScanSections.Box); if (_scanSectionsSelected == BCIScanSections.Box) parameters = GetCalibrationParameters(); else @@ -158,7 +165,7 @@ private void ButtonCalibrate_Click(object sender, EventArgs e) break; case var _ when scannerRoundedButtonControl.Name.Contains("Sentence"): - Log.Debug("BCI LOG | Calibrate Button Selected " + BCIScanSections.Sentence); + _logger.LogDebug("BCI LOG | Calibrate Button Selected {Section}", BCIScanSections.Sentence); if (_scanSectionsSelected == BCIScanSections.Sentence) parameters = GetCalibrationParameters(); else @@ -167,7 +174,7 @@ private void ButtonCalibrate_Click(object sender, EventArgs e) break; case var _ when scannerRoundedButtonControl.Name.Contains("KeyboardL"): - Log.Debug("BCI LOG | Calibrate Button Selected " + BCIScanSections.KeyboardL); + _logger.LogDebug("BCI LOG | Calibrate Button Selected {Section}", BCIScanSections.KeyboardL); if (_scanSectionsSelected == BCIScanSections.KeyboardL) parameters = GetCalibrationParameters(); else @@ -176,7 +183,7 @@ private void ButtonCalibrate_Click(object sender, EventArgs e) break; case var _ when scannerRoundedButtonControl.Name.Contains("Word"): - Log.Debug("BCI LOG | Calibrate Button Selected " + BCIScanSections.Word); + _logger.LogDebug("BCI LOG | Calibrate Button Selected {Section}", BCIScanSections.Word); if (_scanSectionsSelected == BCIScanSections.Word) parameters = GetCalibrationParameters(); else @@ -185,7 +192,7 @@ private void ButtonCalibrate_Click(object sender, EventArgs e) break; case var _ when scannerRoundedButtonControl.Name.Contains("KeyboardR"): - Log.Debug("BCI LOG | Calibrate Button Selected " + BCIScanSections.KeyboardR); + _logger.LogDebug("BCI LOG | Calibrate Button Selected {Section}", BCIScanSections.KeyboardR); if (_scanSectionsSelected == BCIScanSections.KeyboardR) parameters = GetCalibrationParameters(); else @@ -197,7 +204,7 @@ private void ButtonCalibrate_Click(object sender, EventArgs e) } catch (Exception ex) { - Log.Exception("BCI LOG | Error ButtonCalibrate_Click " + ex.Message); + _logger.LogError(ex, "BCI LOG | Error ButtonCalibrate_Click"); } } @@ -284,7 +291,7 @@ private void ButtonInfoModes_MouseEnter(object sender, EventArgs e) private void ButtonInfoModes_MouseLeave(object sender, EventArgs e) { - try { customToolTip?.HideToolTip(); } catch (Exception ex) { Log.Debug("Error ButtonInfoModes_MouseLeave: " + ex.Message); } + try { customToolTip?.HideToolTip(); } catch (Exception ex) { _logger.LogDebug(ex, "Error ButtonInfoModes_MouseLeave"); } } private void ButtonInfoParameters_MouseEnter(object sender, EventArgs e) @@ -350,7 +357,7 @@ private void ButtonOpc_Click(object sender, EventArgs e) } catch (Exception ex) { - Log.Exception("BCI LOG | Error ButtonOpc_Click " + ex.Message); + _logger.LogError(ex, "BCI LOG | Error ButtonOpc_Click"); } } @@ -512,7 +519,7 @@ private void DisplayCalibrationHelp() } catch (Exception ex) { - Log.Exception("BCI LOG | Exception DisplayCalibrationHelp " + ex.Message); + _logger.LogError(ex, "BCI LOG | Exception DisplayCalibrationHelp"); } } @@ -544,7 +551,7 @@ private BCISimpleParameters GetCalibrationParametersDefault(BCIScanSections bCIS } catch (Exception ex) { - Log.Exception("BCI LOG | Error GetCalibrationParametersDefault | " + ex.Message.ToString()); + _logger.LogError(ex, "BCI LOG | Error GetCalibrationParametersDefault"); } return bciSimpleParameters; } @@ -673,7 +680,7 @@ private void ProcessCalibrationStatusResult() } catch (Exception ex) { - Log.Exception("BCI LOG | Error ProcessCalibrationStatusResult | " + ex.Message.ToString()); + _logger.LogError(ex, "BCI LOG | Error ProcessCalibrationStatusResult"); } } @@ -843,7 +850,7 @@ private void ValidateSliderValues(ColorSlider.ColorSlider colorSlider, Label lab { colorSlider.Value = colorSlider.Minimum; label.Text = colorSlider.Minimum.ToString(); - Log.Debug("BCI LOG | ValidateSliderValues | " + ex.Message.ToString()); + _logger.LogDebug(ex, "BCI LOG | ValidateSliderValues"); } } @@ -857,7 +864,7 @@ private void WebBrowser_Navigating(object sender, WebBrowserNavigatingEventArgs { var str = e.Url.ToString(); - Log.Debug("Url is [" + str + "]"); + _logger.LogDebug("Url is [{Url}]", str); if (str.ToLower().Contains("blank")) { diff --git a/src/Extensions/BCI/Common/BCIInterfaceUtilities/ConfirmBoxTriggerBoxSettings.cs b/src/Extensions/BCI/Common/BCIInterfaceUtilities/ConfirmBoxTriggerBoxSettings.cs index 28449145..ea79754b 100644 --- a/src/Extensions/BCI/Common/BCIInterfaceUtilities/ConfirmBoxTriggerBoxSettings.cs +++ b/src/Extensions/BCI/Common/BCIInterfaceUtilities/ConfirmBoxTriggerBoxSettings.cs @@ -11,6 +11,7 @@ using ACAT.Core.WidgetManagement; using ACAT.Extensions.BCI.Common.BCIControl; using ACATResources; +using Microsoft.Extensions.Logging; using System; using System.Drawing; using System.Windows.Forms; @@ -26,6 +27,7 @@ namespace ACAT.Extensions.BCI.Common.BCIInterfaceUtilities "Application window used as a configuration UI for trigger test")] public partial class ConfirmBoxTriggerBoxSettings : Form { + private readonly ILogger _logger; /// /// Main object of the actuator /// @@ -56,8 +58,9 @@ public partial class ConfirmBoxTriggerBoxSettings : Form /// /// Confirm Box with multiple results /// - public ConfirmBoxTriggerBoxSettings() + public ConfirmBoxTriggerBoxSettings(ILogger logger = null) { + _logger = logger ?? LoggerFactory.GetLogger(); InitializeComponent(); label1.Text = StringResources.CalibrationIsEssential; Load += ConfirmBox_Load; @@ -104,7 +107,7 @@ private void ButtonStartTriggerTest_Click(object sender, EventArgs e) } catch (Exception ex) { - Log.Exception("Error ButtonStartTriggerTest_Click: " + ex.Message); + _logger.LogError(ex, "Error ButtonStartTriggerTest_Click: " + ex.Message); OptionResult = new Tuple(BCIMenuOptions.Options.TriggerTest, GetTriggerTestParameters()); Close(); } @@ -163,7 +166,7 @@ private void ButtonInfoModes_MouseEnter(object sender, EventArgs e) private void ButtonInfoModes_MouseLeave(object sender, EventArgs e) { - try { customToolTip?.HideToolTip(); } catch (Exception ex) { Log.Debug("Error ButtonInfoModes_MouseLeave: " + ex.Message); } + try { customToolTip?.HideToolTip(); } catch (Exception ex) { _logger.LogDebug("Error ButtonInfoModes_MouseLeave: " + ex.Message); } } private void ButtonInfoParameters_MouseEnter(object sender, EventArgs e) @@ -195,7 +198,7 @@ private void ButtonOpcTriggerTest_Click(object sender, EventArgs e) } catch (Exception ex) { - Log.Exception("Error ButtonOpc_Click: " + ex.Message); + _logger.LogError(ex, "Error ButtonOpc_Click: " + ex.Message); } } diff --git a/src/Extensions/BCI/Common/BCIInterfaceUtilities/OtherTestForm.cs b/src/Extensions/BCI/Common/BCIInterfaceUtilities/OtherTestForm.cs index 85f48a5c..cb0fcf88 100644 --- a/src/Extensions/BCI/Common/BCIInterfaceUtilities/OtherTestForm.cs +++ b/src/Extensions/BCI/Common/BCIInterfaceUtilities/OtherTestForm.cs @@ -9,6 +9,7 @@ using ACAT.Core.WidgetManagement; using ACAT.Extensions.BCI.Common.BCIControl; using ACATResources; +using Microsoft.Extensions.Logging; using System; using System.Drawing; using System.Windows.Forms; @@ -25,6 +26,7 @@ namespace ACAT.Extensions.BCI.Common.BCIInterfaceUtilities "Application window used to display other test for BCI")] public partial class OtherTestForm : Form { + private readonly ILogger _logger; /// /// Custom Tooltip object /// @@ -37,8 +39,9 @@ public partial class OtherTestForm : Form /// /// Confirm Box with multiple results /// - public OtherTestForm() + public OtherTestForm(ILogger logger = null) { + _logger = logger ?? LoggerFactory.GetLogger(); InitializeComponent(); Load += ConfirmBox_Load; } @@ -97,22 +100,22 @@ private void ButtonOpc_Click(object sender, EventArgs e) switch (scannerRoundedButtonControl.Name) { case var _ when scannerRoundedButtonControl.Name.Contains("ReMapCalibrations"): - Log.Debug("BCI LOG | AdvancedOptions | ButtonClick: ReMapCalibrations"); + _logger.LogDebug("BCI LOG | AdvancedOptions | ButtonClick: ReMapCalibrations"); Options = BCIMenuOptions.Options.RemapCalibrations; break; case var _ when scannerRoundedButtonControl.Name.Contains("TriggerCheck"): - Log.Debug("BCI LOG | AdvancedOptions | ButtonClick: TriggerCheck"); + _logger.LogDebug("BCI LOG | AdvancedOptions | ButtonClick: TriggerCheck"); Options = BCIMenuOptions.Options.TriggerTest; break; case var _ when scannerRoundedButtonControl.Name.Contains("SignalCheck"): - Log.Debug("BCI LOG | AdvancedOptions | ButtonClick: SignalCheck"); + _logger.LogDebug("BCI LOG | AdvancedOptions | ButtonClick: SignalCheck"); Options = BCIMenuOptions.Options.SignalCheck; break; case var _ when scannerRoundedButtonControl.Name.Contains("EyesOpenClose"): - Log.Debug("BCI LOG | AdvancedOptions | ButtonClick: EyesOpenClose"); + _logger.LogDebug("BCI LOG | AdvancedOptions | ButtonClick: EyesOpenClose"); Options = BCIMenuOptions.Options.EyesCalibration; break; } @@ -121,7 +124,7 @@ private void ButtonOpc_Click(object sender, EventArgs e) } catch (Exception ex) { - Log.Exception("BCI LOG | Error ButtonCalibrate_Click: " + ex.Message); + _logger.LogError(ex, "BCI LOG | Error ButtonCalibrate_Click: " + ex.Message); Close(); } } diff --git a/src/Extensions/BCI/Common/BCIInterfaceUtilities/RemapCalibrationForm.cs b/src/Extensions/BCI/Common/BCIInterfaceUtilities/RemapCalibrationForm.cs index abd84190..6dfd39ad 100644 --- a/src/Extensions/BCI/Common/BCIInterfaceUtilities/RemapCalibrationForm.cs +++ b/src/Extensions/BCI/Common/BCIInterfaceUtilities/RemapCalibrationForm.cs @@ -10,6 +10,7 @@ using ACAT.Core.Utility; using ACAT.Extensions.BCI.Common.BCIControl; using ACATResources; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Windows.Forms; @@ -25,6 +26,11 @@ namespace ACAT.Extensions.BCI.Common.BCIInterfaceUtilities "Application window used to display the remap of calibrations")] public partial class RemapCalibrationForm : Form { + /// + /// Logger instance + /// + private readonly ILogger _logger; + /// /// Main object of the actuator /// @@ -55,8 +61,9 @@ public partial class RemapCalibrationForm : Form /// /// Confirm Box with multiple results /// - public RemapCalibrationForm() + public RemapCalibrationForm(ILogger logger) { + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); InitializeComponent(); Load += ConfirmBox_Load; @@ -96,7 +103,7 @@ private void AddItemsToComboBox(ComboBox comboBox, List bCICl } catch (Exception ex) { - Log.Exception("Error AddItemsToComboBox: " + ex.Message); + _logger.LogError(ex, "Error AddItemsToComboBox"); } } @@ -127,7 +134,7 @@ private void ButtonDone_Click(object sender, EventArgs e) var strBCICalibrationUpdatedMappings = GetMappingsValues(); _bciActuator?.IoctlRequest((int)OpCodes.SendUpdatedMappings, strBCICalibrationUpdatedMappings); OptionResult = CheckIfComboBoxValuesChanged(); - Log.Debug("BCI LOG | Mappings change: " + OptionResult); + _logger.LogDebug("BCI LOG | Mappings change: {MappingsChanged}", OptionResult); Close(); } @@ -195,7 +202,7 @@ private BCICalibrationUpdatedMappings GetMappingsValues() } catch (Exception ex) { - Log.Exception("Error SaveMappingsValues: " + ex.Message); + _logger.LogError(ex, "Error SaveMappingsValues"); } return bCICalibrationUpdatedMappings; } @@ -273,7 +280,7 @@ private void ProcessMapOptionsAnswer() } catch (Exception ex) { - Log.Exception("BCI LOG | Error ProcessMapOptionsAnswer: " + ex.Message); + _logger.LogError(ex, "BCI LOG | Error ProcessMapOptionsAnswer"); } } @@ -326,7 +333,7 @@ private void SetDefaultItemInComboBox(ComboBox comboBox, BCIScanSections bCIScan } catch (Exception ex) { - Log.Exception("BCI LOG | Error SetDefaultItemInComboBox: " + ex.Message); + _logger.LogError(ex, "BCI LOG | Error SetDefaultItemInComboBox"); } } @@ -340,7 +347,7 @@ private void WebBrowserDesc_Navigating(object sender, WebBrowserNavigatingEventA { var str = e.Url.ToString(); - Log.Debug("Url is [" + str + "]"); + _logger.LogDebug("Url is [{Url}]", str); if (str.ToLower().Contains("blank")) { diff --git a/src/Extensions/Default/Actuators/CameraActuator/CameraActuator.cs b/src/Extensions/Default/Actuators/CameraActuator/CameraActuator.cs index 5c6f055f..2146f3c3 100644 --- a/src/Extensions/Default/Actuators/CameraActuator/CameraActuator.cs +++ b/src/Extensions/Default/Actuators/CameraActuator/CameraActuator.cs @@ -22,6 +22,7 @@ using ACAT.Core.Utility; using ACAT.Core.Utility.TypeLoader; using ACATResources; +using Microsoft.Extensions.Logging; using System; using System.Linq; using System.Runtime.ExceptionServices; @@ -40,6 +41,8 @@ namespace ACAT.Extensions.Actuators.CameraActuator "Actuator which uses a webcam to detect facial gestures and trigger ACAT")] internal class CameraActuator : ActuatorBase, ISupportsPreferences, IPluginExtension { + private readonly ILogger _logger; + /// /// The settings object for this actuator /// diff --git a/src/Extensions/Default/Actuators/CameraActuator/CameraActuatorSwitch.cs b/src/Extensions/Default/Actuators/CameraActuator/CameraActuatorSwitch.cs index 67e3228f..32372dc6 100644 --- a/src/Extensions/Default/Actuators/CameraActuator/CameraActuatorSwitch.cs +++ b/src/Extensions/Default/Actuators/CameraActuator/CameraActuatorSwitch.cs @@ -24,6 +24,7 @@ using ACAT.Core.ActuatorManagement; using ACAT.Core.ActuatorManagement.Interfaces; using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; namespace ACAT.Extensions.Actuators.CameraActuator { @@ -34,11 +35,14 @@ public class CameraActuatorSwitch : ActuatorSwitchBase /// private bool _disposed; + private readonly ILogger _logger; + /// /// Initializes a new instance of the class /// - public CameraActuatorSwitch() + public CameraActuatorSwitch(ILogger logger = null) { + _logger = logger; } /// @@ -46,9 +50,10 @@ public CameraActuatorSwitch() /// members over from switchObj /// /// Switch object to clone - public CameraActuatorSwitch(IActuatorSwitch switchObj) + public CameraActuatorSwitch(IActuatorSwitch switchObj, ILogger logger = null) : base(switchObj) { + _logger = logger; } /// @@ -61,7 +66,7 @@ protected override void Dispose(bool disposing) { try { - Log.Verbose(); + _logger?.LogTrace("Disposing CameraActuatorSwitch"); if (disposing) { diff --git a/src/Extensions/Default/Actuators/CameraActuator/ConfigureActuatorForm.cs b/src/Extensions/Default/Actuators/CameraActuator/ConfigureActuatorForm.cs index 41ba274b..baf65862 100644 --- a/src/Extensions/Default/Actuators/CameraActuator/ConfigureActuatorForm.cs +++ b/src/Extensions/Default/Actuators/CameraActuator/ConfigureActuatorForm.cs @@ -15,6 +15,7 @@ using ACAT.Core.PanelManagement.Utils; using ACAT.Core.Utility; using ACATResources; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Drawing; @@ -47,6 +48,7 @@ public partial class ConfigureActuatorForm : Form private readonly Color _buttonBackColor; private bool _gestureDetectedAtleastOnce = false; private readonly CameraActuator _cameraActuator; + private readonly ILogger _logger; private int _gestureCount = 0; private Mode _mode = Mode.SelectCamera; private SampleImageForm _sampleImageForm = null; @@ -56,13 +58,14 @@ public partial class ConfigureActuatorForm : Form private WebcamGestureSelectUserControl _webcamGestureSelectUserControl; private WebcamGestureSettingsUserControl _webcamGestureSettingsUserControl; - internal ConfigureActuatorForm(CameraActuator cameraActuator) + internal ConfigureActuatorForm(CameraActuator cameraActuator, ILogger logger) { InitializeComponent(); _buttonBackColor = buttonDone.BackColor; _cameraActuator = cameraActuator; + _logger = logger; Load += ConfigureActuatorForm_Load; Shown += ConfigureActuatorForm_Shown; @@ -100,7 +103,7 @@ private void _textTimer_Tick(object sender, EventArgs e) private void _timer_Tick(object sender, EventArgs e) { - Log.Debug("_cameraActuator.CameraSensorRunning: " + _cameraActuator.CameraSensorRunning); + _logger.LogDebug("_cameraActuator.CameraSensorRunning: {CameraSensorRunning}", _cameraActuator.CameraSensorRunning); if (_cameraActuator.CameraSensorRunning) { @@ -109,19 +112,19 @@ private void _timer_Tick(object sender, EventArgs e) setLabelPromptDefaultText(); - Log.Debug("Camera sensor is is running. Calling _videoWindowFinder.Start()"); + _logger.LogDebug("Camera sensor is is running. Calling _videoWindowFinder.Start()"); _videoWindowFinder.Start(); } } private void _videoWindowFinder_EvtVideoWindowDisplayed(IntPtr handle) { - Log.Verbose(); + _logger.LogDebug("Video window displayed"); try { - Log.Debug("Docking calibration window"); + _logger.LogDebug("Docking calibration window"); _videoWindowFinder.DockVideoWindow(this); @@ -213,9 +216,9 @@ private void buttonDone_Click(object sender, EventArgs e) _videoWindowFinder.EvtVideoWindowDisplayed -= _videoWindowFinder_EvtVideoWindowDisplayed; _videoWindowFinder.EvtVideoWindowFindStart -= _videoWindowFinder_EvtVideoWindowFindStart; - Log.Debug("Calling dockvideo dispose"); + _logger.LogDebug("Calling dockvideo dispose"); _videoWindowFinder.Dispose(); - Log.Debug("Returned from dockvideo dispose"); + _logger.LogDebug("Returned from dockvideo dispose"); } CameraSensor.hideVideoWindow(); @@ -315,7 +318,7 @@ private void CameraActuator_EvtChangeCameraStart(String camera) } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex, "Exception in CameraActuator_EvtChangeCameraStart"); } } @@ -341,7 +344,7 @@ private void ConfigureActuatorForm_Load(object sender, EventArgs e) { Left = Top = 0; - Log.Debug("ENtered ConfigureActuatorForm_Load"); + _logger.LogDebug("Entered ConfigureActuatorForm_Load"); Resize += CalibrateForm_Resize; diff --git a/src/Extensions/Default/Actuators/CameraActuator/VideoWindowFinder.cs b/src/Extensions/Default/Actuators/CameraActuator/VideoWindowFinder.cs index 15bd0075..c90188ed 100644 --- a/src/Extensions/Default/Actuators/CameraActuator/VideoWindowFinder.cs +++ b/src/Extensions/Default/Actuators/CameraActuator/VideoWindowFinder.cs @@ -12,6 +12,7 @@ //////////////////////////////////////////////////////////////////////////// using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Threading; using System.Windows.Forms; @@ -28,6 +29,7 @@ public class VideoWindowFinder : IDisposable /// private bool _disposed; + private readonly ILogger _logger; private Thread _thread; public delegate void VideoWindowDisplayedDelegate(IntPtr handle); @@ -36,6 +38,11 @@ public class VideoWindowFinder : IDisposable public event EventHandler EvtVideoWindowFindStart; + public VideoWindowFinder(ILogger logger) + { + _logger = logger; + } + /// /// Disposes resources /// @@ -83,7 +90,7 @@ private void dispose(bool disposing) { try { - Log.Verbose(); + _logger.LogDebug("Disposing VideoWindowFinder"); if (disposing) { @@ -106,7 +113,7 @@ private void dispose(bool disposing) // Release the native unmanaged resources - Log.Debug("Exiting dispose"); + _logger.LogDebug("Exiting dispose"); _disposed = true; } finally diff --git a/src/Extensions/Default/Actuators/CameraActuator/WebcamGestureSelectUserControl.cs b/src/Extensions/Default/Actuators/CameraActuator/WebcamGestureSelectUserControl.cs index d73ac19f..3230c574 100644 --- a/src/Extensions/Default/Actuators/CameraActuator/WebcamGestureSelectUserControl.cs +++ b/src/Extensions/Default/Actuators/CameraActuator/WebcamGestureSelectUserControl.cs @@ -15,6 +15,7 @@ using ACAT.Core.ActuatorManagement.Interfaces; using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Drawing; @@ -29,6 +30,7 @@ public partial class WebcamGestureSelectUserControl : UserControl private readonly Dictionary _dict = new(); private IEnumerable _installedCameras; private readonly CameraActuator _cameraActuator; + private readonly ILogger _logger; private int bothIndex = -1; private int cameraIndex = -1; @@ -37,11 +39,12 @@ public partial class WebcamGestureSelectUserControl : UserControl private int erIndex = -1; - internal WebcamGestureSelectUserControl(CameraActuator cameraActuator) + internal WebcamGestureSelectUserControl(CameraActuator cameraActuator, ILogger logger) { InitializeComponent(); _buttonBackColor = buttonRecalibrate.BackColor; _cameraActuator = cameraActuator; + _logger = logger; } public delegate void GestureSelected(bool cheekTwitch, bool eyebrowRaise); @@ -115,7 +118,7 @@ private void DropdownCameraSelect_SelectedIndexChanged(object sender, EventArgs { var camera = dropdownCameraSelect.SelectedItem as String; - Log.Debug("calling changeCamera to : " + camera); + _logger.LogDebug("calling changeCamera to {Camera}", camera); if (dropdownCameraSelect.Items.Count > 1 && dropdownCameraSelect.SelectedIndex != cameraIndex) { diff --git a/src/Extensions/Default/AppAgents/TalkApplicationScannerAgent/TalkApplicationScannerAgent.cs b/src/Extensions/Default/AppAgents/TalkApplicationScannerAgent/TalkApplicationScannerAgent.cs index 8db4a3da..bc285394 100644 --- a/src/Extensions/Default/AppAgents/TalkApplicationScannerAgent/TalkApplicationScannerAgent.cs +++ b/src/Extensions/Default/AppAgents/TalkApplicationScannerAgent/TalkApplicationScannerAgent.cs @@ -13,6 +13,7 @@ using ACAT.Core.AgentManagement; using ACAT.Core.AgentManagement.TextControlAgents; using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; @@ -26,6 +27,16 @@ namespace ACAT.Extensions.AppAgents.TalkApplicationScannerAgent "Manages interactions with the Talk Window with Embedded Scanner")] internal class TalkApplicationScannerAgent : AgentBase { + /// + /// Logger instance + /// + private readonly ILogger _logger; + + /// + /// Logger factory for creating loggers + /// + private readonly ILoggerFactory _loggerFactory; + /// /// The text control agent responsbile for handling /// editing and caret movement functions @@ -42,6 +53,16 @@ internal class TalkApplicationScannerAgent : AgentBase /// private Control textBoxControl; + /// + /// Initializes a new instance of the TalkApplicationScannerAgent class + /// + public TalkApplicationScannerAgent(ILogger logger, ILoggerFactory loggerFactory) + { + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + _loggerFactory = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory)); + } + private Control textBoxControl; + /// /// Gets the list of process supported by this agent /// @@ -102,25 +123,25 @@ public override void OnContextMenuRequest(WindowActivityMonitorInfo monitorInfo) /// set to true if handled public override void OnFocusChanged(WindowActivityMonitorInfo monitorInfo, ref bool handled) { - Log.Verbose(); + _logger.LogTrace("OnFocusChanged"); _windowHandle = monitorInfo.FgHwnd; - Log.Debug("window handle: " + _windowHandle); + _logger.LogDebug("window handle: {WindowHandle}", _windowHandle); if (monitorInfo.IsNewFocusedElement || monitorInfo.IsNewWindow) { var automationElement = getTalkTextWinAutomationElement(); if (automationElement != null) { - Log.Debug("found automationelement for the text box"); + _logger.LogDebug("found automationelement for the text box"); disposeTextInterface(); createTalkWindowTextInterface(monitorInfo.FgHwnd, automationElement); } else { - Log.Error("DID NOT find automationelement for the text box"); + _logger.LogError("DID NOT find automationelement for the text box"); textBoxControl = null; } } @@ -168,7 +189,8 @@ private void createTalkWindowTextInterface(IntPtr handle, AutomationElement auto bool handled = false; //_textInterface = new EditTextControlAgent(handle, automationElement, ref handled); - _textInterface = new TalkApplicationTextControlAgent(textBoxControl, handle, automationElement, ref handled); + var textControlLogger = _loggerFactory.CreateLogger(); + _textInterface = new TalkApplicationTextControlAgent(textControlLogger, textBoxControl, handle, automationElement, ref handled); _textInterface.EvtTextChanged += _textInterface_EvtTextChanged; setTextInterface(_textInterface); @@ -182,7 +204,7 @@ private void disposeTextInterface() { if (_textInterface != null) { - Log.Debug("Disposing old text interface"); + _logger.LogDebug("Disposing old text interface"); _textInterface.EvtTextChanged -= _textInterface_EvtTextChanged; _textInterface.Dispose(); _textInterface = null; diff --git a/src/Extensions/Default/AppAgents/TalkApplicationScannerAgent/TalkApplicationTextControlAgent.cs b/src/Extensions/Default/AppAgents/TalkApplicationScannerAgent/TalkApplicationTextControlAgent.cs index efd12f6f..bad84823 100644 --- a/src/Extensions/Default/AppAgents/TalkApplicationScannerAgent/TalkApplicationTextControlAgent.cs +++ b/src/Extensions/Default/AppAgents/TalkApplicationScannerAgent/TalkApplicationTextControlAgent.cs @@ -13,6 +13,7 @@ using ACAT.Core.AgentManagement; using ACAT.Core.AgentManagement.TextControlAgents; using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Text; using System.Windows.Automation; @@ -22,11 +23,13 @@ namespace ACAT.Extensions.AppAgents.TalkApplicationScannerAgent { internal class TalkApplicationTextControlAgent : EditTextControlAgent { + private readonly ILogger _logger; private readonly Control _textControl; - public TalkApplicationTextControlAgent(Control textControl, IntPtr handle, AutomationElement editControlElement, ref bool handled) : + public TalkApplicationTextControlAgent(ILogger logger, Control textControl, IntPtr handle, AutomationElement editControlElement, ref bool handled) : base(handle, editControlElement, ref handled) { + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); _textControl = textControl; } @@ -64,7 +67,7 @@ public override void Insert(int offset, string word) } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, "Error in Insert method"); } finally { @@ -74,7 +77,7 @@ public override void Insert(int offset, string word) public override void Replace(int offset, int count, String word) { - Log.Debug("HARRIS offset = " + offset + " count " + count + " word " + word); + _logger.LogDebug("HARRIS offset = {Offset} count {Count} word {Word}", offset, count, word); try { @@ -114,7 +117,7 @@ public override void Replace(int offset, int count, String word) } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, "Error in Replace method"); } finally { diff --git a/src/Extensions/Default/FunctionalAgents/LaunchAppAgent/LaunchAppAgent.cs b/src/Extensions/Default/FunctionalAgents/LaunchAppAgent/LaunchAppAgent.cs index 19c1a20a..3af60ecd 100644 --- a/src/Extensions/Default/FunctionalAgents/LaunchAppAgent/LaunchAppAgent.cs +++ b/src/Extensions/Default/FunctionalAgents/LaunchAppAgent/LaunchAppAgent.cs @@ -26,6 +26,7 @@ using ACAT.Core.Utility; using ACAT.Extension.UI; using ACAT.Extensions.UI.UserControls.Toolbars; +using Microsoft.Extensions.Logging; using System; using System.Diagnostics; using System.Threading; @@ -63,6 +64,8 @@ internal class LaunchAppAgent : FunctionalAgentBase /// private const string SettingsFileName = "LaunchAppSettings.xml"; + private readonly ILogger _logger; + /// /// The usercontrol that displays the list of applications /// @@ -86,8 +89,9 @@ internal class LaunchAppAgent : FunctionalAgentBase /// /// Initializes a new instance of the class. /// - public LaunchAppAgent() + public LaunchAppAgent(ILogger logger) { + _logger = logger; LaunchAppSettings.PreferencesFilePath = UserManager.GetFullPath(SettingsFileName); Settings = LaunchAppSettings.Load(); } @@ -99,7 +103,7 @@ public override bool Activate() if (_launchAppScanner == null) { - Log.Error("Could not create LaunchAppScanner"); + _logger.LogError("Could not create LaunchAppScanner"); return false; } @@ -192,11 +196,11 @@ public override void OnFocusChanged(WindowActivityMonitorInfo monitorInfo, ref b { if (IsClosing) { - Log.Debug("IsClosing is true. Will not handle the focus change"); + _logger.LogDebug("IsClosing is true. Will not handle the focus change"); return; } - Log.Debug("OnFocus: " + monitorInfo); + _logger.LogDebug("OnFocus: {MonitorInfo}", monitorInfo); base.OnFocusChanged(monitorInfo, ref handled); @@ -379,7 +383,7 @@ public bool launchProcess(AppInfo info) } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex, "{Exception}", ex.ToString()); retVal = false; } @@ -452,7 +456,7 @@ private void waitForProcessAndActivate(Process process) } catch (Exception ex) { - Log.Debug(ex.ToString()); + _logger.LogDebug("{Exception}", ex.ToString()); } } diff --git a/src/Extensions/Default/FunctionalAgents/SwitchWindowsAgent/SwitchWindowsAgent.cs b/src/Extensions/Default/FunctionalAgents/SwitchWindowsAgent/SwitchWindowsAgent.cs index bb5ddbd8..927c2438 100644 --- a/src/Extensions/Default/FunctionalAgents/SwitchWindowsAgent/SwitchWindowsAgent.cs +++ b/src/Extensions/Default/FunctionalAgents/SwitchWindowsAgent/SwitchWindowsAgent.cs @@ -22,6 +22,7 @@ using ACAT.Core.AgentManagement; using ACAT.Core.PanelManagement; using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Windows.Automation; using System.Windows.Forms; @@ -49,6 +50,8 @@ internal class SwitchWindowsAgent : FunctionalAgentBase /// private static SwitchWindowsScanner _switchWindowsScanner; + private readonly ILogger _logger; + /// /// Meta data for window selected /// @@ -57,8 +60,9 @@ internal class SwitchWindowsAgent : FunctionalAgentBase /// /// Initializes a new instance of the class. /// - public SwitchWindowsAgent() + public SwitchWindowsAgent(ILogger logger) { + _logger = logger; Name = ClassDescriptorAttribute.GetDescriptor(GetType()).Name; } @@ -131,11 +135,11 @@ public override void OnFocusChanged(WindowActivityMonitorInfo monitorInfo, ref b { if (IsClosing) { - Log.Debug("IsClosing is true. Will not handle the focus change"); + _logger.LogDebug("IsClosing is true. Will not handle the focus change"); return; } - Log.Debug("OnFocus: " + monitorInfo); + _logger.LogDebug("OnFocus: {MonitorInfo}", monitorInfo); base.OnFocusChanged(monitorInfo, ref handled); diff --git a/src/Extensions/Default/FunctionalAgents/SwitchWindowsAgent/SwitchWindowsScanner.cs b/src/Extensions/Default/FunctionalAgents/SwitchWindowsAgent/SwitchWindowsScanner.cs index 8152c610..b5d82058 100644 --- a/src/Extensions/Default/FunctionalAgents/SwitchWindowsAgent/SwitchWindowsScanner.cs +++ b/src/Extensions/Default/FunctionalAgents/SwitchWindowsAgent/SwitchWindowsScanner.cs @@ -25,6 +25,7 @@ using ACAT.Core.Utility; using ACAT.Core.WidgetManagement; using ACAT.Core.Widgets; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Drawing; @@ -48,7 +49,7 @@ namespace ACAT.Extensions.FunctionalAgents.SwitchWindowsAgent "SwitchWindowsScanner", "Switch Windows Scanner")] public partial class SwitchWindowsScanner : GenericScannerForm - { + { private readonly ILogger _logger; /// /// Enables invoking methods and properties in this form /// diff --git a/src/Extensions/Default/TTSEngines/SAPIEngine/SAPIEngine.cs b/src/Extensions/Default/TTSEngines/SAPIEngine/SAPIEngine.cs index aeeaf93c..d0d7ec9a 100644 --- a/src/Extensions/Default/TTSEngines/SAPIEngine/SAPIEngine.cs +++ b/src/Extensions/Default/TTSEngines/SAPIEngine/SAPIEngine.cs @@ -17,6 +17,7 @@ using ACAT.Core.TTSManagement.Interfaces; using ACAT.Core.UserManagement; using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Collections; using System.Collections.Generic; @@ -65,6 +66,8 @@ public class SAPIEngine : ExtensionInvoker, ITTSEngine, ISupportsPreferences /// private bool _disposed; + private readonly ILogger _logger; + /// /// Is speech muted? /// @@ -93,8 +96,9 @@ public class SAPIEngine : ExtensionInvoker, ITTSEngine, ISupportsPreferences /// /// Initializes a new instance of the class. /// - public SAPIEngine() + public SAPIEngine(ILogger logger) { + _logger = logger; SAPISettings.PreferencesFilePath = UserManager.GetFullPath(SettingsFileName); SAPISettings = SAPISettings.Load(); UseAlternatePronunciations = SAPISettings.UseAlternatePronunciations; @@ -281,10 +285,8 @@ public bool Init(CultureInfo ci) foreach (InstalledVoice iv in ins) { - Log.Debug("Found installed voice: " + iv.VoiceInfo.Name + - "Gender " + iv.VoiceInfo.Gender + - ", age: " + iv.VoiceInfo.Age + - ", culture: " + iv.VoiceInfo.Culture.Name); + _logger.LogDebug("Found installed voice: {VoiceName} Gender {Gender}, age: {Age}, culture: {Culture}", + iv.VoiceInfo.Name, iv.VoiceInfo.Gender, iv.VoiceInfo.Age, iv.VoiceInfo.Culture.Name); } loadPronunciations(ci); @@ -433,20 +435,20 @@ public virtual bool ShowPreferencesDialog() /// true on success public bool Speak(String text) { - Log.Debug("Entering..."); + _logger.LogDebug("Entering..."); try { if (!IsMuted()) { text = autoAppendPunctuation(replaceWithAltPronunciations(text)); - Log.Debug("Speaking text"); + _logger.LogDebug("Speaking text"); Synthesizer.SpeakAsync(text); } } catch (Exception ex) { - Log.Exception("Exception caught! ex=" + ex.Message); + _logger.LogError(ex, "Exception caught! ex={Message}", ex.Message); } return true; @@ -471,7 +473,7 @@ public bool SpeakAsync(String text, out int bookmark) { var promptBuilder = new PromptBuilder(); text = autoAppendPunctuation(replaceWithAltPronunciations(text)); - Log.Debug("Speaking text"); + _logger.LogDebug("Speaking text"); promptBuilder.AppendText(autoAppendPunctuation(text)); promptBuilder.AppendBookmark(bookmark.ToString()); @@ -481,7 +483,7 @@ public bool SpeakAsync(String text, out int bookmark) } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex, "{Exception}", ex.ToString()); retVal = false; } @@ -496,7 +498,7 @@ public bool SpeakAsync(String text, out int bookmark) /// true on success public bool SpeakSsml(String ssml, String text, String ttsPlaceHolderString) { - Log.Debug("Entering..."); + _logger.LogDebug("Entering..."); try { @@ -505,13 +507,13 @@ public bool SpeakSsml(String ssml, String text, String ttsPlaceHolderString) text = autoAppendPunctuation(replaceWithAltPronunciations(text)); ssml = ssml.Replace(ttsPlaceHolderString, text); - Log.Debug("Speaking text"); + _logger.LogDebug("Speaking text"); Synthesizer.SpeakSsmlAsync(ssml); } } catch (Exception ex) { - Log.Exception("Exception caught! ex=" + ex.Message); + _logger.LogError(ex, "Exception caught! ex={Message}", ex.Message); } return true; @@ -544,7 +546,7 @@ public bool SpeakSsmlAsync(String ssml, String text, String ttsPlaceHolderString text = autoAppendPunctuation(replaceWithAltPronunciations(text)); ssml = ssml.Replace(ttsPlaceHolderString, text); - Log.Debug("Speaking text"); + _logger.LogDebug("Speaking text"); TTSPrompt prompt = new(ssml, SynthesisTextFormat.Ssml) { @@ -552,7 +554,7 @@ public bool SpeakSsmlAsync(String ssml, String text, String ttsPlaceHolderString }; Synthesizer.SpeakAsync(prompt); - Log.Debug("Returned from speakasync"); + _logger.LogDebug("Returned from speakasync"); } else { @@ -561,7 +563,7 @@ public bool SpeakSsmlAsync(String ssml, String text, String ttsPlaceHolderString } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex, "{Exception}", ex.ToString()); retVal = false; } @@ -618,7 +620,7 @@ protected virtual void Dispose(bool disposing) // Check to see if Dispose has already been called. if (!_disposed) { - Log.Verbose(); + _logger.LogTrace("Disposing SAPIEngine"); if (disposing) { @@ -679,7 +681,7 @@ private bool loadPronunciations(CultureInfo ci) _pronunciations = new Pronunciations(); - Log.Debug("Loading pronunciations. Filename is " + SAPISettings.PronunciationsFile); + _logger.LogDebug("Loading pronunciations. Filename is {PronunciationsFile}", SAPISettings.PronunciationsFile); return _pronunciations.Load(ci, SAPISettings.PronunciationsFile); } @@ -735,7 +737,7 @@ private void setSpeechSynthSettings() } catch (Exception ex) { - Log.Exception("Error setting TTS settings " + ex); + _logger.LogError(ex, "Error setting TTS settings {Exception}", ex); } } @@ -754,7 +756,7 @@ private void speechSynthesizer_BookmarkReached(object sender, BookmarkReachedEve } catch (Exception ex) { - Log.Exception("Invalid bookmark " + e.Bookmark + ", exception: " + ex); + _logger.LogError(ex, "Invalid bookmark {Bookmark}, exception: {Exception}", e.Bookmark, ex); } } diff --git a/src/Extensions/Default/TTSEngines/TTSClient/TTSClient.cs b/src/Extensions/Default/TTSEngines/TTSClient/TTSClient.cs index e95fd4c9..c2e4f0c4 100644 --- a/src/Extensions/Default/TTSEngines/TTSClient/TTSClient.cs +++ b/src/Extensions/Default/TTSEngines/TTSClient/TTSClient.cs @@ -17,6 +17,7 @@ using ACAT.Core.TTSManagement.Interfaces; using ACAT.Core.UserManagement; using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Globalization; @@ -74,6 +75,8 @@ public class TTSClient : ExtensionInvoker, ITTSEngine, ISupportsPreferences /// private bool _disposed; + private readonly ILogger _logger; + /// /// Is speech muted? /// @@ -114,8 +117,9 @@ public class TTSClient : ExtensionInvoker, ITTSEngine, ISupportsPreferences /// /// Initializes a new instance of the class. /// - public TTSClient() + public TTSClient(ILogger logger) { + _logger = logger; TTSClientSettings.PreferencesFilePath = UserManager.GetFullPath(SettingsFileName); Settings = TTSClientSettings.Load(); UseAlternatePronunciations = Settings.UseAlternatePronunciations; @@ -412,7 +416,7 @@ public virtual bool ShowPreferencesDialog() /// true on success public bool Speak(String text) { - Log.Debug("Entering...text=" + text); + _logger.LogDebug("Entering...text={Text}", text); try { @@ -423,7 +427,7 @@ public bool Speak(String text) } catch (Exception ex) { - Log.Exception("Exception caught! ex=" + ex.Message); + _logger.LogError(ex, "Exception caught! ex={Message}", ex.Message); } return true; @@ -451,7 +455,7 @@ public bool SpeakAsync(String text, out int bookmark) } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex, "{Exception}", ex.ToString()); retVal = false; } @@ -467,7 +471,7 @@ public bool SpeakAsync(String text, out int bookmark) /// true on success public bool SpeakSsml(String ssml, String text, String placeHolder) { - Log.Debug("Entering...text=" + ssml); + _logger.LogDebug("Entering...text={Ssml}", ssml); try { @@ -476,15 +480,15 @@ public bool SpeakSsml(String ssml, String text, String placeHolder) text = autoAppendPunctuation(replaceWithAltPronunciations(text)); ssml = ssml.Replace(placeHolder, text); - Log.Debug("Speaking text:" + text); - Log.Debug("ssml:" + ssml); + _logger.LogDebug("Speaking text:{Text}", text); + _logger.LogDebug("ssml:{Ssml}", ssml); sendSsml(ssml); } } catch (Exception ex) { - Log.Exception("Exception caught! ex=" + ex.Message); + _logger.LogError(ex, "Exception caught! ex={Message}", ex.Message); } return true; @@ -510,15 +514,15 @@ public bool SpeakSsmlAsync(String ssml, String text, String placeHolder, out int text = autoAppendPunctuation(replaceWithAltPronunciations(text)); ssml = ssml.Replace(placeHolder, text); - Log.Debug("Speaking text:" + text); - Log.Debug("ssml:" + ssml); + _logger.LogDebug("Speaking text:{Text}", text); + _logger.LogDebug("ssml:{Ssml}", ssml); sendSsml(ssml); } } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex, "{Exception}", ex.ToString()); retVal = false; } @@ -570,7 +574,7 @@ protected virtual void Dispose(bool disposing) // Check to see if Dispose has already been called. if (!_disposed) { - Log.Verbose(); + _logger.LogTrace("Disposing TTSClient"); if (disposing) { @@ -624,8 +628,8 @@ private String getTempFileName(String extension) } catch (Exception ex) { - Log.Exception("Could not create temp directory for TTSClient. " + ex); - path = ".\\"; + _logger.LogError(ex, "Could not create temp directory for TTSClient. {Exception}", ex); + path = ".\\\ } path = path + "\\TTS_" + Guid.NewGuid() + extension; @@ -647,7 +651,7 @@ private bool loadPronunciations(CultureInfo ci) _pronunciations = new Pronunciations(); - Log.Debug("Loading pronunciations. Filename is " + Settings.PronunciationsFile); + _logger.LogDebug("Loading pronunciations. Filename is {PronunciationsFile}", Settings.PronunciationsFile); return _pronunciations.Load(ci, Settings.PronunciationsFile); } @@ -809,7 +813,7 @@ private bool writeToFile(String fileName, String text) } catch (Exception ex) { - Log.Exception("Error writing to temp file " + fileName + ". Exception: " + ex); + _logger.LogError(ex, "Error writing to temp file {FileName}. Exception: {Exception}", fileName, ex); return false; } diff --git a/src/Extensions/Default/TTSEngines/TTSClient/TransportHttp.cs b/src/Extensions/Default/TTSEngines/TTSClient/TransportHttp.cs index a1234c4b..7b433a49 100644 --- a/src/Extensions/Default/TTSEngines/TTSClient/TransportHttp.cs +++ b/src/Extensions/Default/TTSEngines/TTSClient/TransportHttp.cs @@ -12,6 +12,7 @@ //////////////////////////////////////////////////////////////////////////// using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Net.Http; using System.Text; @@ -21,6 +22,13 @@ namespace ACAT.Extensions.TTSEngines.TTSClient [Serializable] public class TransportHttp : ITTSTransport { + private readonly ILogger _logger; + + public TransportHttp(ILogger logger) + { + _logger = logger; + } + public bool Send(String data, TTSFormat format) { if (format == TTSFormat.None) @@ -49,7 +57,7 @@ private async void sendHttp(String data, TTSFormat format) } catch (Exception ex) { - Log.Exception("*** Could not send TTS request over http to " + Url + ". Exception: " + ex); + _logger.LogError(ex, "*** Could not send TTS request over http to {Url}. Exception: {Exception}", Url, ex); } } } diff --git a/src/Extensions/Default/WordPredictors/ConvAssist/ConvAssistUtils.cs b/src/Extensions/Default/WordPredictors/ConvAssist/ConvAssistUtils.cs index a57d50c3..1f715f07 100644 --- a/src/Extensions/Default/WordPredictors/ConvAssist/ConvAssistUtils.cs +++ b/src/Extensions/Default/WordPredictors/ConvAssist/ConvAssistUtils.cs @@ -12,6 +12,7 @@ using ACAT.Core.Utility; using ACAT.Extension; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Globalization; @@ -129,7 +130,8 @@ public static List> ToList(List predictions } catch (Exception es) { - Log.Exception("ConvAssist Predict " + es); + // Log exception but continue - return empty list + // Note: Static method cannot use injected logger } return newList; } diff --git a/src/Extensions/Default/WordPredictors/ConvAssist/ConvAssistWordPredictor.cs b/src/Extensions/Default/WordPredictors/ConvAssist/ConvAssistWordPredictor.cs index 88841837..8fee7da0 100644 --- a/src/Extensions/Default/WordPredictors/ConvAssist/ConvAssistWordPredictor.cs +++ b/src/Extensions/Default/WordPredictors/ConvAssist/ConvAssistWordPredictor.cs @@ -19,6 +19,7 @@ using ACAT.Core.WordPredictorManagement.Interfaces; using ACAT.Extensions.WordPredictors.ConvAssist.MessageTypes; using ACATResources; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Diagnostics; @@ -79,6 +80,8 @@ public class ConvAssistWordPredictor : ConvAssistWordPredictorBase /// internal static Settings settings; + private readonly ILogger _logger; + private readonly WordPredictionsRequestHandler _wordPredictionsRequestHandler; /// @@ -92,8 +95,9 @@ public class ConvAssistWordPredictor : ConvAssistWordPredictorBase /// /// Initializes and instance of the class /// - public ConvAssistWordPredictor() + public ConvAssistWordPredictor(ILogger logger) { + _logger = logger; Settings.PreferencesFilePath = getUserRelativePath(CultureInfo.CurrentCulture.TwoLetterISOLanguageName, SettingsFileName, true); settings = Settings.Load(); @@ -171,7 +175,7 @@ public override bool Init(CultureInfo ci) //So, we don't need to start it here string path = Path.Combine(FileUtils.ACATPath, ConvAssistAppFolder, ConvAssistAppName); - Log.Info("ConvAssist path: " + path); + _logger.LogInformation("ConvAssist path: {Path}", path); Process[] runningProcesses = Process.GetProcessesByName(ConvAssistName); if (runningProcesses.Length == 0) @@ -194,7 +198,7 @@ public override bool Init(CultureInfo ci) } } #endif - Log.Info("ConvAssist process started. Starting Named Pipe."); + _logger.LogInformation("ConvAssist process started. Starting Named Pipe."); // Now start the named pipe server and wait for the client to connect string convAssistSettings = Path.Combine(UserManager.CurrentUserDir, CultureInfo.CurrentUICulture.TwoLetterISOLanguageName, "WordPredictors", "ConvAssist", "Settings"); @@ -305,7 +309,7 @@ protected override bool learn(String text, WordPredictorMessageTypes requestType } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, "Exception in Init"); } return result; @@ -334,7 +338,7 @@ private void Close(bool waitOnCompletion = true) /// A list of predicted words private WordPredictionResponse ProcessPredictionRequest(WordPredictionRequest request) { - Log.Debug("Predict for: " + request.PrevWords + " " + request.CurrentWord); + _logger.LogDebug("Predict for: {PrevWords} {CurrentWord}", request.PrevWords, request.CurrentWord); WordPredictionResponse response = null; try @@ -358,7 +362,7 @@ private WordPredictionResponse ProcessPredictionRequest(WordPredictionRequest re } catch (Exception ex) { - Log.Exception("ConvAssist Exception " + ex); + _logger.LogError(ex, "ConvAssist Exception {Exception}", ex); response = new WordPredictionResponse(request, new List(), false); } diff --git a/src/Extensions/Default/WordPredictors/ConvAssist/NamedPipeServerConvAssist.cs b/src/Extensions/Default/WordPredictors/ConvAssist/NamedPipeServerConvAssist.cs index 542d55bc..01198444 100644 --- a/src/Extensions/Default/WordPredictors/ConvAssist/NamedPipeServerConvAssist.cs +++ b/src/Extensions/Default/WordPredictors/ConvAssist/NamedPipeServerConvAssist.cs @@ -18,6 +18,7 @@ using ACAT.Core.WordPredictorManagement.Interfaces; using ACAT.Extension; using ACAT.Extensions.WordPredictors.ConvAssist.MessageTypes; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Globalization; @@ -64,6 +65,8 @@ public class NamedPipeServerConvAssist : IDisposable /// private readonly object _syncObj = new(); + private readonly ILogger _logger; + /// /// Path to the INI files /// @@ -94,8 +97,11 @@ public class NamedPipeServerConvAssist : IDisposable /// /// Name of the pipe /// What direction? - public NamedPipeServerConvAssist(string pipeName, PipeDirection pipeDirection, string path) + /// Path to files + /// Logger instance + public NamedPipeServerConvAssist(string pipeName, PipeDirection pipeDirection, string path, ILogger logger) { + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); this.PipeName = pipeName; this.PipeDirection = pipeDirection; this._pathToFiles = path; @@ -138,7 +144,7 @@ public bool ClosePipeServer() } catch (Exception ex) { - Log.Exception("ConvAssist ClosePipe Error:" + ex.Message); + _logger.LogError(ex, "ConvAssist ClosePipe Error:{Message}", ex.Message); return false; } clientConected = false; @@ -159,7 +165,7 @@ public bool CreatePipeServer(bool send_params = false) } catch (Exception ex) { - Log.Exception("Exception in createPipeServer: " + ex); + _logger.LogError(ex, "Exception in createPipeServer: {Exception}", ex); } return success; @@ -200,7 +206,7 @@ public bool NotifyAppEvent(EventTypes eventType) } catch (Exception ex) { - Log.Exception("ConvAssist AppEvent: " + ex.Message); + _logger.LogError(ex, "ConvAssist AppEvent: {Message}", ex.Message); } return true; } @@ -239,7 +245,7 @@ public async Task SendParams() } catch (Exception ex) { - Log.Exception("Error in param enable log: " + ex); + _logger.LogError(ex, "Error in param enable log: {Exception}", ex); } } @@ -305,7 +311,7 @@ public async Task StartNamedPipeServer(CancellationToken token, bool send_ } catch (TimeoutException) { - Log.Exception("ConvAssist StartNamedPiperServer Timeout"); + _logger.LogError("ConvAssist StartNamedPiperServer Timeout"); } } @@ -325,12 +331,12 @@ public async Task StartNamedPipeServer(CancellationToken token, bool send_ catch (TimeoutException ex) { success = false; - Log.Exception(ex); + _logger.LogError(ex, "TimeoutException in SendParams"); } catch (Exception ex) { success = false; - Log.Exception(ex); + _logger.LogError(ex, "Exception in SendParams"); } } @@ -434,7 +440,7 @@ public void Write(string value) catch (Exception ex) { - Log.Exception("ConvAssist Write Error: " + ex.Message); + _logger.LogError(ex, "ConvAssist Write Error: {Message}", ex.Message); } } @@ -451,7 +457,7 @@ public async Task WriteAsync(string value, int msDelay) byte[] payload = Encoding.UTF8.GetBytes(value); - Log.Debug("Payload hex: " + BitConverter.ToString(payload)); + _logger.LogDebug("Payload hex: {Payload}", BitConverter.ToString(payload)); byte[] lengthPrefix = BitConverter.GetBytes(payload.Length); @@ -523,7 +529,7 @@ public string WriteSync(string value, int msDelay) string message = string.Empty; try { - Log.Debug("ConvAssist WriteSync Lock on"); + _logger.LogDebug("ConvAssist WriteSync Lock on"); lock (_writeSyncObj) { TaskFinished = false; @@ -563,9 +569,9 @@ public string WriteSync(string value, int msDelay) } catch (Exception ex) { - Log.Exception("ConvAssist WriteSync " + ex); + _logger.LogError(ex, "ConvAssist WriteSync {Exception}", ex); } - Log.Debug("ConvAssist WriteSync Lock off"); + _logger.LogDebug("ConvAssist WriteSync Lock off"); return message; } @@ -575,7 +581,7 @@ public string WriteSync(string value, int msDelay) /// private void OnConnection(IAsyncResult ar) { - Log.Debug("ConvAssist Establish connection"); + _logger.LogDebug("ConvAssist Establish connection"); NumClientsConnected++; clientConected = true; var pipeServerState = (PipeServerStateConvAssist)ar.AsyncState; @@ -608,7 +614,7 @@ private void PipeServer_EvtClientConnected() private void PipeServer_EvtClientDisconnected() { - Log.Debug("ConvAssist PipeServer_EvtClientDisconnected"); + _logger.LogDebug("ConvAssist PipeServer_EvtClientDisconnected"); EvtClientDisconnected?.Invoke(null, new EventArgs()); clientConected = false; clientAnswerParameters = false; @@ -706,7 +712,7 @@ private void WriteCallback(IAsyncResult iar) } catch (Exception ex) { - Log.Exception("ConvAssist Error in writeCallback: " + ex.Message); + _logger.LogError(ex, "ConvAssist Error in writeCallback: {Message}", ex.Message); } } } diff --git a/src/Extensions/Default/WordPredictors/ConvAssist/SentencePredictionsRequestHandler.cs b/src/Extensions/Default/WordPredictors/ConvAssist/SentencePredictionsRequestHandler.cs index e31a8739..e5a2dfeb 100644 --- a/src/Extensions/Default/WordPredictors/ConvAssist/SentencePredictionsRequestHandler.cs +++ b/src/Extensions/Default/WordPredictors/ConvAssist/SentencePredictionsRequestHandler.cs @@ -15,6 +15,7 @@ using ACAT.Core.WordPredictorManagement; using ACAT.Core.WordPredictorManagement.Interfaces; using ACAT.Extensions.WordPredictors.ConvAssist.MessageTypes; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; @@ -29,10 +30,12 @@ internal class SentencePredictionsRequestHandler private string _prevPrevWords = null; private List _prevSentencePredictionResults = new(); private readonly ConvAssistWordPredictor _wordPredictor; + private readonly ILogger _logger; - public SentencePredictionsRequestHandler(ConvAssistWordPredictor wordPredictor) + public SentencePredictionsRequestHandler(ConvAssistWordPredictor wordPredictor, ILogger logger) { _wordPredictor = wordPredictor; + _logger = logger; } /// @@ -56,7 +59,7 @@ public WordPredictionResponse ProcessPredictionRequest(WordPredictionRequest req WordPredictionResponse response; try { - Log.Debug("_prevMode: " + _prevMode + ", currentMode: " + _wordPredictor.GetMode()); + _logger.LogDebug("_prevMode: {PrevMode}, currentMode: {CurrentMode}", _prevMode, _wordPredictor.GetMode()); if (_prevMode != _wordPredictor.GetMode() || _prevPrevWords == null || _prevCurrentWord == null || @@ -93,7 +96,7 @@ public WordPredictionResponse ProcessPredictionRequest(WordPredictionRequest req { predictedSentences = _wordPredictor.SendMessageConvAssistSentencePrediction(preceedingWords.ToString(), request.WordPredictionMode); - Log.Debug("ConvAssist sentences response: " + predictedSentences); + _logger.LogDebug("ConvAssist sentences response: {PredictedSentences}", predictedSentences); } else { @@ -130,13 +133,13 @@ public WordPredictionResponse ProcessPredictionRequest(WordPredictionRequest req } else { - Log.Debug("Nothing changed. returning previous"); + _logger.LogDebug("Nothing changed. returning previous"); response = new WordPredictionResponse(request, _prevSentencePredictionResults, true); } } catch (Exception ex) { - Log.Exception("ConvAssist Predict Exception " + ex); + _logger.LogError(ex, "ConvAssist Predict Exception"); _prevSentencePredictionResults = new List(); response = new WordPredictionResponse(request, new List(), false); @@ -205,7 +208,7 @@ private List ProcessSentencesPredictions(string predictions, string curr } catch (Exception sentencesLetters) { - Log.Exception("ConvAssist Predict sentencesLetters " + sentencesLetters); + _logger.LogError(sentencesLetters, "ConvAssist Predict sentencesLetters"); } return retVal; } diff --git a/src/Extensions/Default/WordPredictors/ConvAssist/WordPredictionsRequestHandler.cs b/src/Extensions/Default/WordPredictors/ConvAssist/WordPredictionsRequestHandler.cs index 1f618739..f8815425 100644 --- a/src/Extensions/Default/WordPredictors/ConvAssist/WordPredictionsRequestHandler.cs +++ b/src/Extensions/Default/WordPredictors/ConvAssist/WordPredictionsRequestHandler.cs @@ -15,6 +15,7 @@ using ACAT.Core.WordPredictorManagement; using ACAT.Core.WordPredictorManagement.Interfaces; using ACAT.Extensions.WordPredictors.ConvAssist.MessageTypes; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Globalization; @@ -51,9 +52,12 @@ internal class WordPredictionsRequestHandler /// private readonly ConvAssistWordPredictor WordPredictor; - public WordPredictionsRequestHandler(ConvAssistWordPredictor wordPredictor) + private readonly ILogger _logger; + + public WordPredictionsRequestHandler(ConvAssistWordPredictor wordPredictor, ILogger logger) { WordPredictor = wordPredictor; + _logger = logger; } /// @@ -67,7 +71,7 @@ public WordPredictionsRequestHandler(ConvAssistWordPredictor wordPredictor) /// A list of predicted words public WordPredictionResponse ProcessPredictionRequest(WordPredictionRequest request) { - Log.Debug("Predict for: " + request.PrevWords + " " + request.CurrentWord); + _logger.LogDebug("Predict for: {PrevWords} {CurrentWord}", request.PrevWords, request.CurrentWord); StringBuilder preceedingWords = new(); if (request.PredictionType != PredictionTypes.Words) @@ -105,13 +109,13 @@ public WordPredictionResponse ProcessPredictionRequest(WordPredictionRequest req List result; try { - Log.Debug("ConvAssist Mode: " + request.WordPredictionMode); + _logger.LogDebug("ConvAssist Mode: {WordPredictionMode}", request.WordPredictionMode); string predictedWords = String.Empty; predictedWords = WordPredictor.SendMessageConvAssistWordPrediction(preceedingWords.ToString(), request.WordPredictionMode); - Log.Debug("ConvAssist Words response: " + predictedWords); + _logger.LogDebug("ConvAssist Words response: {PredictedWords}", predictedWords); try { @@ -129,7 +133,7 @@ public WordPredictionResponse ProcessPredictionRequest(WordPredictionRequest req PrevWordPredictionResults = result; } - Log.Debug("Entered prediction" + prevWords + " " + currentWord); + _logger.LogDebug("Entered prediction {PrevWords} {CurrentWord}", prevWords, currentWord); response = new WordPredictionResponse(request, result, true); } @@ -140,7 +144,7 @@ public WordPredictionResponse ProcessPredictionRequest(WordPredictionRequest req } catch (Exception ex) { - Log.Exception("ConvAssist Predict Exception " + ex); + _logger.LogError(ex, "ConvAssist Predict Exception"); response = new WordPredictionResponse(request, new List(), false); } finally @@ -230,7 +234,7 @@ private List ProcessWordPredictions(ConvAssistWordPredictor wordPredicto } catch (Exception words) { - Log.Exception("ConvAssist Predict Words " + words); + _logger.LogError(words, "ConvAssist Predict Words"); } // Keyword to split between predictions retVal.Add("&LETTERS"); @@ -258,7 +262,7 @@ private List ProcessWordPredictions(ConvAssistWordPredictor wordPredicto } catch (Exception letters) { - Log.Exception("ConvAssist Predict letters " + letters); + _logger.LogError(letters, "ConvAssist Predict letters"); } return retVal; } diff --git a/src/Libraries/ACATCore/AbbreviationsManagement/Abbreviation.cs b/src/Libraries/ACATCore/AbbreviationsManagement/Abbreviation.cs index b0d7c9df..82ea4dca 100644 --- a/src/Libraries/ACATCore/AbbreviationsManagement/Abbreviation.cs +++ b/src/Libraries/ACATCore/AbbreviationsManagement/Abbreviation.cs @@ -15,6 +15,7 @@ //////////////////////////////////////////////////////////////////////////// using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Text.RegularExpressions; @@ -22,6 +23,8 @@ namespace ACAT.Core.AbbreviationsManagement { public class Abbreviation : IDisposable { + private readonly ILogger _logger; + /// /// Has this object been disposed /// @@ -33,8 +36,9 @@ public class Abbreviation : IDisposable /// abbreviation /// abbreviation expansion /// mode of expansion - speech or text - public Abbreviation(String mnemonic, String expansion, String mode) + public Abbreviation(String mnemonic, String expansion, String mode, ILogger logger = null) { + _logger = logger; Mode = Convert(mode); init(mnemonic, expansion, Mode); } @@ -45,8 +49,9 @@ public Abbreviation(String mnemonic, String expansion, String mode) /// abbreviation /// abbreviation expansion /// mode of expansion - speech or text - public Abbreviation(String mnemonic, String expansion, AbbreviationMode mode) + public Abbreviation(String mnemonic, String expansion, AbbreviationMode mode, ILogger logger = null) { + _logger = logger; init(mnemonic, expansion, mode); } @@ -90,7 +95,7 @@ public static AbbreviationMode Convert(String mode) } catch (Exception ex) { - Log.Exception(ex); + _logger?.LogError(ex, "Exception converting abbreviation mode"); } return retVal; diff --git a/src/Libraries/ACATCore/AbbreviationsManagement/Abbreviations.cs b/src/Libraries/ACATCore/AbbreviationsManagement/Abbreviations.cs index 3d8d39ac..d2e5e13e 100644 --- a/src/Libraries/ACATCore/AbbreviationsManagement/Abbreviations.cs +++ b/src/Libraries/ACATCore/AbbreviationsManagement/Abbreviations.cs @@ -14,6 +14,7 @@ using ACAT.Core.UserManagement; using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.IO; @@ -24,6 +25,8 @@ namespace ACAT.Core.AbbreviationsManagement { public class Abbreviations : IDisposable { + private readonly ILogger _logger; + /// /// Name of the abbreviations file /// @@ -54,6 +57,14 @@ public class Abbreviations : IDisposable /// private bool _disposed; + /// + /// Constructor + /// + public Abbreviations(ILogger logger = null) + { + _logger = logger; + } + /// /// Gets the sorted list of abbreviations /// @@ -168,7 +179,7 @@ public bool Load(String abbreviationsFile = null) } catch (Exception ex) { - Log.Exception("Error processing abbreviations file " + abbreviationsFile + ". Exception: " + ex); + _logger?.LogError(ex, "Error processing abbreviations file {AbbreviationsFile}", abbreviationsFile); retVal = false; } diff --git a/src/Libraries/ACATCore/AbbreviationsManagement/AbbreviationsManager.cs b/src/Libraries/ACATCore/AbbreviationsManagement/AbbreviationsManager.cs index 67b2382e..2a2c9a41 100644 --- a/src/Libraries/ACATCore/AbbreviationsManagement/AbbreviationsManager.cs +++ b/src/Libraries/ACATCore/AbbreviationsManagement/AbbreviationsManager.cs @@ -15,12 +15,15 @@ using ACAT.Core.PanelManagement; using ACAT.Core.PanelManagement.Common; using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; namespace ACAT.Core.AbbreviationsManagement { public class AbbreviationsManager : IDisposable { + private readonly ILogger _logger; + /// /// Static singleton instance /// @@ -34,8 +37,9 @@ public class AbbreviationsManager : IDisposable /// /// Initializes a new instance of the class. /// - private AbbreviationsManager() + private AbbreviationsManager(ILogger logger = null) { + _logger = logger; Context.EvtCultureChanged += Context_EvtCultureChanged; } diff --git a/src/Libraries/ACATCore/ActuatorManagement/ActuatorBase.cs b/src/Libraries/ACATCore/ActuatorManagement/ActuatorBase.cs index 064b9667..011834fc 100644 --- a/src/Libraries/ACATCore/ActuatorManagement/ActuatorBase.cs +++ b/src/Libraries/ACATCore/ActuatorManagement/ActuatorBase.cs @@ -23,6 +23,7 @@ using ACAT.Core.PanelManagement.Interfaces; using ACAT.Core.PreferencesManagement.Interfaces; using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; @@ -38,6 +39,8 @@ namespace ACAT.Core.ActuatorManagement /// public abstract class ActuatorBase : IActuator { + private readonly ILogger _logger; + /// /// Used to invoke methods/properties in the actuator /// @@ -57,8 +60,9 @@ public abstract class ActuatorBase : IActuator /// /// Initializes a new instance of the ActuatorBase class /// - protected ActuatorBase() + protected ActuatorBase(ILogger logger = null) { + _logger = logger; Enabled = false; _switches = new Dictionary(); actuatorState = State.Stopped; diff --git a/src/Libraries/ACATCore/ActuatorManagement/ActuatorEx.cs b/src/Libraries/ACATCore/ActuatorManagement/ActuatorEx.cs index 24bdf582..91ceda9c 100644 --- a/src/Libraries/ACATCore/ActuatorManagement/ActuatorEx.cs +++ b/src/Libraries/ACATCore/ActuatorManagement/ActuatorEx.cs @@ -18,6 +18,7 @@ using ACAT.Core.ActuatorManagement.Interfaces; using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.ComponentModel; using System.Threading; @@ -36,6 +37,8 @@ namespace ACAT.Core.ActuatorManagement /// internal class ActuatorEx { + private readonly ILogger _logger; + /// /// The inner acutator object /// @@ -79,8 +82,9 @@ internal class ActuatorEx /// Initializes an instance of the class /// /// The inner actuator object - public ActuatorEx(IActuator src) + public ActuatorEx(IActuator src, ILogger logger = null) { + _logger = logger; SourceActuator = src; } diff --git a/src/Libraries/ACATCore/ActuatorManagement/ActuatorManager.cs b/src/Libraries/ACATCore/ActuatorManagement/ActuatorManager.cs index 60f23987..a3a223df 100644 --- a/src/Libraries/ACATCore/ActuatorManagement/ActuatorManager.cs +++ b/src/Libraries/ACATCore/ActuatorManagement/ActuatorManager.cs @@ -26,6 +26,7 @@ using ACAT.Core.PreferencesManagement; using ACAT.Core.UserManagement; using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; @@ -45,6 +46,8 @@ namespace ACAT.Core.ActuatorManagement /// public class ActuatorManager : IDisposable { + private readonly ILogger _logger; + /// /// The base directory under which all the actuator Dll's are /// located. @@ -118,9 +121,10 @@ public class ActuatorManager : IDisposable /// /// Prevents a default instance of ActuatorManager class from being created /// - //private ActuatorManager() - //{ - // _activeSwitches = new Dictionary(); + private ActuatorManager(ILogger logger = null) + { + _logger = logger; + _activeSwitches = new Dictionary(); // _nonActuateSwitches = new Dictionary(); // _syncObjectSwitches = new object(); //} diff --git a/src/Libraries/ACATCore/ActuatorManagement/ActuatorSwitchBase.cs b/src/Libraries/ACATCore/ActuatorManagement/ActuatorSwitchBase.cs index 888cf9eb..2419f73e 100644 --- a/src/Libraries/ACATCore/ActuatorManagement/ActuatorSwitchBase.cs +++ b/src/Libraries/ACATCore/ActuatorManagement/ActuatorSwitchBase.cs @@ -16,6 +16,7 @@ using ACAT.Core.ActuatorManagement.Interfaces; using ACAT.Core.ActuatorManagement.Settings; using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Diagnostics; using System.IO; @@ -31,6 +32,8 @@ namespace ACAT.Core.ActuatorManagement /// public class ActuatorSwitchBase : IActuatorSwitch { + private readonly ILogger _logger; + /// /// The command verb to be used for a switch that /// is used for selection @@ -72,8 +75,9 @@ public class ActuatorSwitchBase : IActuatorSwitch /// /// Initializes the Switch object /// - public ActuatorSwitchBase() + public ActuatorSwitchBase(ILogger logger = null) { + _logger = logger; _isActive = false; Name = String.Empty; Source = String.Empty; @@ -85,8 +89,9 @@ public ActuatorSwitchBase() /// Initializes the switch object from the passed switch object /// /// Source switch object - public ActuatorSwitchBase(IActuatorSwitch switchObj) + public ActuatorSwitchBase(IActuatorSwitch switchObj, ILogger logger = null) { + _logger = logger; Name = switchObj.Name; Description = switchObj.Description; Source = switchObj.Source; diff --git a/src/Libraries/ACATCore/ActuatorManagement/Actuators.cs b/src/Libraries/ACATCore/ActuatorManagement/Actuators.cs index ea939f81..77b92f5a 100644 --- a/src/Libraries/ACATCore/ActuatorManagement/Actuators.cs +++ b/src/Libraries/ACATCore/ActuatorManagement/Actuators.cs @@ -6,6 +6,7 @@ using ACAT.Core.ActuatorManagement.Settings; using ACAT.Core.Utility; using ACAT.Core.Utility.TypeLoader; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.IO; @@ -22,6 +23,8 @@ namespace ACAT.Core.ActuatorManagement /// public class Actuators : IDisposable { + private readonly ILogger _logger; + /// /// If one of the dll found has an error with the certificate /// @@ -52,8 +55,9 @@ public class Actuators : IDisposable /// /// Initializes the Actuator object /// - public Actuators() + public Actuators(ILogger logger = null) { + _logger = logger; //_actuatorsTypeCache = new Dictionary(); _actuatorsEx = new List(); _actuators = new List(); diff --git a/src/Libraries/ACATCore/ActuatorManagement/BaseActuators/KeyboardSwitch.cs b/src/Libraries/ACATCore/ActuatorManagement/BaseActuators/KeyboardSwitch.cs index d421a2b2..26227ca0 100644 --- a/src/Libraries/ACATCore/ActuatorManagement/BaseActuators/KeyboardSwitch.cs +++ b/src/Libraries/ACATCore/ActuatorManagement/BaseActuators/KeyboardSwitch.cs @@ -16,6 +16,7 @@ using ACAT.Core.ActuatorManagement.Interfaces; using ACAT.Core.ActuatorManagement.Settings; using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; namespace ACAT.Core.ActuatorManagement.BaseActuators { @@ -27,6 +28,11 @@ namespace ACAT.Core.ActuatorManagement.BaseActuators /// internal class KeyboardSwitch : ActuatorSwitchBase { + /// + /// Logger instance for this class + /// + private readonly ILogger _logger; + /// /// Has this object been disposed? /// @@ -35,17 +41,19 @@ internal class KeyboardSwitch : ActuatorSwitchBase /// /// Initializes the keyboardswitch object /// - public KeyboardSwitch() + public KeyboardSwitch(ILogger logger) { + _logger = logger; } /// /// Initialize the keyboard actuator object /// /// - public KeyboardSwitch(IActuatorSwitch switchObj) + public KeyboardSwitch(IActuatorSwitch switchObj, ILogger logger) : base(switchObj) { + _logger = logger; } /// @@ -82,7 +90,7 @@ protected override void Dispose(bool disposing) { try { - Log.Verbose(); + _logger.LogTrace("Disposing KeyboardSwitch"); if (disposing) { diff --git a/src/Libraries/ACATCore/ActuatorManagement/UI/SwitchCommandMapForm.cs b/src/Libraries/ACATCore/ActuatorManagement/UI/SwitchCommandMapForm.cs index 6bbebe46..31748d97 100644 --- a/src/Libraries/ACATCore/ActuatorManagement/UI/SwitchCommandMapForm.cs +++ b/src/Libraries/ACATCore/ActuatorManagement/UI/SwitchCommandMapForm.cs @@ -14,6 +14,7 @@ using ACAT.Core.PanelManagement; using ACAT.Core.Utility; using ACATResources; +using Microsoft.Extensions.Logging; using System; using System.Windows.Forms; @@ -21,6 +22,11 @@ namespace ACAT.Core.ActuatorManagement { public partial class SwitchCommandMapForm : Form { + /// + /// Logger instance for this class + /// + private readonly ILogger _logger; + /// /// Aspect ratio of form at design time /// @@ -36,8 +42,9 @@ public partial class SwitchCommandMapForm : Form /// private bool _wrapText = true; - public SwitchCommandMapForm() + public SwitchCommandMapForm(ILogger logger) { + _logger = logger; InitializeComponent(); SelectedCommand = String.Empty; @@ -123,7 +130,7 @@ private void refreshDataGridView() { if (CommandManager.Instance?.AppCommandTable?.CmdDescriptors == null) { - Log.Debug("CommandManager or AppCommandTable not initialized"); + _logger.LogDebug("CommandManager or AppCommandTable not initialized"); return; } diff --git a/src/Libraries/ACATCore/ActuatorManagement/WinsockActuators/WinsockClientActuator/WinsockClientActuatorBase.cs b/src/Libraries/ACATCore/ActuatorManagement/WinsockActuators/WinsockClientActuator/WinsockClientActuatorBase.cs index 2b80b9a0..1498ce6e 100644 --- a/src/Libraries/ACATCore/ActuatorManagement/WinsockActuators/WinsockClientActuator/WinsockClientActuatorBase.cs +++ b/src/Libraries/ACATCore/ActuatorManagement/WinsockActuators/WinsockClientActuator/WinsockClientActuatorBase.cs @@ -18,6 +18,7 @@ using ACAT.Core.ActuatorManagement.Interfaces; using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Text; using System.Threading; @@ -36,6 +37,11 @@ namespace ACAT.Core.ActuatorManagement.WinsockActuators.WinsockClientActuator /// public class WinsockClientActuatorBase : ActuatorBase { + /// + /// Logger instance for this class + /// + private readonly ILogger _logger; + /// /// Socket client class that handles the client connection /// @@ -70,8 +76,9 @@ public class WinsockClientActuatorBase : ActuatorBase /// /// Initializes a new instance of the class. /// - public WinsockClientActuatorBase() + public WinsockClientActuatorBase(ILogger logger) { + _logger = logger; socketClient = null; } @@ -150,7 +157,7 @@ protected override void Dispose(bool disposing) { try { - Log.Verbose(); + _logger.LogTrace("Disposing WinsockClientActuatorBase"); _quitConnect = true; _evtConnectRetry.Set(); @@ -191,7 +198,7 @@ protected virtual void onConnected(System.Net.IPAddress address) protected virtual void onDataReceived(System.Net.IPAddress address, byte[] data) { string strData = Encoding.ASCII.GetString(data, 0, data.Length); - Log.Debug("Received data: " + strData); + _logger.LogDebug("Received data: {Data}", strData); // parse the string, find the switch that causes the trigger IActuatorSwitch switchObj = WinsockCommon.parseAndGetSwitch(strData, Switches, CreateSwitch); @@ -225,7 +232,7 @@ protected int Send(string msg) } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, "Error sending message"); } return -1; } @@ -259,7 +266,7 @@ protected void triggerEvent(IActuatorSwitch switchObj) /// Tcp/ip server address private void _socketClient_OnClientConnected(System.Net.IPAddress address) { - Log.Debug("Connected to" + address); + _logger.LogDebug("Connected to {Address}", address); onConnected(address); } @@ -269,7 +276,7 @@ private void _socketClient_OnClientConnected(System.Net.IPAddress address) /// Address of the tcp/ip server private void _socketClient_OnClientConnectionClosed(System.Net.IPAddress addr) { - Log.Debug("Disconnected from " + addr); + _logger.LogDebug("Disconnected from {Address}", addr); closeClientSocket(socketClient); socketClient = null; _evtConnectRetry.Set(); @@ -312,19 +319,19 @@ private void connectProc() { try { - Log.Debug("Trying to connecting to tcp/ip server"); + _logger.LogDebug("Trying to connecting to tcp/ip server"); socketClient ??= createSocketClient(); if (socketClient != null) { if (!socketClient.Connect()) { - Log.Debug("Tcp/ip server not detected. Will retry..."); + _logger.LogDebug("Tcp/ip server not detected. Will retry..."); Thread.Sleep(waitInterval); } else { - Log.Debug("Successfully connected to tcp/ip server"); + _logger.LogDebug("Successfully connected to tcp/ip server"); _evtConnectRetry.WaitOne(); _evtConnectRetry.Reset(); } @@ -336,11 +343,11 @@ private void connectProc() } catch (Exception ex) { - Log.Exception("Error connecting to server " + ex); + _logger.LogError(ex, "Error connecting to server"); } } - Log.Debug("Thread exited"); + _logger.LogDebug("Thread exited"); } /// diff --git a/src/Libraries/ACATCore/ActuatorManagement/WinsockActuators/WinsockCommon.cs b/src/Libraries/ACATCore/ActuatorManagement/WinsockActuators/WinsockCommon.cs index 308f81d2..eb5709e3 100644 --- a/src/Libraries/ACATCore/ActuatorManagement/WinsockActuators/WinsockCommon.cs +++ b/src/Libraries/ACATCore/ActuatorManagement/WinsockActuators/WinsockCommon.cs @@ -15,6 +15,7 @@ using ACAT.Core.ActuatorManagement.Interfaces; using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; @@ -28,6 +29,13 @@ namespace ACAT.Core.ActuatorManagement.WinsockActuators /// internal class WinsockCommon { + private static ILogger _logger; + + public static void SetLogger(ILogger logger) + { + _logger = logger; + } + public delegate IActuatorSwitch CreateSwitchDelegate(IActuatorSwitch s); /// @@ -45,8 +53,7 @@ public static SwitchAction getSwitchAction(string action) } catch (Exception e) { - Log.Warn("Image switch, invalid action specified " + action); - Log.Exception(e); + _logger?.LogWarning(e, "Image switch, invalid action specified {Action}", action); } return retVal; @@ -154,7 +161,7 @@ public static long parseLong(string val) } catch (Exception e) { - Log.Exception(e); + _logger?.LogError(e, "Error parsing long value {Value}", val); } return retVal; @@ -178,7 +185,7 @@ private static IActuatorSwitch getSwitchForGesture( var imageSwitch = switchObj; if (string.Compare(imageSwitch.Source, gesture, true) == 0) { - Log.Debug("Found switch object " + switchObj.Name + " for gesture" + gesture); + _logger?.LogDebug("Found switch object {SwitchName} for gesture {Gesture}", switchObj.Name, gesture); return createSwitchDel(switchObj); } } diff --git a/src/Libraries/ACATCore/ActuatorManagement/WinsockActuators/WinsockServerActuator/ClientConnHandler.cs b/src/Libraries/ACATCore/ActuatorManagement/WinsockActuators/WinsockServerActuator/ClientConnHandler.cs index 6728784f..93587031 100644 --- a/src/Libraries/ACATCore/ActuatorManagement/WinsockActuators/WinsockServerActuator/ClientConnHandler.cs +++ b/src/Libraries/ACATCore/ActuatorManagement/WinsockActuators/WinsockServerActuator/ClientConnHandler.cs @@ -13,6 +13,7 @@ //////////////////////////////////////////////////////////////////////////// using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.IO; using System.Net; @@ -28,6 +29,7 @@ namespace ACAT.Core.ActuatorManagement.WinsockActuators.WinsockServerActuator /// internal class ClientConnHandler : IDisposable { + private readonly ILogger _logger; public ConnectionStatus ClientConnectionStatus = ConnectionStatus.Disconnected; public string ID = string.Empty; public Thread WorkerThread; @@ -45,8 +47,9 @@ internal class ClientConnHandler : IDisposable /// Initializes a instance of the class /// /// The TcpClient connection that is connected to a client. - public ClientConnHandler(TcpClient client) + public ClientConnHandler(TcpClient client, ILogger logger) { + _logger = logger; tcpClient = client; clientStream = tcpClient.GetStream(); ID = Guid.NewGuid().ToString(); @@ -58,7 +61,7 @@ public ClientConnHandler(TcpClient client) } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, "Error getting remote endpoint"); } OnClientMsgReceived += ClientConnHandler_OnClientMsgReceived; @@ -166,7 +169,7 @@ public bool SendToClient(byte[] message, int count) } catch (Exception e) { - Log.Exception(e); + _logger.LogError(e, "Error sending to client"); return false; } } @@ -190,12 +193,12 @@ public void WorkerThreadMethod() { // blocks until a client sends a message bytesRead = clientStream.Read(message, 0, ReadBufferSize); - Log.Debug("Returned from read. Bytes read: " + bytesRead); + _logger.LogDebug("Returned from read. Bytes read: {BytesRead}", bytesRead); } catch (Exception e) { // Probably a socket exception. - Log.Error("SERVER: ClientConnHandler, exception reading stream " + e.StackTrace); + _logger.LogError(e, "SERVER: ClientConnHandler, exception reading stream"); break; } @@ -206,10 +209,10 @@ public void WorkerThreadMethod() } // Data has been received, let's process it. - Log.Debug("Calling OnClientMsgReceived"); + _logger.LogDebug("Calling OnClientMsgReceived"); OnClientMsgReceived?.Invoke(message, bytesRead); - Log.Debug("Returned from OnClientMsgReceived"); + _logger.LogDebug("Returned from OnClientMsgReceived"); } // Out of the WorkerThreadMethod loop... time to close stuff down. @@ -271,7 +274,7 @@ private void ClientConnHandler_OnClientMsgReceived(byte[] message, int count) /// Length of the data private void HandleClientMessage(byte[] messageFromClient, int count) { - Log.Debug("Received " + count + " bytes"); + _logger.LogDebug("Received {Count} bytes", count); lock (_lockObj) { int offset = 0; @@ -291,9 +294,9 @@ private void HandleClientMessage(byte[] messageFromClient, int count) Data = _memoryStream.ToArray() }; - Log.Debug(string.Format("Entire packet received. Calling threadpool for data received")); + _logger.LogDebug("Entire packet received. Calling threadpool for data received"); ThreadPool.QueueUserWorkItem(Worker, item); - Log.Debug(string.Format("Returned from QueueUserWorkItem")); + _logger.LogDebug("Returned from QueueUserWorkItem"); _memoryStream = new MemoryStream(); } @@ -324,7 +327,7 @@ private void SocketServer_OnServerShutdown() } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, "Error aborting worker thread"); } } diff --git a/src/Libraries/ACATCore/AgentManagement/AgentBase.cs b/src/Libraries/ACATCore/AgentManagement/AgentBase.cs index c430f257..bd5d0eb9 100644 --- a/src/Libraries/ACATCore/AgentManagement/AgentBase.cs +++ b/src/Libraries/ACATCore/AgentManagement/AgentBase.cs @@ -11,6 +11,7 @@ using ACAT.Core.PanelManagement.Common; using ACAT.Core.PreferencesManagement.Interfaces; using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; @@ -25,6 +26,11 @@ namespace ACAT.Core.AgentManagement /// public abstract class AgentBase : IApplicationAgent { + /// + /// Logger instance for this class + /// + private readonly ILogger _logger; + /// /// Used to invoke methods/properties in the agent /// @@ -58,8 +64,9 @@ public abstract class AgentBase : IApplicationAgent /// /// Initializes a new instance of the class. /// - protected AgentBase() + protected AgentBase(ILogger logger) { + _logger = logger; _name = Descriptor.Name; _invoker = new ExtensionInvoker(this); } @@ -399,11 +406,11 @@ protected void setTextInterface(TextControlAgentBase textInterface = null) { if (_textInterface != null) { - Log.Debug("Disposing " + _textInterface.GetType().Name); + _logger.LogDebug("Disposing {TextInterfaceType}", _textInterface.GetType().Name); _textInterface.Dispose(); } - Log.Debug("Setting textinterface to " + ((textInterface != null) ? textInterface.GetType().Name : "null")); + _logger.LogDebug("Setting textinterface to {TextInterfaceType}", ((textInterface != null) ? textInterface.GetType().Name : "null")); _textInterface = textInterface ?? _nullTextInterface; AgentManager.Instance.TextControlAgent = _textInterface; diff --git a/src/Libraries/ACATCore/AgentManagement/AgentUtils.cs b/src/Libraries/ACATCore/AgentManagement/AgentUtils.cs index cb053243..b4f608b8 100644 --- a/src/Libraries/ACATCore/AgentManagement/AgentUtils.cs +++ b/src/Libraries/ACATCore/AgentManagement/AgentUtils.cs @@ -6,6 +6,7 @@ //////////////////////////////////////////////////////////////////////////// using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Windows.Automation; using System.Windows.Forms; @@ -17,6 +18,12 @@ namespace ACAT.Core.AgentManagement /// public class AgentUtils { + private static ILogger _logger; + + public static void SetLogger(ILogger logger) + { + _logger = logger; + } /// /// Finds a descendent of the focused element that has the specified /// className, controlType and automationID @@ -75,8 +82,8 @@ public static AutomationElement GetElementOrAncestorByAutomationId(AutomationEle while (parent != null) { - Log.Debug("parent.ClassName: " + parent.Current.ClassName + ", parent.ControlType: " + - parent.Current.ControlType.ProgrammaticName + ", parent.AutoId: " + parent.Current.AutomationId); + _logger?.LogDebug("parent.ClassName: {ClassName}, parent.ControlType: {ControlType}, parent.AutoId: {AutoId}", + parent.Current.ClassName, parent.Current.ControlType.ProgrammaticName, parent.Current.AutomationId); if (String.Compare(parent.Current.ClassName, className, true) == 0 && String.Compare(parent.Current.ControlType.ProgrammaticName, controlType, true) == 0 && @@ -147,7 +154,8 @@ public static void InsertTextIntoElement(AutomationElement element, string value { if (!element.Current.IsEnabled || !element.Current.IsKeyboardFocusable) { - Log.Debug("Control not enabled or keyboard focusable. AutomationID " + element.Current.AutomationId); + _logger?.LogDebug("Control not enabled or keyboard focusable. AutomationID {AutomationId}", + element.Current.AutomationId); return; } @@ -164,7 +172,7 @@ public static void InsertTextIntoElement(AutomationElement element, string value } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger?.LogError(ex, "Error inserting text into element"); } } diff --git a/src/Libraries/ACATCore/AgentManagement/GenericAppAgentBase.cs b/src/Libraries/ACATCore/AgentManagement/GenericAppAgentBase.cs index 2ba5b78b..b6df6013 100644 --- a/src/Libraries/ACATCore/AgentManagement/GenericAppAgentBase.cs +++ b/src/Libraries/ACATCore/AgentManagement/GenericAppAgentBase.cs @@ -7,6 +7,7 @@ using ACAT.Core.AgentManagement.TextControlAgents; using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Windows.Automation; @@ -46,7 +47,7 @@ public abstract class GenericAppAgentBase : AgentBase /// was this handled? public override void OnFocusChanged(WindowActivityMonitorInfo monitorInfo, ref bool handled) { - Log.Verbose(); + _logger.LogTrace("OnFocusChanged"); disposeAndCreateTextInterface(monitorInfo); triggerTextChanged(appTextInterface); @@ -77,7 +78,7 @@ protected virtual TextControlAgentBase createEditControlTextInterface( AutomationElement focusedElement, ref bool handled) { - Log.Verbose(); + _logger.LogTrace("createEditControlTextInterface"); return new EditTextControlAgent(handleMain, focusedElement, ref handled); } @@ -114,10 +115,10 @@ protected override void OnDispose() /// event arg private void _textInterface_EvtTextChanged(object sender, TextChangedEventArgs e) { - Log.Verbose(); + _logger.LogTrace("_textInterface_EvtTextChanged"); if (e.TextInterface != null) { - Log.Debug("Calling triggertextchanged"); + _logger.LogDebug("Calling triggertextchanged"); triggerTextChanged(e.TextInterface); } } @@ -134,7 +135,7 @@ private TextControlAgentBase createEditControlTextInterface( AutomationElement focusedElement) { bool handled = false; - Log.Debug("base.createEditControlTextInterface()"); + _logger.LogDebug("base.createEditControlTextInterface()"); var textInterface = createEditControlTextInterface(handleMain, focusedElement, ref handled); if (handled) { diff --git a/src/Libraries/ACATCore/AgentManagement/Keyboard.cs b/src/Libraries/ACATCore/AgentManagement/Keyboard.cs index b9780bf9..debd8194 100644 --- a/src/Libraries/ACATCore/AgentManagement/Keyboard.cs +++ b/src/Libraries/ACATCore/AgentManagement/Keyboard.cs @@ -7,6 +7,7 @@ using ACAT.Core.AgentManagement.Interfaces; using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; @@ -21,6 +22,11 @@ namespace ACAT.Core.AgentManagement /// public class Keyboard : IKeyboard { + /// + /// Logger instance for this class + /// + private readonly ILogger _logger; + /// /// Windows keyboard layout /// @@ -37,6 +43,11 @@ private enum Flags KEYEVENTF_KEYUP = 0x0002 } + public Keyboard(ILogger logger) + { + _logger = logger; + } + /// /// Disposes resources /// @@ -56,7 +67,7 @@ public void Dispose() /// modifier key public void ExtendedKeyDown(Keys key) { - Log.Debug(key.ToString()); + _logger.LogDebug("ExtendedKeyDown: {Key}", key.ToString()); User32Interop.keybd_event((byte)key, 0xAA, 0, UIntPtr.Zero); } @@ -67,7 +78,7 @@ public void ExtendedKeyDown(Keys key) /// modifier key public void ExtendedKeyUp(Keys key) { - Log.Debug(key.ToString()); + _logger.LogDebug("ExtendedKeyUp: {Key}", key.ToString()); User32Interop.keybd_event((byte)key, 0xAA, (uint)Flags.KEYEVENTF_KEYUP, UIntPtr.Zero); } @@ -361,11 +372,11 @@ private bool shiftNeeded(char c) Log.Debug("virtualKey for [" + c + "] is " + virtualKey); if ((virtualKey & 0x100) == 0x100) { - Log.Debug("Shift needs to be pressed for [" + c + "]"); + _logger.LogDebug("Shift needs to be pressed for [{Char}]", c); return true; } - Log.Debug("Shift does not need to be pressed for [" + c + "]"); + _logger.LogDebug("Shift does not need to be pressed for [{Char}]", c); return false; } diff --git a/src/Libraries/ACATCore/Audit/AuditLog.cs b/src/Libraries/ACATCore/Audit/AuditLog.cs index f8dcf464..7eb8258f 100644 --- a/src/Libraries/ACATCore/Audit/AuditLog.cs +++ b/src/Libraries/ACATCore/Audit/AuditLog.cs @@ -6,6 +6,7 @@ //////////////////////////////////////////////////////////////////////////// using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.IO; @@ -20,6 +21,8 @@ namespace ACAT.Core.Audit /// public class AuditLog { + private static ILogger _logger; + /// /// Full path to the log file /// @@ -59,6 +62,8 @@ public class AuditLog /// static AuditLog() { + _logger = LoggerFactory.Create(builder => builder.AddConsole()).CreateLogger(); + string logFileFolder = FileUtils.GetLogsDir(); loadFilters(); @@ -67,7 +72,7 @@ static AuditLog() { if (!Directory.Exists(logFileFolder)) { - Log.Debug("Creating log directory."); + _logger.LogDebug("Creating log directory."); Directory.CreateDirectory(logFileFolder); } } @@ -89,7 +94,7 @@ static AuditLog() LogFileFullPath = Path.Combine(logFileFolder, Path.GetFileNameWithoutExtension(LogFileName) + CoreGlobals.LogFileSuffix + Path.GetExtension(LogFileName)); - Log.Debug("LogFileFullPath=" + LogFileFullPath); + _logger.LogDebug("LogFileFullPath=" + LogFileFullPath); /* objMutex = new Mutex(false, MutexName); diff --git a/src/Libraries/ACATCore/PanelManagement/Common/ScannerCommon.cs b/src/Libraries/ACATCore/PanelManagement/Common/ScannerCommon.cs index 47234d8b..314506a3 100644 --- a/src/Libraries/ACATCore/PanelManagement/Common/ScannerCommon.cs +++ b/src/Libraries/ACATCore/PanelManagement/Common/ScannerCommon.cs @@ -20,6 +20,7 @@ using ACAT.Core.WidgetManagement.Interfaces; using ACAT.Core.WidgetManagement.Layout; using ACAT.Core.Widgets; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Drawing; @@ -62,6 +63,11 @@ public class ScannerCommon : IDisposable, IPanelCommon /// private readonly SyncLock _syncLock; + /// + /// Logger instance + /// + private readonly ILogger _logger; + /// /// The animation manager object. Manages all animations /// @@ -137,8 +143,9 @@ public class ScannerCommon : IDisposable, IPanelCommon /// Initializes a new instance of the class /// /// The scanner Form object - public ScannerCommon(IScannerPanel iScannerPanel) + public ScannerCommon(IScannerPanel iScannerPanel, ILogger logger = null) { + _logger = logger; ScannerForm = iScannerPanel.Form; StartupArg = null; @@ -432,7 +439,7 @@ public void HideScanner() /// public bool Initialize(StartupArg startupArg) { - Log.Debug("Entered from Initialize"); + _logger?.LogDebug("Entered from Initialize"); Context.AppPanelManager.EvtPanelPreShow += AppPanelManager_EvtPanelPreShow; @@ -501,7 +508,7 @@ public bool Initialize(StartupArg startupArg) Context.AppPanelManager.EvtCalibrationStartNotify += AppPanelManager_EvtCalibrationStartNotify; Context.AppPanelManager.EvtCalibrationEndNotify += AppPanelManager_EvtCalibrationEndNotify; - Log.Debug("Returning from Initialize " + retVal); + _logger?.LogDebug("Returning from Initialize {RetVal}", retVal); return retVal; } @@ -543,7 +550,7 @@ public void OnClosing() } catch (Exception ex) { - Log.Exception(ex); + _logger?.LogError(ex, "Exception in OnClosing"); } } @@ -586,29 +593,29 @@ public void OnFormClosing(FormClosingEventArgs e) CoreGlobals.AppPreferences.EvtPreferencesChanged -= AppPreferences_EvtPreferencesChanged; - Log.Debug(ScannerForm.Name + ", _syncObj.Status: " + _syncLock.Status + ", hashcode: " + _syncLock.GetHashCode()); + _logger?.LogDebug("{FormName}, _syncObj.Status: {Status}, hashcode: {HashCode}", ScannerForm.Name, _syncLock.Status, _syncLock.GetHashCode()); if (_syncLock.Status != SyncLock.StatusValues.None) { - Log.Debug(ScannerForm.Name + ", _syncObj.Status: " + _syncLock.Status + ", form already closed. returning"); + _logger?.LogDebug("{FormName}, _syncObj.Status: {Status}, form already closed. returning", ScannerForm.Name, _syncLock.Status); return; } - Log.Debug(ScannerForm.Name + ", _syncObj.Status: " + _syncLock.Status + ", Will continue closing"); + _logger?.LogDebug("{FormName}, _syncObj.Status: {Status}, Will continue closing", ScannerForm.Name, _syncLock.Status); - Log.Debug("Setting _syncLock.Status to CLOSING " + ScannerForm.Name); + _logger?.LogDebug("Setting _syncLock.Status to CLOSING {FormName}", ScannerForm.Name); _syncLock.Status = SyncLock.StatusValues.Closing; if (_animationManager != null) { - Log.Verbose("Before animationmangoer.stop"); + _logger?.LogTrace("Before animationmangoer.stop"); _animationManager.Stop(); - Log.Verbose("After animationmangoer.stop"); + _logger?.LogTrace("After animationmangoer.stop"); } - Log.Verbose("Unsubscribe to EvtHeartbeat for " + ScannerForm.Name); + _logger?.LogTrace("Unsubscribe to EvtHeartbeat for {FormName}", ScannerForm.Name); WindowActivityMonitor.EvtWindowMonitorHeartbeat -= WindowActivityMonitor_EvtWindowMonitorHeartbeat; - Log.Verbose("Unsubscribe to EvtHeartbeat DONE for " + ScannerForm.Name); + _logger?.LogTrace("Unsubscribe to EvtHeartbeat DONE for {FormName}", ScannerForm.Name); PositionSizeController.OnClosing(); @@ -619,7 +626,7 @@ public void OnFormClosing(FormClosingEventArgs e) Context.AppPanelManager.EvtCalibrationStartNotify -= AppPanelManager_EvtCalibrationStartNotify; Context.AppPanelManager.EvtCalibrationEndNotify -= AppPanelManager_EvtCalibrationEndNotify; - Log.Debug("Exiting FormClosing for " + ScannerForm.Name); + _logger?.LogDebug("Exiting FormClosing for {FormName}", ScannerForm.Name); } /// diff --git a/src/Libraries/ACATCore/PanelManagement/Common/TextController.cs b/src/Libraries/ACATCore/PanelManagement/Common/TextController.cs index 7beb9837..603a16b7 100644 --- a/src/Libraries/ACATCore/PanelManagement/Common/TextController.cs +++ b/src/Libraries/ACATCore/PanelManagement/Common/TextController.cs @@ -9,6 +9,7 @@ using ACAT.Core.AgentManagement; using ACAT.Core.PanelManagement.Interfaces; using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Collections; using System.Linq; @@ -50,11 +51,17 @@ public class TextController : ITextController /// private static LastAction _lastAction = LastAction.Unknown; + /// + /// Logger instance + /// + private readonly ILogger _logger; + /// /// Initializes a new instance of the class. /// - internal TextController() + internal TextController(ILogger logger = null) { + _logger = logger; } /// @@ -101,7 +108,7 @@ public void AutoCompleteWord(string wordSelected) } bool isCapitalizedWordToReplace = false; - Log.Debug("Entered AutoCompleteWord"); + _logger?.LogDebug("Entered AutoCompleteWord"); try { using AgentContext context = Context.AppAgentMgr.ActiveContext(); @@ -116,19 +123,19 @@ public void AutoCompleteWord(string wordSelected) _autocompleteStartOffset = -1; context.TextAgent().GetPrevWordOffsetAutoComplete(out int offset, out int count); - Log.Debug("PrevWord offset: " + offset + ", count: " + count); + _logger?.LogDebug("PrevWord offset: {Offset}, count: {Count}", offset, count); CoreGlobals.Stopwatch4.Stop(); - Log.Debug("AutoComplete TimeElapsed 1: " + CoreGlobals.Stopwatch4.ElapsedMilliseconds); + _logger?.LogDebug("AutoComplete TimeElapsed 1: {ElapsedMilliseconds}", CoreGlobals.Stopwatch4.ElapsedMilliseconds); CoreGlobals.Stopwatch4.Reset(); CoreGlobals.Stopwatch4.Start(); // check if we are just completing the current word or inserting a new word bool checkInsert = context.TextAgent().CheckInsertOrReplaceWord(out int insertOrReplaceOffset, out string wordToReplace); - Log.Debug("checkInsert: " + checkInsert + ", insertorreplaceoffset: " + insertOrReplaceOffset + - ", caret: " + caretPos + ", caretPos-delprev: " + (caretPos - count)); - Log.Debug("wordtoReplace: " + wordToReplace); + _logger?.LogDebug("checkInsert: {CheckInsert}, insertorreplaceoffset: {Offset}, caret: {Caret}, caretPos-delprev: {CaretMinusCount}", + checkInsert, insertOrReplaceOffset, caretPos, caretPos - count); + _logger?.LogDebug("wordtoReplace: {WordToReplace}", wordToReplace); _autoCompletePartialWord = wordToReplace; @@ -139,12 +146,12 @@ public void AutoCompleteWord(string wordSelected) } CoreGlobals.Stopwatch4.Stop(); - Log.Debug("AutoComplete TimeElapsed 2: " + CoreGlobals.Stopwatch4.ElapsedMilliseconds); + _logger?.LogDebug("AutoComplete TimeElapsed 2: {ElapsedMilliseconds}", CoreGlobals.Stopwatch4.ElapsedMilliseconds); CoreGlobals.Stopwatch4.Reset(); CoreGlobals.Stopwatch4.Start(); - Log.Debug("checkInsert: " + checkInsert + ". inserRepOff: " + insertOrReplaceOffset + - ". wordTORep: " + wordToReplace); + _logger?.LogDebug("checkInsert: {CheckInsert}. inserRepOff: {Offset}. wordTORep: {Word}", + checkInsert, insertOrReplaceOffset, wordToReplace); if (KeyStateTracker.IsStickyShiftOn()) { @@ -158,7 +165,7 @@ public void AutoCompleteWord(string wordSelected) if (checkInsert) { - Log.Debug("Inserting [" + wordSelected + "] at offset " + insertOrReplaceOffset); + _logger?.LogDebug("Inserting [{WordSelected}] at offset {Offset}", wordSelected, insertOrReplaceOffset); CoreGlobals.Stopwatch5.Reset(); CoreGlobals.Stopwatch5.Start(); @@ -166,7 +173,7 @@ public void AutoCompleteWord(string wordSelected) context.TextAgent().Insert(insertOrReplaceOffset, wordSelected); CoreGlobals.Stopwatch5.Stop(); - Log.Debug("AutoComplete Insert operation TimeElapsed: " + CoreGlobals.Stopwatch5.ElapsedMilliseconds); + _logger?.LogDebug("AutoComplete Insert operation TimeElapsed: {ElapsedMilliseconds}", CoreGlobals.Stopwatch5.ElapsedMilliseconds); } else { @@ -183,14 +190,14 @@ public void AutoCompleteWord(string wordSelected) wordSelected = capitalizeWord(wordSelected); } - Log.Debug("Replacing word at offset " + insertOrReplaceOffset + ". Length: " + - wordToReplaceLength + ". with [" + wordSelected + "]"); + _logger?.LogDebug("Replacing word at offset {Offset}. Length: {Length}. with [{Word}]", + insertOrReplaceOffset, wordToReplaceLength, wordSelected); context.TextAgent().Replace(insertOrReplaceOffset, wordToReplaceLength, wordSelected); } CoreGlobals.Stopwatch4.Stop(); - Log.Debug("AutoComplete TimeElapsed 3: " + CoreGlobals.Stopwatch4.ElapsedMilliseconds); + _logger?.LogDebug("AutoComplete TimeElapsed 3: {ElapsedMilliseconds}", CoreGlobals.Stopwatch4.ElapsedMilliseconds); CoreGlobals.Stopwatch4.Reset(); CoreGlobals.Stopwatch4.Start(); @@ -201,30 +208,30 @@ public void AutoCompleteWord(string wordSelected) postAutoCompleteWord(); _autoCompleteCaretPos = context.TextAgent().GetCaretPos(); - Log.Debug("_autocompleteCursorPos is " + _autoCompleteCaretPos); + _logger?.LogDebug("_autocompleteCursorPos is {CaretPos}", _autoCompleteCaretPos); CoreGlobals.Stopwatch4.Stop(); - Log.Debug("AutoComplete TimeElapsed 4: " + CoreGlobals.Stopwatch4.ElapsedMilliseconds); + _logger?.LogDebug("AutoComplete TimeElapsed 4: {ElapsedMilliseconds}", CoreGlobals.Stopwatch4.ElapsedMilliseconds); } catch (InvalidAgentContextException iace) { - Log.Exception("Agent Context is invalid " + iace); + _logger?.LogError(iace, "Agent Context is invalid"); } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger?.LogError(ex, "Exception in AutoCompleteWord"); } finally { uint threadId = Kernel32Interop.GetCurrentThreadId(); - Log.Debug("Calling TextChangedNotifications.Release AFTER Autocompeting word"); + _logger?.LogDebug("Calling TextChangedNotifications.Release AFTER Autocompeting word"); Context.AppAgentMgr.TextChangedNotifications.Release(); - Log.Debug("Returned from TextChangedNotifications.Release AFTER Autocompeting word " + threadId); + _logger?.LogDebug("Returned from TextChangedNotifications.Release AFTER Autocompeting word {ThreadId}", threadId); } - Log.Debug("Exited AutoCompleteWord"); + _logger?.LogDebug("Exited AutoCompleteWord"); } /// @@ -251,12 +258,12 @@ public Abbreviation CheckAndReplaceAbbreviation(ref bool handled) if (CoreGlobals.AppPreferences.ExpandAbbreviationsOnSeparator && !TextUtils.IsTerminatorOrWhiteSpace(charAtCaret)) { - Log.Debug("no sentence terminator or white space here. returning"); + _logger?.LogDebug("no sentence terminator or white space here. returning"); return null; } int startPos = context.TextAgent().GetPreviousWordAtCaret(out string word); - Log.Debug("Prev word: " + word); + _logger?.LogDebug("Prev word: {Word}", word); if (string.IsNullOrEmpty(word)) { return null; @@ -274,9 +281,9 @@ public Abbreviation CheckAndReplaceAbbreviation(ref bool handled) string stringToCaret = context.TextAgent().GetStringToCaret(startPos); - Log.Debug("String to caret from startPos " + startPos + ": [" + stringToCaret + "]"); + _logger?.LogDebug("String to caret from startPos {StartPos}: [{StringToCaret}]", startPos, stringToCaret); replacement = stringToCaret.Replace(word, replacement); - Log.Debug("After replacement, replacement : [" + replacement + "]"); + _logger?.LogDebug("After replacement, replacement : [{Replacement}]", replacement); if (isFirstWord) { diff --git a/src/Libraries/ACATCore/PanelManagement/PanelManager.cs b/src/Libraries/ACATCore/PanelManagement/PanelManager.cs index cff9540f..18315835 100644 --- a/src/Libraries/ACATCore/PanelManagement/PanelManager.cs +++ b/src/Libraries/ACATCore/PanelManagement/PanelManager.cs @@ -10,6 +10,7 @@ using ACAT.Core.PanelManagement.PanelConfig; using ACAT.Core.UserControlManagement; using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Diagnostics; @@ -64,6 +65,11 @@ public class PanelManager : IDisposable /// private static PanelManager _instance; + /// + /// Logger instance + /// + private readonly ILogger _logger; + /// /// Represents the stack of panels /// @@ -82,8 +88,9 @@ public class PanelManager : IDisposable /// /// Initializes an instance of the PanelManager /// - public PanelManager() + public PanelManager(ILogger logger = null) { + _logger = logger; Context.AppAgentMgr.EvtPanelRequest += AppAgent_EvtPanelRequest; Context.AppAgentMgr.EvtFocusChanged += AppAgent_EvtFocusChanged; Context.EvtCultureChanged += Context_EvtCultureChanged; @@ -247,7 +254,7 @@ public void CloseCurrentForm() /// public void CloseCurrentPanel() { - Log.Verbose(); + _logger?.LogTrace("CloseCurrentPanel"); if (_stack.Count > 0) { @@ -563,7 +570,7 @@ protected virtual void Dispose(bool disposing) // Check to see if Dispose has already been called. if (!_disposed) { - Log.Verbose(); + _logger?.LogTrace("Dispose"); Context.EvtCultureChanged -= Context_EvtCultureChanged; @@ -584,7 +591,7 @@ private void AppActuatorManager_EvtCalibrationEndNotify(object sender, EventArgs { _actuatorCalibrationInProgress = false; - Log.Debug("Resuming WindowActivityMonitor"); + _logger?.LogDebug("Resuming WindowActivityMonitor"); WindowActivityMonitor.Resume(); @@ -606,7 +613,7 @@ private void AppActuatorManager_EvtCalibrationStartNotify(ActuatorManagement.Cal { _actuatorCalibrationInProgress = true; - Log.Debug("Pausing WindowActivityMonitor"); + _logger?.LogDebug("Pausing WindowActivityMonitor"); WindowActivityMonitor.Pause(); @@ -730,7 +737,7 @@ private void ScannerCommon_EvtScannerShow(object sender, ScannerShowEventArg arg /// event args private void SystemEvents_DisplaySettingsChanged(object sender, EventArgs e) { - Log.Debug("Display Resolution changed. Working area is " + Screen.PrimaryScreen.WorkingArea); + _logger?.LogDebug("Display Resolution changed. Working area is {WorkingArea}", Screen.PrimaryScreen.WorkingArea); EvtDisplaySettingsChanged?.Invoke(sender, e); } diff --git a/src/Libraries/ACATCore/PanelManagement/PanelStack.cs b/src/Libraries/ACATCore/PanelManagement/PanelStack.cs index 3b4055c4..2930b5f6 100644 --- a/src/Libraries/ACATCore/PanelManagement/PanelStack.cs +++ b/src/Libraries/ACATCore/PanelManagement/PanelStack.cs @@ -10,6 +10,7 @@ using ACAT.Core.PanelManagement.Interfaces; using ACAT.Core.PanelManagement.PanelConfig; using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Linq; using System.Windows.Automation; @@ -28,6 +29,11 @@ public class PanelStack { private static bool _appCloseNotifed; + /// + /// Logger instance + /// + private readonly ILogger _logger; + /// /// The currently active and visible scanner form. /// @@ -45,8 +51,9 @@ public class PanelStack /// /// Initializes an instance of the class /// - public PanelStack() + public PanelStack(ILogger logger = null) { + _logger = logger; PreShowPanel = null; PreShowPanelDisplayMode = DisplayModeTypes.None; } @@ -101,7 +108,7 @@ public DisplayModeTypes PanelDisplayMode public void AppAgent_EvtPanelRequest(object sender, PanelRequestEventArgs args) { - Log.Debug($"Panel Request: {args}"); + _logger?.LogDebug("Panel Request: {Args}", args); if (_currentForm != null) { @@ -109,7 +116,7 @@ public void AppAgent_EvtPanelRequest(object sender, PanelRequestEventArgs args) if (!args.UseCurrentScreenAsParent && IsModalBlocked(_currentForm, args.TargetPanel as IPanel)) { - Log.Warn("Model dialog open; request denied."); + _logger?.LogWarning("Model dialog open; request denied."); return; } } @@ -128,14 +135,14 @@ public void AppAgent_EvtPanelRequest(object sender, PanelRequestEventArgs args) private void LogCurrentFormState() { - Log.Verbose($"_currentForm: {_currentForm.Name}, Modal={_currentForm.Modal}"); + _logger?.LogTrace("_currentForm: {FormName}, Modal={Modal}", _currentForm.Name, _currentForm.Modal); if (_currentForm.Owner != null) { - Log.Verbose($"Owner: {_currentForm.Owner.Name}, Modal={_currentForm.Owner.Modal}"); + _logger?.LogTrace("Owner: {OwnerName}, Modal={Modal}", _currentForm.Owner.Name, _currentForm.Owner.Modal); } else { - Log.Verbose("_currentForm.Owner is null"); + _logger?.LogTrace("_currentForm.Owner is null"); } } @@ -165,7 +172,7 @@ private void HandleNewWindowRequest(PanelRequestEventArgs args, string requested if (currentScanner != null && PanelConfigMap.AreEqual(currentScanner.PanelClass, requestedPanelClass) && _currentPanel.Owner == null) { - Log.Debug("Current panel is already {0}, showing it", requestedPanelClass); + _logger?.LogDebug("Current panel is already {PanelClass}, showing it", requestedPanelClass); if (_currentPanel is MenuPanelBase menu) menu.SetTitle(args.Title); @@ -184,7 +191,7 @@ private void HandleExistingWindowRequest(PanelRequestEventArgs args, string requ IScannerPanel currentScanner = _currentPanel as IScannerPanel; if (currentScanner == null) { - Log.Debug("_currentPanel is null. Returning."); + _logger?.LogDebug("_currentPanel is null. Returning."); return; } @@ -201,20 +208,20 @@ private void HandleExistingWindowRequest(PanelRequestEventArgs args, string requ private void SwapPanel(PanelRequestEventArgs args, string requestedPanelClass) { - Log.Debug("Swapping panel to {0}", requestedPanelClass); + _logger?.LogDebug("Swapping panel to {PanelClass}", requestedPanelClass); Form newPanelForm = PanelManager.Instance.CreatePanel(requestedPanelClass, args.Title ) as Form; if (newPanelForm == null) { //MessageBox.Show($"Invalid form requested: {requestedPanelClass}"); - Log.Error($"Invalid form requested: {requestedPanelClass}"); + _logger?.LogError("Invalid form requested: {PanelClass}", requestedPanelClass); return; } if (args.UseCurrentScreenAsParent && _currentForm != null) { newPanelForm.Owner = _currentForm; - Log.Debug("Parent override enabled; new panel Owner set to _currentForm"); + _logger?.LogDebug("Parent override enabled; new panel Owner set to _currentForm"); } Show(null, newPanelForm as IPanel); diff --git a/src/Libraries/ACATCore/SpellCheckManagement/SpellCheckManager.cs b/src/Libraries/ACATCore/SpellCheckManagement/SpellCheckManager.cs index 5edb940f..fd9cb53b 100644 --- a/src/Libraries/ACATCore/SpellCheckManagement/SpellCheckManager.cs +++ b/src/Libraries/ACATCore/SpellCheckManagement/SpellCheckManager.cs @@ -9,6 +9,7 @@ using ACAT.Core.PanelManagement.Common; using ACAT.Core.SpellCheckManagement.Interfaces; using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Globalization; @@ -37,6 +38,11 @@ public class SpellCheckManager : IDisposable /// private static readonly SpellCheckManager _instance = new(); + /// + /// Logger instance + /// + private readonly ILogger _logger; + /// /// The active word predictor /// @@ -55,8 +61,9 @@ public class SpellCheckManager : IDisposable /// /// Initializes a new instance of the class. /// - private SpellCheckManager() + private SpellCheckManager(ILogger logger = null) { + _logger = logger; AppDomain currentDomain = AppDomain.CurrentDomain; currentDomain.AssemblyResolve += currentDomain_AssemblyResolve; diff --git a/src/Libraries/ACATCore/SpellCheckManagement/SpellCheckers.cs b/src/Libraries/ACATCore/SpellCheckManagement/SpellCheckers.cs index c21b6ef8..c87d4bb3 100644 --- a/src/Libraries/ACATCore/SpellCheckManagement/SpellCheckers.cs +++ b/src/Libraries/ACATCore/SpellCheckManagement/SpellCheckers.cs @@ -9,6 +9,7 @@ using ACAT.Core.SpellCheckManagement.Interfaces; using ACAT.Core.UserManagement; using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Globalization; @@ -35,6 +36,11 @@ public class SpellCheckers : IDisposable /// private static ISpellChecker _nullSpellChecker = null; + /// + /// Logger instance + /// + private readonly ILogger _logger; + /// /// The object that holds the preferred spellcheckers /// @@ -63,8 +69,9 @@ public class SpellCheckers : IDisposable /// /// Initializes an instance of the class /// - public SpellCheckers() + public SpellCheckers(ILogger logger = null) { + _logger = logger; _spellCheckersTypeCache = new Dictionary>(); PreferredSpellCheckers.FilePath = UserManager.GetFullPath(PreferredConfigFile); @@ -298,11 +305,11 @@ internal void Add(Guid guid, String language, Type type) { if (_spellCheckersTypeCache.ContainsKey(guid)) { - Log.Debug("SpellChecker " + type.FullName + ", guid " + guid + " is already added"); + _logger?.LogDebug("SpellChecker {TypeName}, guid {Guid} is already added", type.FullName, guid); return; } - Log.Debug("Adding SpellChecker " + type.FullName + ", guid " + guid + " to cache"); + _logger?.LogDebug("Adding SpellChecker {TypeName}, guid {Guid} to cache", type.FullName, guid); _spellCheckersTypeCache.Add(guid, new Tuple(language, type)); } diff --git a/src/Libraries/ACATCore/TTSManagement/TTSEngines.cs b/src/Libraries/ACATCore/TTSManagement/TTSEngines.cs index 8b43441c..4fa413b1 100644 --- a/src/Libraries/ACATCore/TTSManagement/TTSEngines.cs +++ b/src/Libraries/ACATCore/TTSManagement/TTSEngines.cs @@ -8,6 +8,7 @@ using ACAT.Core.UserManagement; using ACAT.Core.Utility; using ACAT.Core.Extensions; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Globalization; @@ -38,6 +39,11 @@ public class TTSEngines : IDisposable /// private static ITTSEngine _nullTTSEngine = null; + /// + /// Logger instance + /// + private readonly ILogger _logger; + /// /// Table mapping the GUID and culture to the TTSEngine type /// @@ -68,8 +74,9 @@ public class TTSEngines : IDisposable /// /// Initializes a new instance of the class /// - public TTSEngines() + public TTSEngines(ILogger logger = null) { + _logger = logger; _ttsEnginesTypeCache = new Dictionary>(); PreferredTTSEngines.FilePath = UserManager.GetFullPath(PreferredConfigFile); @@ -328,11 +335,11 @@ internal void Add(Guid guid, String language, Type type) { if (_ttsEnginesTypeCache.ContainsKey(guid)) { - Log.Debug("TTS Engine" + type.FullName + ", guid " + guid + " is already added"); + _logger?.LogDebug("TTS Engine {TypeName}, guid {Guid} is already added", type.FullName, guid); return; } - Log.Debug("Adding TTS Engine " + type.FullName + ", guid " + guid + " to cache"); + _logger?.LogDebug("Adding TTS Engine {TypeName}, guid {Guid} to cache", type.FullName, guid); _ttsEnginesTypeCache.Add(guid, new Tuple(language, type)); } diff --git a/src/Libraries/ACATCore/TTSManagement/TTSManager.cs b/src/Libraries/ACATCore/TTSManagement/TTSManager.cs index 92be58c7..9d0dd08d 100644 --- a/src/Libraries/ACATCore/TTSManagement/TTSManager.cs +++ b/src/Libraries/ACATCore/TTSManagement/TTSManager.cs @@ -11,6 +11,7 @@ using ACAT.Core.PreferencesManagement; using ACAT.Core.TTSManagement.Interfaces; using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Globalization; @@ -55,6 +56,11 @@ public class TTSManager : IDisposable /// private static readonly TTSManager _instance = new(); + /// + /// Logger instance + /// + private readonly ILogger _logger; + /// /// Has this object been disposed /// @@ -68,8 +74,9 @@ public class TTSManager : IDisposable /// /// Initializes the singleton instance of the class /// - private TTSManager() + private TTSManager(ILogger logger = null) { + _logger = logger; ActiveEngine = TTSEngines.NullTTSEngine; Context.EvtCultureChanged += Context_EvtCultureChanged; } diff --git a/src/Libraries/ACATCore/UserControlManagement/UserControlCommon.cs b/src/Libraries/ACATCore/UserControlManagement/UserControlCommon.cs index 33d120cc..7282fe45 100644 --- a/src/Libraries/ACATCore/UserControlManagement/UserControlCommon.cs +++ b/src/Libraries/ACATCore/UserControlManagement/UserControlCommon.cs @@ -14,6 +14,7 @@ using ACAT.Core.WidgetManagement; using ACAT.Core.WidgetManagement.Interfaces; using ACAT.Core.Widgets; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Runtime.InteropServices; @@ -24,8 +25,11 @@ namespace ACAT.Core.UserControlManagement { public class UserControlCommon : IUserControlCommon, IDisposable { - public UserControlCommon(IUserControl userControl, UserControlConfigMapEntry mapEntry, IScannerPanel iScannerPanel) + private readonly ILogger _logger; + + public UserControlCommon(IUserControl userControl, UserControlConfigMapEntry mapEntry, IScannerPanel iScannerPanel, ILogger logger) { + _logger = logger; ScannerForm = iScannerPanel.Form; this.mapEntry = mapEntry; ScannerPanel = iScannerPanel; @@ -92,7 +96,7 @@ public void Dispose() public bool Initialize() { - Log.Debug("Entered from Initialize"); + _logger.LogDebug("Entered from Initialize"); bool retVal = initWidgetManager(mapEntry); @@ -101,7 +105,7 @@ public bool Initialize() retVal = initAnimationManager(mapEntry); } - Log.Debug("Returning from Initialize " + retVal); + _logger.LogDebug("Returning from Initialize {RetVal}", retVal); WindowActivityMonitor.EvtWindowMonitorHeartbeat += WindowActivityMonitorEvtWindowMonitorHeartbeat; @@ -123,7 +127,7 @@ public void OnClosing() } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, "Exception in OnClosing"); } } @@ -145,31 +149,31 @@ public void OnFormClosing(FormClosingEventArgs e) } } - Log.Debug(ScannerForm.Name + ", SyncObj.Status: " + SyncLock.Status + ", hashcode: " + SyncLock.GetHashCode()); + _logger.LogDebug("{ScannerFormName}, SyncObj.Status: {Status}, hashcode: {HashCode}", ScannerForm.Name, SyncLock.Status, SyncLock.GetHashCode()); if (SyncLock.Status != SyncLock.StatusValues.None) { - Log.Debug(ScannerForm.Name + ", SyncObj.Status: " + SyncLock.Status + ", form already closed. returning"); + _logger.LogDebug("{ScannerFormName}, SyncObj.Status: {Status}, form already closed. returning", ScannerForm.Name, SyncLock.Status); return; } - Log.Debug(ScannerForm.Name + ", SyncObj.Status: " + SyncLock.Status + ", Will continue closing"); + _logger.LogDebug("{ScannerFormName}, SyncObj.Status: {Status}, Will continue closing", ScannerForm.Name, SyncLock.Status); - Log.Debug("Setting SyncLock.Status to CLOSING " + ScannerForm.Name); + _logger.LogDebug("Setting SyncLock.Status to CLOSING {ScannerFormName}", ScannerForm.Name); SyncLock.Status = SyncLock.StatusValues.Closing; - Log.Debug("Before animationmangoer.stop"); + _logger.LogDebug("Before animationmangoer.stop"); AnimationManager.Stop(); - Log.Debug("After animationmangoer.stop"); + _logger.LogDebug("After animationmangoer.stop"); - Log.Debug("Unsubscribe to EvtHeartbeat for " + ScannerForm.Name); + _logger.LogDebug("Unsubscribe to EvtHeartbeat for {ScannerFormName}", ScannerForm.Name); WindowActivityMonitor.EvtWindowMonitorHeartbeat -= WindowActivityMonitorEvtWindowMonitorHeartbeat; - Log.Debug("Unsubscribe to EvtHeartbeat DONE for " + ScannerForm.Name); + _logger.LogDebug("Unsubscribe to EvtHeartbeat DONE for {ScannerFormName}", ScannerForm.Name); unsubscribeEvents(); - Log.Debug("Exiting FormClosing for " + ScannerForm.Name); + _logger.LogDebug("Exiting FormClosing for {ScannerFormName}", ScannerForm.Name); } [EnvironmentPermission(SecurityAction.LinkDemand, Unrestricted = true)] @@ -195,7 +199,7 @@ public void OnPause() } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex, "Exception in OnPause"); } } @@ -214,7 +218,7 @@ public void OnResume() } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex, "Exception in OnResume"); } } @@ -223,7 +227,7 @@ protected virtual void Dispose(bool disposing) // Check to see if Dispose has already been called. if (!disposed) { - Log.Verbose(); + _logger.LogTrace("Disposing UserControlCommon"); if (disposing) { @@ -273,7 +277,7 @@ private bool initAnimationManager(UserControlConfigMapEntry panelConfigMapEntry) if (!retVal) { - Log.Error("Error initializing animation manager"); + _logger.LogError("Error initializing animation manager"); AnimationManager = null; } @@ -289,7 +293,7 @@ private bool initWidgetManager(UserControlConfigMapEntry mapEntry) bool retVal = WidgetManager.Initialize(mapEntry.ConfigFileName); if (!retVal) { - Log.Error("Unable to initialize widget manager"); + _logger.LogError("Unable to initialize widget manager"); } else { @@ -314,7 +318,7 @@ public void runCommand(String command) command = command.Substring(1); } - Log.Debug("Calling scanner common runcomand with " + command); + _logger.LogDebug("Calling scanner common runcomand with {Command}", command); ScannerForm.Invoke(new MethodInvoker(delegate { String[] parts = command.Split('.'); @@ -362,7 +366,7 @@ private void setWidgetEnabledStates(WindowActivityMonitorInfo monitorInfo) { if (SyncLock.IsClosing()) { - Log.Debug("Form is closing " + ScannerForm.Name); + _logger.LogDebug("Form is closing {ScannerFormName}", ScannerForm.Name); WindowActivityMonitor.EvtWindowMonitorHeartbeat -= WindowActivityMonitorEvtWindowMonitorHeartbeat; return; } @@ -391,7 +395,7 @@ private void setWidgetEnabledStates(WindowActivityMonitorInfo monitorInfo) break; } - Log.Verbose($"widget.Enabled set to: {widget.Enabled} for feature {widget.Name}"); + _logger.LogTrace("widget.Enabled set to: {Enabled} for feature {WidgetName}", widget.Enabled, widget.Name); } } } @@ -418,7 +422,7 @@ private void subscribeToEvents() private void textToSpeech(String text) { - Log.Debug("Convert to speech. text=" + text); + _logger.LogDebug("Convert to speech. text={Text}", text); Context.AppTTSManager.ActiveEngine.Speak(text); } @@ -449,7 +453,7 @@ private void widgetEvtActuated(object sender, WidgetActuatedEventArgs e) var value = widget.Value; if (!String.IsNullOrEmpty(value)) { - Log.Debug("**Actuate** " + widget.Name + " Value: " + value); + _logger.LogDebug("**Actuate** {WidgetName} Value: {Value}", widget.Name, value); actuateButton(widget); } diff --git a/src/Libraries/ACATCore/UserControlManagement/UserControlManager.cs b/src/Libraries/ACATCore/UserControlManagement/UserControlManager.cs index 359ed66f..ca81eb52 100644 --- a/src/Libraries/ACATCore/UserControlManagement/UserControlManager.cs +++ b/src/Libraries/ACATCore/UserControlManagement/UserControlManager.cs @@ -15,6 +15,7 @@ using ACAT.Core.Utility; using ACAT.Core.WidgetManagement; using ACAT.Core.Widgets; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Windows.Forms; @@ -28,6 +29,7 @@ namespace ACAT.Core.UserControlManagement /// public class UserControlManager { + private readonly ILogger _logger; private int _iterationCount = 0; private int _iterations = 1; private volatile bool _playerTransitioned = false; @@ -40,9 +42,8 @@ public class UserControlManager private readonly Dictionary _userControlCache = new(); - public UserControlManager(IScannerPanel scannerPanel, TextController textController) - { - _scannerPanel = scannerPanel; + public UserControlManager(IScannerPanel scannerPanel, TextController textController, ILogger logger) + { _logger = logger; _scannerPanel = scannerPanel; GridScanIterations = CoreGlobals.AppPreferences.GridScanIterations; _textController = textController; } @@ -92,7 +93,7 @@ public static List findAllWidgets(List list) } catch (Exception es) { - Log.Exception("Error geting widgets: " + es.ToString()); + _logger.LogError(es, "Error geting widgets: {Exception}", es.ToString()); } return Widgets; } @@ -151,12 +152,12 @@ public void OnClosing() public void OnPause() { - Log.Debug("CALIBTEST UserControlManager.OnPause()"); + _logger.LogDebug("CALIBTEST UserControlManager.OnPause()"); _playerTransitioned = false; foreach (var userControl in _userControls) { - Log.Verbose("CALIBTEST calling onPause for " + userControl.Descriptor.Name); + _logger.LogTrace("CALIBTEST calling onPause for {UserControlName}", userControl.Descriptor.Name); userControl.OnPause(); } } @@ -165,15 +166,15 @@ public void OnResume() { _stopTopLevelAnimation = true; - Log.Debug("CALIBTEST UserControlManager.OnResume()"); + _logger.LogDebug("CALIBTEST UserControlManager.OnResume()"); foreach (var userControl in _userControls) { - Log.Verbose("CALIBTEST. Calling onResume for uc" + userControl.Descriptor.Name); + _logger.LogTrace("CALIBTEST. Calling onResume for uc{UserControlName}", userControl.Descriptor.Name); userControl.OnResume(); } - Log.Debug("CALIBTEST Calling StartTopLevelAnimation"); + _logger.LogDebug("CALIBTEST Calling StartTopLevelAnimation"); StartTopLevelAnimation(); } @@ -204,7 +205,7 @@ public bool PopUserControl(Control parent) } else { - Log.Warn("MLEAK: list.Count is already zero"); + _logger.LogWarning("MLEAK: list.Count is already zero"); } } @@ -255,7 +256,7 @@ public void StartTopLevelAnimation() if (_userControls.Count > 0) { - Log.Debug("CALIBTEST StartTopLevelAnimation. Starting animation for " + _userControls[0].Descriptor.Name); + _logger.LogDebug("CALIBTEST StartTopLevelAnimation. Starting animation for {UserControlName}", _userControls[0].Descriptor.Name); _userControls[0].UserControlCommon.AnimationManager.Start(); } } @@ -298,7 +299,7 @@ private bool addUserControlByKey(Control parent, String userControlKeyName, obje } catch (Exception ex) { - Log.Exception("Unable to load userControl " + userControlName + ", exception: " + ex.ToString()); + _logger.LogError(ex, "Unable to load userControl {UserControlName}", userControlName); retVal = false; } @@ -314,7 +315,7 @@ private bool addUserControlByName(Control parent, String userControlName, object } catch (Exception ex) { - Log.Exception("Unable to load userControl " + userControlName + ", exception: " + ex.ToString()); + _logger.LogError(ex, "Unable to load userControl {UserControlName}", userControlName); retVal = false; } @@ -323,29 +324,29 @@ private bool addUserControlByName(Control parent, String userControlName, object private void animationManager_EvtPlayerAnimationTransition(object sender, string animationName, bool isTopLevel) { - Log.Debug("AP1: transition " + animationName + ", isTopLevel: " + isTopLevel); + _logger.LogDebug("AP1: transition {AnimationName}, isTopLevel: {IsTopLevel}", animationName, isTopLevel); if (!isTopLevel) { - Log.Verbose("AP1: SETTING _PlayerTransitioned to TRUE"); + _logger.LogTrace("AP1: SETTING _PlayerTransitioned to TRUE"); _playerTransitioned = true; _iterationCount = 0; } else { - Log.Verbose("AP1: SETTING _PlayerTransitioned to FALSE"); + _logger.LogTrace("AP1: SETTING _PlayerTransitioned to FALSE"); _playerTransitioned = false; } } private void appActuatorManager_EvtSwitchActivated(object sender, ActuatorSwitchEventArgs e) { - Log.Debug("Switch activated"); + _logger.LogDebug("Switch activated"); foreach (var userControl in _userControls) { var playerState = userControl.UserControlCommon.AnimationManager.GetPlayerState(); - Log.Verbose("userControl: " + userControl.Descriptor.Name + ", state: " + playerState); + _logger.LogTrace("userControl: {UserControlName}, state: {PlayerState}", userControl.Descriptor.Name, playerState); if (playerState != PlayerState.Timeout && playerState != PlayerState.Interrupted) { @@ -387,12 +388,12 @@ private bool createAndInitializeUserControl(Control parent, String userControlNa iUserControl = (userControl as IUserControl); _userControlCache.Add(iUserControl.Descriptor.Id, iUserControl); - Log.Verbose("Adding UserControl to cache: " + iUserControl.Descriptor.Name); + _logger.LogTrace("Adding UserControl to cache: {UserControlName}", iUserControl.Descriptor.Name); } else { userControl = (iUserControl as UserControl); - Log.Verbose("Got UserControl from cache: " + iUserControl.Descriptor.Name); + _logger.LogTrace("Got UserControl from cache: {UserControlName}", iUserControl.Descriptor.Name); } if (tag != null) @@ -427,12 +428,12 @@ private bool createAndInitializeUserControl(Control parent, String userControlNa private IUserControl getNextUserControl(IUserControl userControl) { int ii; - Log.Verbose("AP1 Find next user control. Count: " + _userControls.Count); + _logger.LogTrace("AP1 Find next user control. Count: {Count}", _userControls.Count); for (ii = 0; ii < _userControls.Count; ii++) { if (_userControls[ii] == userControl) { - Log.Verbose("AP1 Found! ii = " + ii); + _logger.LogTrace("AP1 Found! ii = {Index}", ii); break; } } @@ -445,7 +446,7 @@ private IUserControl getNextUserControl(IUserControl userControl) ii = 0; } - Log.Verbose("AP1 Returning next user control " + _userControls[ii].Descriptor.Name); + _logger.LogTrace("AP1 Returning next user control {UserControlName}", _userControls[ii].Descriptor.Name); return _userControls[ii]; } @@ -471,23 +472,23 @@ private void removeUserControl(Control parent, IUserControl userControl) private void userControl_EvtPlayerStateChanged(IUserControl userControl, PlayerStateChangedEventArgs e) { - Log.Verbose("AP1 playerStateChanged for " + userControl.Descriptor.Name + ", " + "newState: " + e.NewState); + _logger.LogTrace("AP1 playerStateChanged for {UserControlName}, newState: {NewState}", userControl.Descriptor.Name, e.NewState); if (_playerTransitioned) { - Log.Verbose("AP1: _playterTransitioned is TRUE. Returning"); + _logger.LogTrace("AP1: _playterTransitioned is TRUE. Returning"); return; } if (_stopTopLevelAnimation) { - Log.Verbose("AP1: _stopTopLevelanimation is TRUE. Returning"); + _logger.LogTrace("AP1: _stopTopLevelanimation is TRUE. Returning"); return; } if (e.NewState == PlayerState.Timeout) { - Log.Verbose("PlayerState timeout for " + userControl.Descriptor.Name); + _logger.LogTrace("PlayerState timeout for {UserControlName}", userControl.Descriptor.Name); var next = getNextUserControl(userControl); if (next != null) { @@ -495,7 +496,7 @@ private void userControl_EvtPlayerStateChanged(IUserControl userControl, PlayerS if (_iterationCount < _iterations) { - Log.Verbose("AP1 Calling start on " + next.Descriptor.Name); + _logger.LogTrace("AP1 Calling start on {UserControlName}", next.Descriptor.Name); next.UserControlCommon.AnimationManager.Start(); } } diff --git a/src/Libraries/ACATCore/UserManagement/UserManager.cs b/src/Libraries/ACATCore/UserManagement/UserManager.cs index 86cb66dd..195cea50 100644 --- a/src/Libraries/ACATCore/UserManagement/UserManager.cs +++ b/src/Libraries/ACATCore/UserManagement/UserManager.cs @@ -6,6 +6,7 @@ //////////////////////////////////////////////////////////////////////////// using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Globalization; using System.IO; @@ -23,6 +24,8 @@ namespace ACAT.Core.UserManagement /// public class UserManager { + private static ILogger _logger; + public const String BaseUserInstallDir = "Install\\Users"; /// @@ -40,6 +43,7 @@ public class UserManager /// static UserManager() { + _logger = LoggerFactory.Create(builder => builder.AddConsole()).CreateLogger(); _currentUserName = DefaultUserName; } @@ -136,7 +140,7 @@ public static bool CreateUserDir(String userName) { MessageBox.Show("Error creating dir. ex: " + ex); - Log.Exception(ex.ToString()); + _logger.LogError(ex, ex.Message); retVal = false; } diff --git a/src/Libraries/ACATCore/Utility/AutomationEventManager.cs b/src/Libraries/ACATCore/Utility/AutomationEventManager.cs index 605675b1..65f585d4 100644 --- a/src/Libraries/ACATCore/Utility/AutomationEventManager.cs +++ b/src/Libraries/ACATCore/Utility/AutomationEventManager.cs @@ -5,6 +5,7 @@ // //////////////////////////////////////////////////////////////////////////// +using Microsoft.Extensions.Logging; using System; using System.Collections; using System.Collections.Generic; @@ -30,6 +31,8 @@ namespace ACAT.Core.Utility /// public class AutomationEventManager : IDisposable { + private readonly ILogger _logger; + /// /// Returns the singleton instance /// @@ -65,8 +68,9 @@ public class AutomationEventManager : IDisposable /// /// Prevents a default instance of AutomationEventManager class from being created /// - private AutomationEventManager() + private AutomationEventManager(ILogger logger = null) { + _logger = logger; Start(); } @@ -91,7 +95,7 @@ public static void AddAutomationEventHandler(IntPtr hWnd, AutomationElement element, AutomationEventHandler eventHandler) { - Log.Verbose(); + _logger?.LogTrace("AddAutomationEventHandler called"); var windowElement = (WindowElement)WindowTable[hWnd]; if (windowElement == null) @@ -113,7 +117,7 @@ public static void AddAutomationEventHandler(IntPtr hWnd, } else { - Log.Debug("Found window element"); + _logger?.LogDebug("Found window element"); } // create the item and add it @@ -168,7 +172,7 @@ public static void AddAutomationPropertyChangedEventHandler(IntPtr hWnd, /// window handle public static void RemoveAllAutomationEventHandlers(IntPtr hwnd) { - Log.Debug(hwnd.ToString()); + _instance._logger?.LogDebug("RemoveAllAutomationEventHandlers: {Hwnd}", hwnd); lock (WindowTable) { @@ -177,17 +181,17 @@ public static void RemoveAllAutomationEventHandlers(IntPtr hwnd) var windowElement = (WindowElement)WindowTable[hwnd]; windowElement.EvtOnWindowClosed -= windowElement_EvtOnWindowClosed; - Log.Debug("Found " + hwnd + " in hashtable. removing it"); + _instance._logger?.LogDebug("Found {Hwnd} in hashtable. removing it", hwnd); WindowTable.Remove(hwnd); - Log.Debug("Calling RemoveAllEvents"); + _instance._logger?.LogDebug("Calling RemoveAllEvents"); var item = new RemoveAllEventsItem { WinElement = windowElement }; RemoveAllEvents(item); } else { - Log.Debug("Did not find " + hwnd + " in hashtable."); + _instance._logger?.LogDebug("Did not find {Hwnd} in hashtable", hwnd); } } } @@ -200,7 +204,7 @@ public static void RemoveAllAutomationEventHandlers(IntPtr hwnd) /// the automation element public static void RemoveAutomationEventHandler(IntPtr hWnd, AutomationEvent autoEvent, AutomationElement element) { - Log.Debug("hWnd=" + hWnd); + _instance._logger?.LogDebug("RemoveAutomationEventHandler: hWnd={HWnd}", hWnd); if (hWnd != IntPtr.Zero) { lock (WindowTable) @@ -234,7 +238,7 @@ public static void RemoveAutomationPropertyChangedEventHandler(IntPtr hWnd, AutomationElement element, AutomationPropertyChangedEventHandler eventHandler) { - Log.Verbose(); + _instance._logger?.LogTrace("RemoveAutomationPropertyChangedEventHandler called"); if (hWnd == IntPtr.Zero) { @@ -310,11 +314,11 @@ public void HandlerThread() } else if (obj is DoneEventHandlerItem) { - Log.Debug("Received command to quit thread"); + _logger?.LogDebug("Received command to quit thread"); _done = true; } } - Log.Debug("Exiting Handler Thread"); + _logger?.LogDebug("Exiting Handler Thread"); } /// @@ -346,7 +350,7 @@ protected virtual void Dispose(bool disposing) // Check to see if Dispose has already been called. if (!_disposed) { - Log.Verbose(); + _logger?.LogTrace("Dispose called"); try { @@ -358,15 +362,15 @@ protected virtual void Dispose(bool disposing) _queue.Enqueue(item); - Log.Debug("Aborting thread..."); + _logger?.LogDebug("Aborting thread..."); _thread.Abort(); - Log.Debug("Returned from abort"); + _logger?.LogDebug("Returned from abort"); // Wait until oThread finishes. Join also has overloads // that take a millisecond interval or a TimeSpan object. - Log.Debug("Calling Join"); + _logger?.LogDebug("Calling Join"); _thread.Join(); - Log.Debug("REturned from join"); + _logger?.LogDebug("Returned from join"); // dispose all managed resources. Automation.RemoveAllEventHandlers(); @@ -472,7 +476,7 @@ private static void RemoveAutomationPropertyChanged(RemoveAutomationPropertyChan /// handle to the window that was closed private static void windowElement_EvtOnWindowClosed(IntPtr hwnd) { - Log.Debug(hwnd.ToString()); + _instance._logger?.LogDebug("Window closed: {Hwnd}", hwnd); RemoveAllAutomationEventHandlers(hwnd); } @@ -569,7 +573,7 @@ public WindowElement(IntPtr handle) } catch (Exception ex) { - Log.Exception(ex.ToString()); + _instance._logger?.LogError(ex, "Exception in WindowElement constructor"); } } @@ -592,38 +596,38 @@ public WindowElement(IntPtr handle) /// the event handler public void AddAutomationEventHandler(AutomationElement element, AutomationEvent autoEvent, AutomationEventHandler eventHandler) { - Log.Verbose(); + _instance._logger?.LogTrace("AddAutomationEventHandler called"); try { var events = (Hashtable)_controlElements[element]; if (events == null) { - Log.Debug("events Arraylist is null. Creating one..."); + _instance._logger?.LogDebug("events Arraylist is null. Creating one..."); _controlElements.Add(element, new Hashtable()); events = (Hashtable)_controlElements[element]; } if (!events.Contains(autoEvent)) { - Log.Debug("Events array does not contain. Adding automation event " + - autoEvent.ProgrammaticName + - ". AutomationID: " + (element.Current.AutomationId ?? "none")); + _instance._logger?.LogDebug("Events array does not contain. Adding automation event {EventName}. AutomationID: {AutomationId}", + autoEvent.ProgrammaticName, + element.Current.AutomationId ?? "none"); Automation.AddAutomationEventHandler(autoEvent, element, TreeScope.Element, eventHandler); - Log.Debug("Returned from AddAutomationEventHandler"); + _instance._logger?.LogDebug("Returned from AddAutomationEventHandler"); events.Add(autoEvent, eventHandler); - Log.Debug("Done adding"); + _instance._logger?.LogDebug("Done adding"); } else { - Log.Debug("Event already registered. Will not be readded" + - autoEvent.ProgrammaticName + - ". AutomationID: " + (element.Current.AutomationId ?? "none")); + _instance._logger?.LogDebug("Event already registered. Will not be readded {EventName}. AutomationID: {AutomationId}", + autoEvent.ProgrammaticName, + element.Current.AutomationId ?? "none"); } } catch (Exception e) { - Log.Exception("Exception occured! e=" + e.ToString()); + _instance._logger?.LogError(e, "Exception occurred in AddAutomationEventHandler"); } } @@ -637,7 +641,7 @@ public void AddAutomationPropertyChangedEventHandler(AutomationElement element, AutomationProperty property, AutomationPropertyChangedEventHandler eventHandler) { - Log.Verbose(); + _instance._logger?.LogTrace("AddAutomationPropertyChangedEventHandler called"); try { @@ -652,8 +656,9 @@ public void AddAutomationPropertyChangedEventHandler(AutomationElement element, { Automation.AddAutomationPropertyChangedEventHandler(element, TreeScope.Element, onPropertyChanged, property); - Log.Debug("Adding property changed event " + property.ProgrammaticName + - ". AutomationID: " + (element.Current.AutomationId ?? "none")); + _instance._logger?.LogDebug("Adding property changed event {PropertyName}. AutomationID: {AutomationId}", + property.ProgrammaticName, + element.Current.AutomationId ?? "none"); var eventHandlerList = new List { @@ -666,22 +671,23 @@ public void AddAutomationPropertyChangedEventHandler(AutomationElement element, var eventHandlerList = (List)events[property]; if (!eventHandlerList.Contains(eventHandler)) { - Log.Debug("Registering event. " + property.ProgrammaticName + - ". AutomationID: " + (element.Current.AutomationId ?? "none")); + _instance._logger?.LogDebug("Registering event. {PropertyName}. AutomationID: {AutomationId}", + property.ProgrammaticName, + element.Current.AutomationId ?? "none"); eventHandlerList.Add(eventHandler); } else { - Log.Debug("Property change already registered. " + - property.ProgrammaticName + ". AutomationID: " + - (element.Current.AutomationId ?? "none")); + _instance._logger?.LogDebug("Property change already registered. {PropertyName}. AutomationID: {AutomationId}", + property.ProgrammaticName, + element.Current.AutomationId ?? "none"); } } } catch (Exception e) { - Log.Exception(e); + _instance._logger?.LogError(e, "Exception in AddAutomationPropertyChangedEventHandler"); } } @@ -690,15 +696,15 @@ public void AddAutomationPropertyChangedEventHandler(AutomationElement element, /// public void RemoveAllEvents() { - Log.Verbose(); + _instance._logger?.LogTrace("RemoveAllEvents called"); try { - Log.Debug("ControlElements count: " + _controlElements.Count); + _instance._logger?.LogDebug("ControlElements count: {Count}", _controlElements.Count); foreach (AutomationElement element in _controlElements.Keys) { var events = (Hashtable)_controlElements[element]; - Log.Debug("events count: " + events.Count); + _instance._logger?.LogDebug("events count: {Count}", events.Count); foreach (var key in events.Keys) { if (key is AutomationEvent) @@ -707,9 +713,9 @@ public void RemoveAllEvents() var eventHandler = (AutomationEventHandler)events[autoEvent]; try { - Log.Debug("Removing automation event " + autoEvent.ProgrammaticName); + _instance._logger?.LogDebug("Removing automation event {EventName}", autoEvent.ProgrammaticName); Automation.RemoveAutomationEventHandler(autoEvent, element, eventHandler); - Log.Debug("Done removing automation event"); + _instance._logger?.LogDebug("Done removing automation event"); } catch { } } @@ -719,9 +725,9 @@ public void RemoveAllEvents() var eventHandler = (AutomationPropertyChangedEventHandler)events[autoProperty]; try { - Log.Debug("Removing automation property " + autoProperty.ProgrammaticName); + _instance._logger?.LogDebug("Removing automation property {PropertyName}", autoProperty.ProgrammaticName); Automation.RemoveAutomationPropertyChangedEventHandler(element, eventHandler); - Log.Debug("Done removing automation property"); + _instance._logger?.LogDebug("Done removing automation property"); } catch { } } @@ -732,7 +738,7 @@ public void RemoveAllEvents() } catch (Exception e) { - Log.Exception("Exception occured! e=" + e.ToString()); + _instance._logger?.LogError(e, "Exception occurred in RemoveAllEvents"); } } @@ -743,28 +749,28 @@ public void RemoveAllEvents() /// the event public void RemoveAutomationEventHandler(AutomationElement element, AutomationEvent autoEvent) { - Log.Verbose(); + _instance._logger?.LogTrace("RemoveAutomationEventHandler called"); try { var events = (Hashtable)_controlElements[element]; if (events != null && events.Contains(autoEvent)) { - Log.Debug("Removing automation event " + autoEvent.ProgrammaticName); + _instance._logger?.LogDebug("Removing automation event {EventName}", autoEvent.ProgrammaticName); var eventHandler = (AutomationEventHandler)events[autoEvent]; Automation.RemoveAutomationEventHandler(autoEvent, element, eventHandler); - Log.Debug("RemoveAutomationEventHandler succeeded!"); + _instance._logger?.LogDebug("RemoveAutomationEventHandler succeeded!"); events.Remove(autoEvent); } else { - Log.Debug("Event already Removed." + - autoEvent.ProgrammaticName + ". AutomationID: " + - (element.Current.AutomationId ?? "none")); + _instance._logger?.LogDebug("Event already Removed. {EventName}. AutomationID: {AutomationId}", + autoEvent.ProgrammaticName, + element.Current.AutomationId ?? "none"); } } catch (Exception e) { - Log.Exception(e); + _instance._logger?.LogError(e, "Exception in RemoveAutomationEventHandler"); } } @@ -778,11 +784,11 @@ public void RemoveAutomationPropertyChangedEventHandler(AutomationElement elemen AutomationProperty property, AutomationPropertyChangedEventHandler eventHandler) { - Log.Verbose(); + _instance._logger?.LogTrace("RemoveAutomationPropertyChangedEventHandler called"); try { - Log.Debug("Removing propertychanged event for automation property " + property.ProgrammaticName); + _instance._logger?.LogDebug("Removing propertychanged event for automation property {PropertyName}", property.ProgrammaticName); var events = (Hashtable)_controlElements[element]; if (events != null && events.Contains(property)) { @@ -790,28 +796,28 @@ public void RemoveAutomationPropertyChangedEventHandler(AutomationElement elemen if (eventHandlerList.Contains(eventHandler)) { eventHandlerList.Remove(eventHandler); - Log.Debug("RemoveAutomationPropertyChangedEventHandler succeeded!"); + _instance._logger?.LogDebug("RemoveAutomationPropertyChangedEventHandler succeeded!"); if (eventHandlerList.Count == 0) { - Log.Debug("Event handler list is empty. No more subscribers. Removing event"); + _instance._logger?.LogDebug("Event handler list is empty. No more subscribers. Removing event"); Automation.RemoveAutomationPropertyChangedEventHandler(element, onPropertyChanged); events.Remove(property); } } else { - Log.Error("Could not remove event. Did not find event handler in the eventhandlers list"); + _instance._logger?.LogError("Could not remove event. Did not find event handler in the eventhandlers list"); } } else { - Log.Error("Could not remove event. Did not find property in the events list"); + _instance._logger?.LogError("Could not remove event. Did not find property in the events list"); } } catch (Exception e) { - Log.Exception("Exception occured! e=" + e.ToString()); + _instance._logger?.LogError(e, "Exception occurred in RemoveAutomationPropertyChangedEventHandler"); } } @@ -823,7 +829,7 @@ public void RemoveAutomationPropertyChangedEventHandler(AutomationElement elemen /// event args private void onPropertyChanged(object sender, AutomationPropertyChangedEventArgs e) { - Log.Debug(e.Property.ProgrammaticName); + _instance._logger?.LogDebug("Property changed: {PropertyName}", e.Property.ProgrammaticName); var element = sender as AutomationElement; Hashtable events = (Hashtable)_controlElements[element]; @@ -831,10 +837,10 @@ private void onPropertyChanged(object sender, AutomationPropertyChangedEventArgs if (events != null && events.Contains(e.Property)) { var eventHandlerList = (List)events[e.Property]; - Log.Debug("eventHandlerList.Count = " + eventHandlerList.Count); + _instance._logger?.LogDebug("eventHandlerList.Count = {Count}", eventHandlerList.Count); foreach (var p in eventHandlerList) { - Log.Debug("Calling property changed for " + e.Property.ProgrammaticName); + _instance._logger?.LogDebug("Calling property changed for {PropertyName}", e.Property.ProgrammaticName); p(sender, e); } } @@ -849,7 +855,7 @@ private void onWindowClose(object sender, AutomationEventArgs e) { if (EvtOnWindowClosed != null) { - Log.Debug("Triggering event closed"); + _instance._logger?.LogDebug("Triggering event closed"); EvtOnWindowClosed(_hwnd); } } diff --git a/src/Libraries/ACATCore/Utility/CachedLog.cs b/src/Libraries/ACATCore/Utility/CachedLog.cs index c62e7c99..dc66531c 100644 --- a/src/Libraries/ACATCore/Utility/CachedLog.cs +++ b/src/Libraries/ACATCore/Utility/CachedLog.cs @@ -5,6 +5,7 @@ // //////////////////////////////////////////////////////////////////////////// +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.IO; @@ -17,6 +18,8 @@ namespace ACAT.Core.Utility /// public class CachedLog { + private readonly ILogger _logger; + /// /// Full path to the log file /// @@ -29,8 +32,9 @@ public class CachedLog /// private readonly string LogFileName; - public CachedLog(string baseFileName) + public CachedLog(string baseFileName, ILogger logger) { + _logger = logger; string logFileFolder = FileUtils.GetLogsDir(); try @@ -80,7 +84,7 @@ public bool Save() } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex, ex.Message); return false; } finally diff --git a/src/Libraries/ACATCore/Utility/DirectoryWalker.cs b/src/Libraries/ACATCore/Utility/DirectoryWalker.cs index b34a68d8..dff1d2a4 100644 --- a/src/Libraries/ACATCore/Utility/DirectoryWalker.cs +++ b/src/Libraries/ACATCore/Utility/DirectoryWalker.cs @@ -5,6 +5,7 @@ // //////////////////////////////////////////////////////////////////////////// +using Microsoft.Extensions.Logging; using System; using System.IO; using System.Linq; @@ -30,6 +31,8 @@ namespace ACAT.Core.Utility /// files to find public class DirectoryWalker { + private readonly ILogger _logger; + ///// ///// Invoked when a directory is found ///// @@ -59,8 +62,9 @@ public DirectoryWalker(String rootDir) : this(rootDir, string.Empty) { } - public DirectoryWalker(String rootDir, String fileWildCard) + public DirectoryWalker(String rootDir, String fileWildCard, ILogger logger = null) { + _logger = logger ?? LoggerFactory.Create(builder => builder.AddConsole()).CreateLogger(); _rootDir = rootDir; _wildCard = fileWildCard; } @@ -83,21 +87,21 @@ public void Walk(OnFileFoundDelegate fileFoundDelegate) foreach (var file in dllFiles) { - Log.Verbose("Found file: " + file); + _logger.LogTrace("Found file: " + file); fileFoundDelegate?.Invoke(file); } } catch (UnauthorizedAccessException ex) { - Log.Exception("Access denied: " + ex.Message); + _logger.LogError(ex, "Access denied: " + ex.Message); } catch (IOException ex) { - Log.Verbose("IO error: " + ex.Message); + _logger.LogTrace("IO error: " + ex.Message); } catch (Exception ex) { - Log.Exception("Error: " + ex.Message); + _logger.LogError(ex, "Error: " + ex.Message); } } diff --git a/src/Libraries/ACATCore/Utility/EnumWindows.cs b/src/Libraries/ACATCore/Utility/EnumWindows.cs index aacd8f89..8a288232 100644 --- a/src/Libraries/ACATCore/Utility/EnumWindows.cs +++ b/src/Libraries/ACATCore/Utility/EnumWindows.cs @@ -7,6 +7,7 @@ using ACAT.Core.PanelManagement; using ACAT.Core.PanelManagement.Interfaces; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Diagnostics; @@ -20,6 +21,8 @@ namespace ACAT.Core.Utility /// public static class EnumWindows { + private static ILogger _logger; + /// /// Ignore windows with these class names during enumeration /// @@ -52,6 +55,11 @@ public static class EnumWindows /// private static List windowList; + static EnumWindows() + { + _logger = LoggerFactory.Create(builder => builder.AddConsole()).CreateLogger(typeof(EnumWindows)); + } + /// /// Synchronously enumerates windows and returns a window list /// @@ -76,7 +84,7 @@ public static List Enumerate(bool excludeThisProcess = true) public static void RestoreFocusToTopWindow(int ignoreHandle = 0) { var winList = Enumerate(false); - Log.Debug("winList Count: " + winList.Count); + _logger.LogDebug("winList Count: " + winList.Count); bool found = false; var handle = IntPtr.Zero; IntPtr ignoreWindowHandle = new(ignoreHandle); @@ -94,7 +102,7 @@ public static void RestoreFocusToTopWindow(int ignoreHandle = 0) var control = Form.FromHandle(handle); if (control is IDialogPanel) { - Log.Debug("Setting focus to ACAT dialog." + windowInfo.Title); + _logger.LogDebug("Setting focus to ACAT dialog." + windowInfo.Title); found = true; break; } @@ -107,7 +115,7 @@ public static void RestoreFocusToTopWindow(int ignoreHandle = 0) control is not MenuPanelBase && control is not IScannerPanel) { - Log.Debug("Found top window " + windowInfo.Title); + _logger.LogDebug("Found top window " + windowInfo.Title); found = true; break; } @@ -131,7 +139,7 @@ control is not MenuPanelBase && public static void RestoreFocusToTopWindowOnDesktop() { var winList = Enumerate(); - Log.Debug("winList Count: " + winList.Count); + _logger.LogDebug("winList Count: " + winList.Count); bool found = false; var handle = IntPtr.Zero; @@ -146,7 +154,7 @@ public static void RestoreFocusToTopWindowOnDesktop() if (!windowInfo.Title.Contains("DebugView") && !Windows.IsMinimized(handle)) { - Log.Debug("Found top window " + windowInfo.Title); + _logger.LogDebug("Found top window " + windowInfo.Title); found = true; break; } @@ -249,7 +257,7 @@ private static bool enumWindowsCallback(IntPtr winHandle, int lParam) if (!string.IsNullOrEmpty(windowTitle)) { - Log.Debug("hWnd=" + winHandle + " windowTitle=" + windowTitle); + _logger.LogDebug("hWnd=" + winHandle + " windowTitle=" + windowTitle); var info = new WindowInfo(winHandle, windowTitle); windowList.Add(info); diff --git a/src/Libraries/ACATCore/Utility/FileUtils.cs b/src/Libraries/ACATCore/Utility/FileUtils.cs index 2c2d0742..e4f4ae84 100644 --- a/src/Libraries/ACATCore/Utility/FileUtils.cs +++ b/src/Libraries/ACATCore/Utility/FileUtils.cs @@ -6,6 +6,7 @@ //////////////////////////////////////////////////////////////////////////// using ACAT.Core.UserManagement; +using Microsoft.Extensions.Logging; using System; using System.Diagnostics; using System.IO; @@ -25,6 +26,8 @@ namespace ACAT.Core.Utility /// public class FileUtils { + private static ILogger _logger; + /// /// Folder under which ACAT extensions are stored /// @@ -125,16 +128,17 @@ public static Assembly AssemblyResolve(Assembly executingAssembly, ResolveEventA return null; } - Log.Debug($"RequestingAssembly: [{args.RequestingAssembly.Location}], Name:[{args.Name}]"); + _logger?.LogDebug("RequestingAssembly: [{Location}], Name:[{Name}]", + args.RequestingAssembly.Location, args.Name); var requestingAssemblyDir = Path.GetDirectoryName(args.RequestingAssembly.Location); - Log.Debug($"RequestingAssembly directory is {requestingAssemblyDir}"); + _logger?.LogDebug("RequestingAssembly directory is {Directory}", requestingAssemblyDir); var assemblyName = new AssemblyName(args.Name).Name; var assemblyPath = $"{requestingAssemblyDir}\\{assemblyName}.dll"; - Log.Debug($"Resolved assembly location: {assemblyPath}"); + _logger?.LogDebug("Resolved assembly location: {Path}", assemblyPath); Assembly retVal = null; try @@ -149,13 +153,13 @@ public static Assembly AssemblyResolve(Assembly executingAssembly, ResolveEventA return null; } - Log.Exception(fnf); + _logger?.LogError(fnf, "Exception loading assembly"); throw; } catch (Exception ex) { - Log.Exception($"Could not load assembly. Exception: {ex}"); + _logger?.LogError(ex, "Could not load assembly"); } return retVal; } @@ -240,7 +244,7 @@ public static bool Copy(String source, String target) } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger?.LogError(ex, "Exception in Copy"); retVal = false; } @@ -317,12 +321,14 @@ public static String GetPanelConfigDir() /// input assembly public static void GetDependentAssemblyVersion(Assembly assembly) { - Log.Debug("Assembly name: " + assembly.GetName() + " Version: " + assembly.GetName().Version.ToString()); + _logger?.LogDebug("Assembly name: {Name} Version: {Version}", + assembly.GetName(), assembly.GetName().Version); AssemblyName[] referenced = assembly.GetReferencedAssemblies(); foreach (AssemblyName refAssembly in referenced) { - Log.Debug("Assembly name: " + refAssembly.Name + " Version: " + refAssembly.Version.ToString()); + _logger?.LogDebug("Assembly name: {Name} Version: {Version}", + refAssembly.Name, refAssembly.Version); } } @@ -635,7 +641,8 @@ public static void LogAssemblyInfo(Assembly executingAssembly = null) var appVersion = "Version " + assembly.GetName().Version; - Log.Info("***** " + appName + ". " + appVersion + ". " + DateTime.Now.ToString() + " *****"); + _logger?.LogInformation("***** {AppName}. {AppVersion}. {DateTime} *****", + appName, appVersion, DateTime.Now); } /// @@ -648,7 +655,7 @@ public static bool Run(String executable, ProcessWindowStyle style = ProcessWind { bool retVal = true; - Log.Debug("Run " + executable); + _logger?.LogDebug("Run {Executable}", executable); var startInfo = new ProcessStartInfo { @@ -663,11 +670,11 @@ public static bool Run(String executable, ProcessWindowStyle style = ProcessWind } catch (Exception e) { - Log.Error("Error executing " + executable + ". Exception: " + e); + _logger?.LogError(e, "Error executing {Executable}", executable); return false; } - Log.Debug("Returning " + retVal); + _logger?.LogDebug("Returning {Result}", retVal); return retVal; } diff --git a/src/Libraries/ACATCore/Utility/GlobalPreferences.cs b/src/Libraries/ACATCore/Utility/GlobalPreferences.cs index 27eadd52..f4091c89 100644 --- a/src/Libraries/ACATCore/Utility/GlobalPreferences.cs +++ b/src/Libraries/ACATCore/Utility/GlobalPreferences.cs @@ -6,6 +6,7 @@ //////////////////////////////////////////////////////////////////////////// using System; +using Microsoft.Extensions.Logging; namespace ACAT.Core.Utility { @@ -17,6 +18,7 @@ namespace ACAT.Core.Utility [Serializable] public class GlobalPreferences { + private static ILogger _logger; public static String DefaultPreferencesFilePath = String.Empty; public static String LogFileName = String.Empty; @@ -53,7 +55,7 @@ public static GlobalPreferences Load(String prefFile, bool loadDefaultsOnFail = if (retVal == null) { - Log.Error($"Could not load global preferences from {prefFile}. Creating a new one."); + _logger?.LogError("Could not load global preferences from {PrefFile}. Creating a new one.", prefFile); if (loadDefaultsOnFail) { retVal = new GlobalPreferences(); @@ -66,7 +68,7 @@ public static GlobalPreferences Load(String prefFile, bool loadDefaultsOnFail = if (!XmlUtils.XmlFileSave(retVal, prefFile)) { - Log.Error("Unable to save global preferences!"); + _logger?.LogError("Unable to save global preferences!"); retVal = null; } @@ -107,7 +109,7 @@ public static bool Save(GlobalPreferences prefs, String preferencesFile) if (retVal == false) { - Log.Error("Error saving preferences! file=" + preferencesFile); + _logger?.LogError("Error saving preferences! file={PreferencesFile}", preferencesFile); } return retVal; diff --git a/src/Libraries/ACATCore/Utility/HtmlUtils.cs b/src/Libraries/ACATCore/Utility/HtmlUtils.cs index 97deb9b0..8f9119a5 100644 --- a/src/Libraries/ACATCore/Utility/HtmlUtils.cs +++ b/src/Libraries/ACATCore/Utility/HtmlUtils.cs @@ -12,11 +12,13 @@ using System.IO; using System.Text; using System.Web; +using Microsoft.Extensions.Logging; namespace ACAT.Core.Utility { public class HtmlUtils { + private static ILogger _logger; /// /// Paths of the browsers exe /// @@ -166,7 +168,7 @@ public static void LoadHtml(string path, string[] htmlData) } catch (Exception ex) { - Log.Exception("Error loading HTML script: " + ex.Message); + _logger?.LogError(ex, "Error loading HTML script: {Message}", ex.Message); } } diff --git a/src/Libraries/ACATCore/Utility/ImageUtils.cs b/src/Libraries/ACATCore/Utility/ImageUtils.cs index 78b2a46c..781f4e4e 100644 --- a/src/Libraries/ACATCore/Utility/ImageUtils.cs +++ b/src/Libraries/ACATCore/Utility/ImageUtils.cs @@ -10,6 +10,7 @@ using System.Drawing.Imaging; using System.IO; using System.Reflection; +using Microsoft.Extensions.Logging; namespace ACAT.Core.Utility { @@ -18,6 +19,7 @@ namespace ACAT.Core.Utility /// public class ImageUtils { + private static ILogger _logger; /// /// Converts the specified icon into a bitmap /// @@ -84,7 +86,7 @@ public static Bitmap ImageCrop(String imageFile, Rectangle cropRectangle) } catch (Exception e) { - Log.Error("ImageCrop: Could not crop image " + imageFile + ". Exception: " + e.ToString()); + _logger?.LogError(e, "ImageCrop: Could not crop image {ImageFile}", imageFile); } return retVal; @@ -167,16 +169,16 @@ public static Image LoadImage(String bitmapFile) return null; } - Log.Debug("imagePath: " + bitmapFile); + _logger?.LogDebug("imagePath: {BitmapFile}", bitmapFile); if (File.Exists(bitmapFile)) { - Log.Debug("File exists. Loading image"); + _logger?.LogDebug("File exists. Loading image"); retVal = Image.FromFile(bitmapFile); } else { - Log.Error("Could not find bitmap file " + bitmapFile); + _logger?.LogError("Could not find bitmap file {BitmapFile}", bitmapFile); } return retVal; diff --git a/src/Libraries/ACATCore/Utility/KeyStateTracker.cs b/src/Libraries/ACATCore/Utility/KeyStateTracker.cs index 02c75c12..0227d58c 100644 --- a/src/Libraries/ACATCore/Utility/KeyStateTracker.cs +++ b/src/Libraries/ACATCore/Utility/KeyStateTracker.cs @@ -9,6 +9,7 @@ using System.Collections; using System.Collections.Generic; using System.Windows.Forms; +using Microsoft.Extensions.Logging; namespace ACAT.Core.Utility { @@ -25,6 +26,7 @@ namespace ACAT.Core.Utility /// public class KeyStateTracker { + private static ILogger _logger; private const byte VK_CAPITAL = 0x14; private const byte VK_NUMLOCK = 0x90; diff --git a/src/Libraries/ACATCore/Utility/NamedPipe/PipeServer.cs b/src/Libraries/ACATCore/Utility/NamedPipe/PipeServer.cs index 2a3999ce..6c61ddc9 100644 --- a/src/Libraries/ACATCore/Utility/NamedPipe/PipeServer.cs +++ b/src/Libraries/ACATCore/Utility/NamedPipe/PipeServer.cs @@ -12,11 +12,13 @@ using System.Security.Principal; using System.Text; using System.Threading; +using Microsoft.Extensions.Logging; namespace ACAT.Core.Utility.NamedPipe { public sealed class PipeServer : IDisposable { + private readonly ILogger _logger; private CancellationToken cancellationToken; private readonly CancellationTokenSource cancellationTokenSource; private bool disposed; @@ -34,8 +36,10 @@ public sealed class PipeServer : IDisposable /// Allow the pipe to be visible by all the users /// Current user and Administrator user /// - public PipeServer(string pipeName, PipeDirection pipeDirection, bool allowAllReadWrite = false) + /// Logger for dependency injection + public PipeServer(string pipeName, PipeDirection pipeDirection, bool allowAllReadWrite = false, ILogger logger = null) { + _logger = logger; if (!allowAllReadWrite) { ServerStream = new NamedPipeServerStream( @@ -203,7 +207,7 @@ private void ReadCallback(IAsyncResult ar) } catch (Exception ex) { - Log.Exception("Error in ReadCallback: " + ex.Message); + _logger?.LogError(ex, "Error in ReadCallback: {Message}", ex.Message); // Check to make sure the Pipe is still around try @@ -214,7 +218,7 @@ private void ReadCallback(IAsyncResult ar) catch (Exception e) { // Something happened to the pipe. Just send an Exit message to the client - Log.Debug("Pipe is not connected. Sending exit message to client. " + e.Message); + _logger?.LogDebug("Pipe is not connected. Sending exit message to client. {Message}", e.Message); OnMessageReceived(new MessageReceivedEventArgs("quit")); } } diff --git a/src/Libraries/ACATCore/Utility/ResourceUtils.cs b/src/Libraries/ACATCore/Utility/ResourceUtils.cs index db8269f7..0bf85dd5 100644 --- a/src/Libraries/ACATCore/Utility/ResourceUtils.cs +++ b/src/Libraries/ACATCore/Utility/ResourceUtils.cs @@ -6,6 +6,7 @@ //////////////////////////////////////////////////////////////////////////// using ACAT.Core.UserManagement; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Globalization; @@ -18,6 +19,7 @@ namespace ACAT.Core.Utility /// public class ResourceUtils { + private static ILogger _logger; /// /// Name of the language resources dll /// @@ -78,7 +80,7 @@ public static IEnumerable EnumerateInstalledLanguages(bool excludeC } catch (Exception ex) { - Log.Exception(ex); + _logger?.LogError(ex, "Exception in EnumerateInstalledLanguages"); } } @@ -114,7 +116,7 @@ public static IEnumerable GetInstalledLangugageDirectories() } catch (Exception ex) { - Log.Verbose("Language detect: Skipping folder " + dir + ". " + ex.Message); + _logger?.LogDebug("Language detect: Skipping folder {Dir}. {Message}", dir, ex.Message); } } @@ -151,7 +153,7 @@ public static void InstallLanguageForUser(String baseDir = null) var targetDir = Path.Combine(UserManager.CurrentUserDir, language); - Log.Debug("Copy directory " + srcDir + "=> " + targetDir); + _logger?.LogDebug("Copy directory {SrcDir} => {TargetDir}", srcDir, targetDir); FileUtils.CopyDir(srcDir, targetDir); } @@ -228,7 +230,7 @@ public static void SetCulture(String language = "en") //TODO: Code Smell if (!Directory.Exists(resourcesDir) || !File.Exists(resourceDll)) { - Log.Warn(language + " resources not found. Will use English as the default"); + _logger?.LogWarning("{Language} resources not found. Will use English as the default", language); culture = CultureInfo.CreateSpecificCulture("en"); } @@ -237,7 +239,7 @@ public static void SetCulture(String language = "en") } catch (Exception ex) { - Log.Error("Error setting culture to " + language + ", " + ex + ", will use English as the default"); + _logger?.LogError(ex, "Error setting culture to {Language}, will use English as the default", language); CultureInfo.DefaultThreadCurrentCulture = CultureInfo.CreateSpecificCulture("en"); CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.CreateSpecificCulture("en"); } diff --git a/src/Libraries/ACATCore/Utility/SoundManager.cs b/src/Libraries/ACATCore/Utility/SoundManager.cs index bcd05790..50194f17 100644 --- a/src/Libraries/ACATCore/Utility/SoundManager.cs +++ b/src/Libraries/ACATCore/Utility/SoundManager.cs @@ -10,14 +10,16 @@ using System; using System.Collections.Generic; using System.Media; +using Microsoft.Extensions.Logging; namespace ACAT.Core.Utility { /// - /// Class that use the C:\Windows\Media Sounds + /// Class that use the C:\\Windows\\Media Sounds /// public class SoundManager { + private static ILogger _logger; /// /// Are the sounds initialized /// @@ -101,7 +103,7 @@ public static void playSound(SoundType soundType, string customPath = null) } catch (Exception ex) { - Log.Exception("Error playing Sound: " + ex); + _logger?.LogError(ex, "Error playing Sound"); } } @@ -120,7 +122,7 @@ private static void SetSoundFile(SoundPlayer player, string soundFilePath) player.Play(); } else - Log.Debug("_soundPlayer object was null"); + _logger?.LogDebug("_soundPlayer object was null"); } /// @@ -138,7 +140,7 @@ private static void SetSoundFileSync(SoundPlayer player, string soundFilePath) player.PlaySync(); } else - Log.Debug("_soundPlayer object was null"); + _logger?.LogDebug("_soundPlayer object was null"); } private static void SetSounds() diff --git a/src/Libraries/ACATCore/Utility/TextUtils.cs b/src/Libraries/ACATCore/Utility/TextUtils.cs index 86dcb8fb..c5a9a018 100644 --- a/src/Libraries/ACATCore/Utility/TextUtils.cs +++ b/src/Libraries/ACATCore/Utility/TextUtils.cs @@ -8,6 +8,7 @@ using System; using System.Text; using System.Windows.Forms; +using Microsoft.Extensions.Logging; namespace ACAT.Core.Utility { @@ -17,6 +18,7 @@ namespace ACAT.Core.Utility /// public class TextUtils { + private static ILogger _logger; /// /// Converts a byte array into a hex string /// @@ -40,7 +42,7 @@ public static string ByteArrayToHexString(byte[] byteArray) /// public static String Capitalize(String word) { - Log.Debug(word); + _logger?.LogDebug("{Word}", word); if (String.IsNullOrEmpty(word)) { return word; @@ -59,7 +61,7 @@ public static String Capitalize(String word) } char c = word[index]; - Log.Debug("index: " + index + "c: " + c.ToString()); + _logger?.LogDebug("index: {Index}, c: {Char}", index, c); if (!Char.IsLetter(c) || Char.IsUpper(c)) { @@ -69,7 +71,7 @@ public static String Capitalize(String word) word = word.Remove(index, 1); c = Char.ToUpper(c); word = word.Insert(index, c.ToString()); - Log.Debug("returning " + word); + _logger?.LogDebug("returning {Word}", word); return word; } @@ -95,7 +97,7 @@ public static bool CheckInsertOrReplaceWord(String inputString, int caretPos, ou if (String.IsNullOrEmpty(inputString)) { - Log.Debug("NULL string. return true " + insertOrReplaceOffset); + _logger?.LogDebug("NULL string. return true {Offset}", insertOrReplaceOffset); return true; } diff --git a/src/Libraries/ACATCore/Utility/TypeLoader/TypeLoader.cs b/src/Libraries/ACATCore/Utility/TypeLoader/TypeLoader.cs index c7697fed..3ef5533d 100644 --- a/src/Libraries/ACATCore/Utility/TypeLoader/TypeLoader.cs +++ b/src/Libraries/ACATCore/Utility/TypeLoader/TypeLoader.cs @@ -3,12 +3,14 @@ using System.IO; using System.Linq; using System.Reflection; +using Microsoft.Extensions.Logging; namespace ACAT.Core.Utility.TypeLoader { public class TypeLoader : ITypeLoader where TInterface : class, IPluginExtension { + private readonly ILogger> _logger; private readonly Dictionary _typeCache = new(); public IReadOnlyDictionary LoadedTypes => _typeCache; @@ -157,7 +159,7 @@ private void LoadTypesFromAssembly(Assembly assembly, bool firstordefault = true catch (Exception ex) { // Log or skip if instantiation fails - Log.Exception($"Failed to create instance of {assembly.FullName}: {ex.Message}"); + _logger?.LogError(ex, "Failed to create instance of {AssemblyName}", assembly.FullName); } } } diff --git a/src/Libraries/ACATCore/Utility/Windows.cs b/src/Libraries/ACATCore/Utility/Windows.cs index e4f8d30b..5140a476 100644 --- a/src/Libraries/ACATCore/Utility/Windows.cs +++ b/src/Libraries/ACATCore/Utility/Windows.cs @@ -6,6 +6,7 @@ //////////////////////////////////////////////////////////////////////////// using ACAT.Core.Utility.Mouse; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Diagnostics; @@ -26,6 +27,8 @@ namespace ACAT.Core.Utility /// public class Windows { + private static ILogger _logger; + private const int GCL_HICON = -14; private const int GCL_HICONSM = -34; private const int GWL_STYLE = (-16); @@ -179,7 +182,7 @@ public static int WidestScannerWidth { //if (value > _widestScannerWidth) { - Log.Debug("Widest scanner width: " + value); + _logger?.LogDebug("Widest scanner width: {Width}", value); _widestScannerWidth = value; } } @@ -331,19 +334,19 @@ public static void DockAppWindowWithScanner(WindowPosition scannerPosition, IntP break; } - Log.Debug("screenOffset=" + screenOffset + " moveX=" + moveX.ToString() + " moveY=" + moveY.ToString()); + _logger?.LogDebug("screenOffset={ScreenOffset} moveX={MoveX} moveY={MoveY}", screenOffset, moveX, moveY); User32Interop.SetWindowPos(handle.ToInt32(), 0, moveX, moveY, (r.Width - scannerForm.Width), r.Height, 0x0040 | 0x0004); } } else { - Log.Debug("fgWnd is zero"); + _logger?.LogDebug("fgWnd is zero"); } } public static void DockWindow(IntPtr fgWindow, Form panel, WindowPosition scannerPosition) { - Log.Debug("fgWindow is null is : " + (fgWindow == IntPtr.Zero)); + _logger?.LogDebug("fgWindow is null is: {IsNull}", fgWindow == IntPtr.Zero); if (fgWindow == IntPtr.Zero) { @@ -353,31 +356,31 @@ public static void DockWindow(IntPtr fgWindow, Form panel, WindowPosition scanne Process process = WindowActivityMonitor.GetProcessForWindow(fgWindow); if (process.ProcessName == Process.GetCurrentProcess().ProcessName) { - Log.Debug("#$#$#$#$ This is an ACAT Window!!!!!"); + _logger?.LogDebug("#$#$#$#$ This is an ACAT Window!!!!!"); return; } if (panel != null) { - Log.Debug("#$#$#$#$ Calling IsDialog"); + _logger?.LogDebug("#$#$#$#$ Calling IsDialog"); if (!IsDialog(fgWindow)) { - Log.Debug("#$#$#$#$ Returned from IsDialog"); + _logger?.LogDebug("#$#$#$#$ Returned from IsDialog"); - Log.Debug("#$#$#$#$ Calling DockAppWindowWithScanner for form " + (panel as Form).Name); + _logger?.LogDebug("#$#$#$#$ Calling DockAppWindowWithScanner for form {FormName}", (panel as Form).Name); DockAppWindowWithScanner(scannerPosition, fgWindow, panel); } else { - Log.Debug("#$#$#$#$ Window is a dialog. will not dock"); + _logger?.LogDebug("#$#$#$#$ Window is a dialog. will not dock"); } } } public static void DockWindowWithLargestScanner(IntPtr fgWindow, Form panel, WindowPosition scannerPosition) { - Log.Debug("#$#$#$#$ fgWindow is null is : " + (fgWindow == IntPtr.Zero)); + _logger?.LogDebug("#$#$#$#$ fgWindow is null is: {IsNull}", fgWindow == IntPtr.Zero); if (fgWindow == IntPtr.Zero) { @@ -393,7 +396,7 @@ public static void DockWindowWithLargestScanner(IntPtr fgWindow, Form panel, Win Process process = WindowActivityMonitor.GetProcessForWindow(fgWindow); if (process.ProcessName == Process.GetCurrentProcess().ProcessName) { - Log.Debug("#$#$#$#$ This is an ACAT Window!!!!!"); + _logger?.LogDebug("#$#$#$#$ This is an ACAT Window!!!!!"); return; } @@ -430,7 +433,7 @@ public static void DockWindowWithLargestScanner(IntPtr fgWindow, Form panel, Win } else { - Log.Debug("Window is a dialog. will not dock"); + _logger?.LogDebug("Window is a dialog. will not dock"); } } @@ -555,7 +558,7 @@ public static Control FindControlAtPoint(Control container, Point pos) /// the icon, null if it can't find one public static Icon GetAppIcon(IntPtr winHandle) { - Log.Debug("hWnd=" + winHandle); + _logger?.LogDebug("GetAppIcon: hWnd={HWnd}", winHandle); IntPtr hIcon = User32Interop.SendMessage(winHandle, WM_GETICON, ICON_BIG, 0); @@ -870,7 +873,7 @@ public static bool GetVisible(Control control) } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger?.LogError(ex, "Exception in GetVisible"); return false; } } @@ -1014,7 +1017,7 @@ public static bool IsDialog(IntPtr handle) retVal = (!windowPattern.Current.CanMinimize && !windowPattern.Current.CanMaximize) || windowPattern.Current.IsModal; } - Log.Debug("returning " + retVal); + _logger?.LogDebug("IsDialog returning {Result}", retVal); return retVal; } @@ -1461,7 +1464,7 @@ public static void SetTrackBarValue(TrackBar trackBar, int positionValue) } else { - Log.Debug("Trying to set trackbar outside legal bounds!"); + _logger?.LogDebug("Trying to set trackbar outside legal bounds!"); } } } @@ -1495,7 +1498,7 @@ public static void SetWindowPosition(Form form, WindowPosition position) { form.StartPosition = FormStartPosition.Manual; - Log.Debug("Before setposition " + position); + _logger?.LogDebug("Before setposition {Position}", position); switch (position) { @@ -1530,7 +1533,7 @@ public static void SetWindowPosition(Form form, WindowPosition position) (Screen.PrimaryScreen.WorkingArea.Height - form.Height) / 2); break; } - Log.Debug("After setposition " + position); + _logger?.LogDebug("After setposition {Position}", position); } catch { @@ -1585,11 +1588,11 @@ public static void SetWindowPosition(Form form, IntPtr insertAfter, WindowPositi /// Where to set the position public static void SetWindowPositionAndNotify(Form form, WindowPosition position) { - Log.Debug("Setting position to " + position); + _logger?.LogDebug("Setting position to {Position}", position); SetWindowPosition(form, position); if (EvtWindowPositionChanged != null) { - Log.Debug("Calling evtpositionchanged with " + position); + _logger?.LogDebug("Calling evtpositionchanged with {Position}", position); EvtWindowPositionChanged(form, position); } @@ -1616,7 +1619,7 @@ public static void SetWindowPositionAndNotify(Form form, IntPtr insertAfter, Win /// percentage of display monitor width public static void SetWindowSizePercent(IntPtr handle, WindowPosition scannerPosition, int percent) { - Log.Debug("Entering...scannerPosition=" + scannerPosition.ToString() + " percent=" + percent.ToString()); + _logger?.LogDebug("Entering...scannerPosition={Position} percent={Percent}", scannerPosition, percent); int moveX = 0; int moveY = 0; // not really using Y-axis yet but something to keep in mind for the future @@ -1636,7 +1639,7 @@ public static void SetWindowSizePercent(IntPtr handle, WindowPosition scannerPos if (r.Width > 0 && r.Height > 0) { - Log.Debug("Resize window to " + (r.Width * percent) / 100 + ", " + r.Height); + _logger?.LogDebug("Resize window to {Width}, {Height}", (r.Width * percent) / 100, r.Height); switch (scannerPosition) { @@ -1661,15 +1664,15 @@ public static void SetWindowSizePercent(IntPtr handle, WindowPosition scannerPos break; } - Log.Debug("screenOffset=" + screenOffset + " moveX=" + moveX.ToString() + " moveY=" + - moveY.ToString()); + _logger?.LogDebug("screenOffset={ScreenOffset} moveX={MoveX} moveY={MoveY}", + screenOffset, moveX, moveY); User32Interop.SetWindowPos(handle.ToInt32(), 0, moveX, moveY, (r.Width * percent) / 100, r.Height, 0x0040 | 0x0004); } } else { - Log.Debug("fgWnd is zero"); + _logger?.LogDebug(\"fgWnd is zero in SetWindowSizePercent\"); } } @@ -1712,7 +1715,7 @@ public static void ShowDialog(Form parent, Form child) child.ShowDialog(parent); if (child.Owner == null) { - Log.Debug("child.parent is null"); + _logger?.LogDebug("child.parent is null"); } } } @@ -1838,7 +1841,7 @@ public static void ToggleForegroundWindowMaximizeDock(Form scanner, WindowPositi Process process = WindowActivityMonitor.GetProcessForWindow(fgWindow); if (process.ProcessName == Process.GetCurrentProcess().ProcessName) { - Log.Debug("This is an ACAT WIndow!"); + _logger?.LogDebug("This is an ACAT Window!"); return; } diff --git a/src/Libraries/ACATCore/Utility/XmlUtils.cs b/src/Libraries/ACATCore/Utility/XmlUtils.cs index 1016f02a..8a8c96ea 100644 --- a/src/Libraries/ACATCore/Utility/XmlUtils.cs +++ b/src/Libraries/ACATCore/Utility/XmlUtils.cs @@ -10,6 +10,7 @@ using System.Text; using System.Xml; using System.Xml.Serialization; +using Microsoft.Extensions.Logging; namespace ACAT.Core.Utility { @@ -19,6 +20,7 @@ namespace ACAT.Core.Utility /// public class XmlUtils { + private static ILogger _logger; private static readonly object _lock = new(); /// @@ -151,7 +153,7 @@ public static bool XmlDeserializeFromString(string objectData, out T obj) } catch (Exception e) { - Log.Exception(e); + _logger?.LogError(e, "XmlDeserializeFromString exception"); retVal = false; obj = default; } @@ -188,7 +190,7 @@ public static T XmlFileLoad(string filename) catch (Exception e) { retVal = default; - Log.Info("Error. FileName: " + filename + ". Error: " + e.ToString()); + _logger?.LogInformation(e, "Error loading file {FileName}", filename); } return retVal; @@ -232,7 +234,7 @@ public static bool XmlFileSave(T o, string filename) catch (Exception e) { retVal = false; - Log.Error("XmlFileSave error. FileName: " + filename + ". Error: " + e.ToString()); + _logger?.LogError(e, "XmlFileSave error. FileName: {FileName}", filename); } } diff --git a/src/Libraries/ACATCore/WidgetManagement/Layout/LayoutAttribute.cs b/src/Libraries/ACATCore/WidgetManagement/Layout/LayoutAttribute.cs index 0780626e..c3257c4b 100644 --- a/src/Libraries/ACATCore/WidgetManagement/Layout/LayoutAttribute.cs +++ b/src/Libraries/ACATCore/WidgetManagement/Layout/LayoutAttribute.cs @@ -7,6 +7,7 @@ using ACAT.Core.ThemeManagement; using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Collections; using System.Collections.Generic; @@ -24,6 +25,8 @@ namespace ACAT.Core.WidgetManagement.Layout /// public class LayoutAttribute { + private readonly ILogger _logger; + /// /// List of widgets that have the "contextual=true" attribute /// enabled. For these widgets, the enable/disable state will @@ -50,8 +53,10 @@ public class LayoutAttribute /// /// Initializes an instance of the Layout class /// - public LayoutAttribute() + /// Logger instance + public LayoutAttribute(ILogger logger = null) { + _logger = logger; _colorSchemeName = string.Empty; _disabledButtonColorSchemeName = string.Empty; Colors = ColorSchemes.DefaultColorScheme; @@ -113,17 +118,17 @@ public Widget CreateWidget(Type classType, string widgetName) Widget widget = null; try { - Log.Debug("creating widget with name " + widgetName); + _logger?.LogDebug("creating widget with name {WidgetName}", widgetName); widget = (Widget)Activator.CreateInstance(classType, widgetName); - Log.IsNull("Widget created ", widget); + _logger?.LogDebug("Widget created: {IsNull}", widget != null ? "Not Null" : "Null"); widget?.SetLayout(this); } catch (Exception ex) { - Log.Exception(ex); + _logger?.LogError(ex, ex.Message); } return widget; @@ -141,17 +146,17 @@ public Widget CreateWidget(Type classType, Control uiControl) Widget widget = null; try { - Log.Debug("creating widget " + classType); + _logger?.LogDebug("creating widget {ClassType}", classType); widget = (Widget)Activator.CreateInstance(classType, uiControl); - Log.IsNull("Widget created ", widget); + _logger?.LogDebug("Widget created: {IsNull}", widget != null ? "Not Null" : "Null"); widget?.SetLayout(layout: this); } catch (Exception ex) { - Log.Exception(ex); + _logger?.LogError(ex, ex.Message); } return widget; @@ -172,7 +177,7 @@ public bool Load(string configFile, Widget rootWidget) { bool retVal = true; - Log.Debug("configFile: " + configFile + ", rootWidget.name is " + rootWidget.Name); + _logger?.LogDebug("configFile: {ConfigFile}, rootWidget.name is {RootWidgetName}", configFile, rootWidget.Name); ConfigFile = configFile; @@ -200,12 +205,12 @@ public bool Load(string configFile, Widget rootWidget) else { retVal = false; - Log.Error("Could not find layout element in xml file " + configFile + ", panel: " + rootWidget.Name); + _logger?.LogError("Could not find layout element in xml file {ConfigFile}, panel: {PanelName}", configFile, rootWidget.Name); } } else { - Log.Error("Could not find config file " + configFile); + _logger?.LogError("Could not find config file {ConfigFile}", configFile); retVal = false; } @@ -366,7 +371,7 @@ private void getWidgetList(string widgetNames, List widgetList) /// xml node that contains layout info private void loadChildren(Widget rootWidget, XmlNode node) { - Log.Debug("rootWidget=" + rootWidget.Name); + _logger?.LogDebug("rootWidget={Name}", rootWidget.Name); XmlNodeList widgetNodes = node.SelectNodes("Widget"); if (widgetNodes == null) { diff --git a/src/Libraries/ACATCore/WidgetManagement/Layout/WidgetAttribute.cs b/src/Libraries/ACATCore/WidgetManagement/Layout/WidgetAttribute.cs index 3c561644..25579797 100644 --- a/src/Libraries/ACATCore/WidgetManagement/Layout/WidgetAttribute.cs +++ b/src/Libraries/ACATCore/WidgetManagement/Layout/WidgetAttribute.cs @@ -8,6 +8,7 @@ using ACAT.Core.Interpreter; using ACAT.Core.Utility; using ACATResources; +using Microsoft.Extensions.Logging; using System; using System.Collections; using System.Drawing; @@ -22,6 +23,8 @@ namespace ACAT.Core.WidgetManagement.Layout /// public class WidgetAttribute : IDisposable { + private static ILogger _logger; + /// /// The code to execute when the user clicks on the button /// @@ -127,9 +130,11 @@ public WidgetAttribute() /// /// /// the xml node + /// Logger instance /// button attribute object - public static WidgetAttribute CreateWidgetAttribute(XmlNode node) + public static WidgetAttribute CreateWidgetAttribute(XmlNode node, ILogger logger = null) { + _logger = logger; var widgetAttribute = new WidgetAttribute(); widgetAttribute.load(node); return widgetAttribute; @@ -156,7 +161,7 @@ protected virtual void Dispose(bool disposing) // Check to see if Dispose has already been called. if (!_disposed) { - Log.Verbose(); + _logger?.LogTrace(""); if (disposing) { @@ -263,7 +268,7 @@ private void parseModifiers(string modifiers) } else { - Log.Error("Invalid modifier " + modifier + " for widgetAttribute entry " + Name); + _logger?.LogError("Invalid modifier {Modifier} for widgetAttribute entry {Name}", modifier, Name); Modifiers = null; break; } diff --git a/src/Libraries/ACATCore/WidgetManagement/Layout/WidgetAttributes.cs b/src/Libraries/ACATCore/WidgetManagement/Layout/WidgetAttributes.cs index 459b2cea..9aab6332 100644 --- a/src/Libraries/ACATCore/WidgetManagement/Layout/WidgetAttributes.cs +++ b/src/Libraries/ACATCore/WidgetManagement/Layout/WidgetAttributes.cs @@ -6,6 +6,7 @@ //////////////////////////////////////////////////////////////////////////// using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.IO; @@ -20,6 +21,8 @@ namespace ACAT.Core.WidgetManagement.Layout /// public class WidgetAttributes : IDisposable { + private readonly ILogger _logger; + /// /// Has this object been disposed /// @@ -33,8 +36,10 @@ public class WidgetAttributes : IDisposable /// /// Initializes a new instance of the class. /// - public WidgetAttributes() + /// Logger instance + public WidgetAttributes(ILogger logger = null) { + _logger = logger; _widgetAttributes = new Dictionary(); } @@ -104,7 +109,7 @@ public bool Load(string configFile) var xmlDoc = new XmlDocument(); - Log.Debug($"Loading config file {configFile}."); + _logger?.LogDebug("Loading config file {ConfigFile}.", configFile); try { @@ -113,7 +118,7 @@ public bool Load(string configFile) XmlNodeList widgetAttributeNodes = xmlDoc.SelectNodes("/ACAT/WidgetAttributes/WidgetAttribute"); if (_widgetAttributes == null) { - Log.Error("widgetAttributes == null."); + _logger?.LogError("widgetAttributes == null."); return false; } @@ -131,12 +136,12 @@ public bool Load(string configFile) } catch (FileNotFoundException) { - Log.Exception($"Could not load config file. File does not exist - {configFile}"); + _logger?.LogError("Could not load config file. File does not exist - {ConfigFile}", configFile); retVal = false; } catch (Exception ex) { - Log.Exception($"Error loading config file {configFile} - {ex}"); + _logger?.LogError(ex, "Error loading config file {ConfigFile}", configFile); retVal = false; } @@ -152,7 +157,7 @@ protected virtual void Dispose(bool disposing) // Check to see if Dispose has already been called. if (!_disposed) { - Log.Verbose(); + _logger?.LogTrace(""); if (disposing) { diff --git a/src/Libraries/ACATCore/WidgetManagement/Widget.cs b/src/Libraries/ACATCore/WidgetManagement/Widget.cs index 0a47d0cd..c3ec6df9 100644 --- a/src/Libraries/ACATCore/WidgetManagement/Widget.cs +++ b/src/Libraries/ACATCore/WidgetManagement/Widget.cs @@ -10,6 +10,7 @@ using ACAT.Core.Utility; using ACAT.Core.WidgetManagement.Interfaces; using ACAT.Core.WidgetManagement.Layout; +using Microsoft.Extensions.Logging; using System; using System.Collections; using System.Collections.Generic; @@ -57,6 +58,8 @@ namespace ACAT.Core.WidgetManagement /// public class Widget : IDisposable { + private readonly ILogger _logger; + /// /// The enabled state of the widget. /// @@ -113,8 +116,11 @@ public class Widget : IDisposable /// Initializes an instance of the widget class /// /// The .NET Control that represents this widget - public Widget(Control control) + /// Logger instance + public Widget(Control control, ILogger logger) { + _logger = logger; + UIControl = control; _children = new List(); @@ -167,8 +173,9 @@ public Widget(Control control) /// Initializes an instance of the Widget class with the name /// /// - public Widget(String name) - : this((Control)null) + /// Logger instance + public Widget(String name, ILogger logger = null) + : this((Control)null, logger) { widgetName = name; } @@ -752,22 +759,22 @@ public virtual int Width /// public virtual void Actuate(bool repeatActuate = false) { - Log.Debug("LARAM " + widgetName + "!!!!!!!!!!!!!!!!" + " repeatActuate = " + repeatActuate); + _logger.LogDebug("LARAM {WidgetName}!!!!!!!!!!!!!!!! repeatActuate = {RepeatActuate}", widgetName, repeatActuate); if (!Enabled) { - Log.Debug("LARAM " + widgetName + " is not enabled. Will not actuate"); + _logger.LogDebug("LARAM {WidgetName} is not enabled. Will not actuate", widgetName); } else { if (EvtActuated != null) { - Log.Debug("LARAM EvtActuated is not null. Calling actuate for " + widgetName); + _logger.LogDebug("LARAM EvtActuated is not null. Calling actuate for {WidgetName}", widgetName); EvtActuated(this, new WidgetActuatedEventArgs(this, repeatActuate)); } else { - Log.Debug("LARAM EvtActuated is null for " + widgetName); + _logger.LogDebug("LARAM EvtActuated is null for {WidgetName}", widgetName); } } } @@ -881,7 +888,7 @@ public void Dispose() /// public void Dump() { - Log.Debug("Widget Name: " + Name); + _logger.LogDebug("Widget Name: {Name}", Name); if (_children.Count == 0) { @@ -942,7 +949,7 @@ public bool HighlightOff() } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex, ex.Message); } return true; @@ -1171,7 +1178,7 @@ protected virtual void Dispose(bool disposing) // Check to see if Dispose has already been called. if (!_disposed) { - Log.Verbose(); + _logger.LogTrace(""); if (disposing) { @@ -1285,7 +1292,7 @@ protected void notifyEvtHighlightOn(out bool handled) handled = false; if (EvtHighlightOn != null) { - Log.Debug("EvtHighlightOn is not null. Triggering event"); + _logger.LogDebug("EvtHighlightOn is not null. Triggering event"); Delegate[] delegates = EvtHighlightOn.GetInvocationList(); bool eventHandled = false; @@ -1301,11 +1308,11 @@ protected void notifyEvtHighlightOn(out bool handled) } handled = eventHandled; - Log.Debug("EvtHighlightOn returned. handled = " + handled); + _logger.LogDebug("EvtHighlightOn returned. handled = {Handled}", handled); } else { - Log.Debug("EvtHighlightOn is null!"); + _logger.LogDebug("EvtHighlightOn is null!"); } } @@ -1436,7 +1443,7 @@ private void control_MouseClick(object sender, MouseEventArgs e) { if (Enabled && EvtMouseClicked != null) { - Log.Debug("Widget control_MouseClick"); + _logger.LogDebug("Widget control_MouseClick"); EvtMouseClicked(this, new WidgetEventArgs(this)); } diff --git a/src/Libraries/ACATCore/WidgetManagement/WidgetManager.cs b/src/Libraries/ACATCore/WidgetManagement/WidgetManager.cs index 2615d0ca..73966f9c 100644 --- a/src/Libraries/ACATCore/WidgetManagement/WidgetManager.cs +++ b/src/Libraries/ACATCore/WidgetManagement/WidgetManager.cs @@ -8,6 +8,7 @@ using ACAT.Core.Utility; using ACAT.Core.WidgetManagement.Interfaces; using ACAT.Core.WidgetManagement.Layout; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.IO; @@ -30,6 +31,8 @@ namespace ACAT.Core.WidgetManagement /// public class WidgetManager : IDisposable { + private readonly ILogger _logger; + /// /// Holds the types of all classes in the executing assembly that /// derive from the Widget class @@ -59,14 +62,18 @@ public class WidgetManager : IDisposable /// /// Initializes a new instance of WidgetManager /// - public WidgetManager(Control control) + /// Root control + /// Logger instance + public WidgetManager(Control control, ILogger logger) { - _widgetAttributes = new WidgetAttributes(); - _layout = new LayoutAttribute(); - _rootWidget = new Widget(control); + _logger = logger; + + _widgetAttributes = new WidgetAttributes(logger); + _layout = new LayoutAttribute(logger); + _rootWidget = new Widget(control, null); - Log.Debug("control name is " + control.Name); - Log.Debug("_rootWidget.name is " + _rootWidget.Name); + _logger.LogDebug("control name is {Name}", control.Name); + _logger.LogDebug("_rootWidget.name is {Name}", _rootWidget.Name); } /// @@ -123,7 +130,7 @@ public static Type GetWidgetType(String widgetTypeName) } catch (Exception ex) { - Log.Exception("Could not find widgettype " + widgetTypeName + ", exception: " + ex); + _logger.LogError(ex, "Could not find widgettype {WidgetTypeName}", widgetTypeName); } return retVal; @@ -190,18 +197,18 @@ public bool Initialize(String configPath) if (retVal) { - Log.Debug("configPath: " + configPath); + _logger.LogDebug("configPath: {ConfigPath}", configPath); retVal = Layout.Load(configPath, _rootWidget); if (retVal) { - Log.Debug($"Layout for root widget {Layout.RootWidget.Name}"); + _logger.LogDebug("Layout for root widget {Name}", Layout.RootWidget.Name); retrieveAndSetWidgetAttribute(Layout.RootWidget); } } else { - Log.Error($"Could not load WidgetAttributes from configFile [{configPath}]"); + _logger.LogError("Could not load WidgetAttributes from configFile [{ConfigPath}]", configPath); } return retVal; @@ -216,7 +223,7 @@ protected virtual void Dispose(bool disposing) // Check to see if Dispose has already been called. if (!_disposed) { - Log.Verbose(); + _logger.LogTrace(""); if (disposing) { @@ -258,7 +265,7 @@ private static bool loadTypesFromAssembly(Assembly assembly) } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex, ex.Message); retVal = false; } @@ -374,7 +381,7 @@ private static void onFileFound(String file) /// private void retrieveAndSetWidgetAttribute(Widget widget) { - Log.Debug("widget.Name=" + widget.Name); + _logger.LogDebug("widget.Name={Name}", widget.Name); if (widget is IButtonWidget && WidgetAttributes.Contains(widget.Name)) { diff --git a/src/Libraries/ACATCore/Widgets/ButtonControlWidget.cs b/src/Libraries/ACATCore/Widgets/ButtonControlWidget.cs index 54680dc4..ab99aeb9 100644 --- a/src/Libraries/ACATCore/Widgets/ButtonControlWidget.cs +++ b/src/Libraries/ACATCore/Widgets/ButtonControlWidget.cs @@ -9,6 +9,7 @@ using ACAT.Core.ThemeManagement; using ACAT.Core.Utility; using ACAT.Core.WidgetManagement.Layout; +using Microsoft.Extensions.Logging; using System.Drawing; using System.Windows.Forms; @@ -20,6 +21,8 @@ namespace ACAT.Core.Widgets /// public class ButtonControlWidget : ButtonWidgetBase { + private readonly ILogger _logger; + /// /// Has this object been disposed off yet? /// @@ -34,9 +37,12 @@ public class ButtonControlWidget : ButtonWidgetBase /// Initializes a new instance of the class. /// /// the inner .NET Control for the widget - public ButtonControlWidget(Control uiControl) - : base(uiControl) + /// Logger instance + public ButtonControlWidget(Control uiControl, ILogger logger) + : base(uiControl, logger) { + _logger = logger; + if (uiControl is Button) { Colors = ThemeManager.Instance.ActiveTheme.Colors.GetColorScheme(ColorSchemes.ButtonSchemeName); @@ -55,8 +61,11 @@ public ButtonControlWidget( string command, string fontname, int fontsize, - bool bold) : this(uiControl) + bool bold, + ILogger logger) : this(uiControl, logger) { + _logger = logger; + uiControl.Name = name; uiControl.Text = label; uiControl.Font = new Font(fontname, fontsize, bold ? FontStyle.Bold : FontStyle.Regular); @@ -107,7 +116,7 @@ protected override void Dispose(bool disposing) { try { - Log.Verbose(); + _logger.LogTrace(""); if (disposing) { diff --git a/src/Libraries/ACATCore/Widgets/ButtonWidgetBase.cs b/src/Libraries/ACATCore/Widgets/ButtonWidgetBase.cs index 87b16385..5d3b533f 100644 --- a/src/Libraries/ACATCore/Widgets/ButtonWidgetBase.cs +++ b/src/Libraries/ACATCore/Widgets/ButtonWidgetBase.cs @@ -9,6 +9,7 @@ using ACAT.Core.WidgetManagement; using ACAT.Core.WidgetManagement.Interfaces; using ACAT.Core.WidgetManagement.Layout; +using Microsoft.Extensions.Logging; using System.Windows.Forms; namespace ACAT.Core.Widgets @@ -18,6 +19,8 @@ namespace ACAT.Core.Widgets /// public class ButtonWidgetBase : Widget, IButtonWidget { + private readonly ILogger _logger; + /// /// The widgetAttribute object that encapsulates all /// the attributes for this widget @@ -33,9 +36,12 @@ public class ButtonWidgetBase : Widget, IButtonWidget /// Initializes a new instance of the class. /// /// the inner .NET Control for the widget - public ButtonWidgetBase(Control uiControl) - : base(uiControl) + /// Logger instance + public ButtonWidgetBase(Control uiControl, ILogger logger) + : base(uiControl, logger) { + _logger = logger; + widgetAttribute = null; Value = null; @@ -78,7 +84,7 @@ protected override void Dispose(bool disposing) { try { - Log.Verbose(); + _logger.LogTrace(""); if (disposing) { diff --git a/src/Libraries/ACATCore/Widgets/CheckBoxWidget.cs b/src/Libraries/ACATCore/Widgets/CheckBoxWidget.cs index 2a89c0d9..9a0a3a7c 100644 --- a/src/Libraries/ACATCore/Widgets/CheckBoxWidget.cs +++ b/src/Libraries/ACATCore/Widgets/CheckBoxWidget.cs @@ -7,6 +7,7 @@ using ACAT.Core.Utility; using ACAT.Core.WidgetManagement; +using Microsoft.Extensions.Logging; using System; using System.Windows.Forms; @@ -56,6 +57,8 @@ public static void SetState(this CheckBoxWidget widget, Boolean state) /// public class CheckBoxWidget : LabelWidget { + private readonly ILogger _logger; + /// /// Assuming we are using the "ACAT Icon" font, the /// text for the OFF state @@ -77,9 +80,10 @@ public class CheckBoxWidget : LabelWidget /// Initializes a new instance of the class. /// /// the inner .NET Control for the widget - public CheckBoxWidget(Control uiControl) + public CheckBoxWidget(Control uiControl, ILogger logger = null) : base(uiControl) { + _logger = logger ?? LoggerFactory.Create(builder => builder.AddConsole()).CreateLogger(); EvtActuated += CheckBoxWidget_EvtActuated; SetToggleState(_toggleState); } @@ -99,7 +103,7 @@ public bool GetToggleState() /// xml node to parse public override void Load(System.Xml.XmlNode node) { - Log.Debug("node=" + node); + _logger.LogDebug("node=" + node); String onOffState = XmlUtils.GetXMLAttrString(node, "onOffState"); bool toggle; diff --git a/src/Libraries/ACATCore/Widgets/CurrentWordWidget.cs b/src/Libraries/ACATCore/Widgets/CurrentWordWidget.cs index 938c9065..b58b2e91 100644 --- a/src/Libraries/ACATCore/Widgets/CurrentWordWidget.cs +++ b/src/Libraries/ACATCore/Widgets/CurrentWordWidget.cs @@ -6,6 +6,7 @@ //////////////////////////////////////////////////////////////////////////// using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Timers; using System.Windows.Forms; @@ -20,6 +21,8 @@ namespace ACAT.Core.Widgets /// public class CurrentWordWidget : LabelWidget { + private readonly ILogger _logger; + /// /// Timer to simulate a blinking cursor /// @@ -44,9 +47,12 @@ public class CurrentWordWidget : LabelWidget /// Initializes a new instance of the class. /// /// the inner .NET Control for the widget - public CurrentWordWidget(Control control) - : base(control) + /// Logger instance + public CurrentWordWidget(Control control, ILogger logger) + : base(control, logger) { + _logger = logger; + if (control is Label) { var label = (Label)control; @@ -81,7 +87,7 @@ protected override void Dispose(bool disposing) { try { - Log.Verbose(); + _logger.LogTrace(""); if (disposing) { diff --git a/src/Libraries/ACATCore/Widgets/ImageWidget.cs b/src/Libraries/ACATCore/Widgets/ImageWidget.cs index 1a8c0df7..c7dfa4fd 100644 --- a/src/Libraries/ACATCore/Widgets/ImageWidget.cs +++ b/src/Libraries/ACATCore/Widgets/ImageWidget.cs @@ -7,6 +7,7 @@ using ACAT.Core.Utility; using ACAT.Core.WidgetManagement.Layout; +using Microsoft.Extensions.Logging; using System; using System.Drawing; using System.Windows.Forms; @@ -25,6 +26,8 @@ namespace ACAT.Core.Widgets /// public class ImageWidget : ImageWidgetBase { + private readonly ILogger _logger; + /// /// Height of the cropped image /// @@ -59,9 +62,11 @@ public class ImageWidget : ImageWidgetBase /// Initializes a new instance of the class. /// /// the inner .NET Control for the widget - public ImageWidget(Control uiControl) - : base(uiControl) + /// Logger instance + public ImageWidget(Control uiControl, ILogger logger) + : base(uiControl, logger) { + _logger = logger; } /// @@ -117,7 +122,7 @@ protected override void Dispose(bool disposing) { try { - Log.Verbose(); + _logger.LogTrace(""); if (disposing) { @@ -157,7 +162,7 @@ protected override void UIControl_Paint(object sender, PaintEventArgs e) } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex, ex.Message); } } diff --git a/src/Libraries/ACATCore/Widgets/ImageWidgetBase.cs b/src/Libraries/ACATCore/Widgets/ImageWidgetBase.cs index 58efb989..59d22a83 100644 --- a/src/Libraries/ACATCore/Widgets/ImageWidgetBase.cs +++ b/src/Libraries/ACATCore/Widgets/ImageWidgetBase.cs @@ -6,6 +6,7 @@ //////////////////////////////////////////////////////////////////////////// using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Drawing; using System.Windows.Forms; @@ -18,6 +19,8 @@ namespace ACAT.Core.Widgets /// public class ImageWidgetBase : ButtonWidgetBase { + private readonly ILogger _logger; + /// /// The Picturebox element for this widget /// @@ -32,9 +35,12 @@ public class ImageWidgetBase : ButtonWidgetBase /// Initializes a new instance of the class. /// /// the inner .NET Control for the widget - public ImageWidgetBase(Control control) - : base(control) + /// Logger instance + public ImageWidgetBase(Control control, ILogger logger) + : base(control, logger) { + _logger = logger; + IsHighlightOn = false; IsSelectedHighlightOn = false; @@ -134,7 +140,7 @@ protected override void Dispose(bool disposing) { try { - Log.Verbose(); + _logger.LogTrace(""); if (disposing) { diff --git a/src/Libraries/ACATCore/Widgets/LabelWidget.cs b/src/Libraries/ACATCore/Widgets/LabelWidget.cs index 18a8e912..d99903eb 100644 --- a/src/Libraries/ACATCore/Widgets/LabelWidget.cs +++ b/src/Libraries/ACATCore/Widgets/LabelWidget.cs @@ -8,6 +8,7 @@ using ACAT.Core.PanelManagement.Utils; using ACAT.Core.Utility; using ACAT.Core.WidgetManagement.Layout; +using Microsoft.Extensions.Logging; using System; using System.Drawing; using System.Windows.Forms; @@ -21,6 +22,8 @@ namespace ACAT.Core.Widgets /// public class LabelWidget : ButtonWidgetBase { + private readonly ILogger _logger; + /// /// Should the corners of the control be rounded? /// @@ -55,9 +58,12 @@ public class LabelWidget : ButtonWidgetBase /// Initializes a new instance of the class. /// /// the inner .NET Control for the widget - public LabelWidget(Control uiControl) - : base(uiControl) + /// Logger instance + public LabelWidget(Control uiControl, ILogger logger) + : base(uiControl, logger) { + _logger = logger; + Label label = (Label)uiControl; label.Paint += label_Paint; @@ -145,7 +151,7 @@ protected override void Dispose(bool disposing) { try { - Log.Verbose(); + _logger.LogTrace(""); if (disposing) { @@ -197,7 +203,7 @@ private void label_Paint(object sender, PaintEventArgs e) } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex, ex.Message); } } diff --git a/src/Libraries/ACATCore/Widgets/LetterListItemWidget.cs b/src/Libraries/ACATCore/Widgets/LetterListItemWidget.cs index af6d6098..f8776e5b 100644 --- a/src/Libraries/ACATCore/Widgets/LetterListItemWidget.cs +++ b/src/Libraries/ACATCore/Widgets/LetterListItemWidget.cs @@ -7,6 +7,7 @@ using ACAT.Core.ThemeManagement; using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Windows.Forms; @@ -18,13 +19,16 @@ namespace ACAT.Core.Widgets /// public class LetterListItemWidget : ScannerButtonBase { + private readonly ILogger _logger; + /// /// Initializes a new instance of the class. /// /// the inner .NET Control for the widget - public LetterListItemWidget(Control control) + public LetterListItemWidget(Control control, ILogger logger = null) : base(control) { + _logger = logger ?? LoggerFactory.Create(builder => builder.AddConsole()).CreateLogger(); if (button != null) { button.AutoEllipsis = true; @@ -43,7 +47,7 @@ public override bool CanAddForAnimation() { String text = GetText().Trim(); AddForAnimation = !String.IsNullOrEmpty(text); - Log.Debug(" LetterListItem " + Name + ", AddForAnimation: " + AddForAnimation + ", Text: [" + text + "]"); + _logger.LogDebug(" LetterListItem " + Name + ", AddForAnimation: " + AddForAnimation + ", Text: [" + text + "]"); return AddForAnimation; } } diff --git a/src/Libraries/ACATCore/Widgets/ScannerButtonBase.cs b/src/Libraries/ACATCore/Widgets/ScannerButtonBase.cs index bd1421f7..863d9921 100644 --- a/src/Libraries/ACATCore/Widgets/ScannerButtonBase.cs +++ b/src/Libraries/ACATCore/Widgets/ScannerButtonBase.cs @@ -8,6 +8,7 @@ using ACAT.Core.PanelManagement.Utils; using ACAT.Core.Utility; using ACAT.Core.WidgetManagement.Layout; +using Microsoft.Extensions.Logging; using System.Drawing; using System.Windows.Forms; @@ -21,6 +22,8 @@ namespace ACAT.Core.Widgets /// public class ScannerButtonBase : ButtonWidgetBase { + private readonly ILogger _logger; + /// /// The Button UI control /// @@ -56,9 +59,11 @@ private FontFamily _fontFamily /// Initializes a new instance of the class. /// /// the inner .NET Control for the widget - public ScannerButtonBase(Control uiControl) - : base(uiControl) + /// Logger instance + public ScannerButtonBase(Control uiControl, ILogger logger) + : base(uiControl, logger) { + _logger = logger; button = uiControl as Button; } @@ -138,7 +143,7 @@ protected override void Dispose(bool disposing) { try { - Log.Verbose(); + _logger.LogTrace(""); if (disposing) { diff --git a/src/Libraries/ACATCore/Widgets/SentenceListItemWidget.cs b/src/Libraries/ACATCore/Widgets/SentenceListItemWidget.cs index 0a40bcfa..eb9e3f57 100644 --- a/src/Libraries/ACATCore/Widgets/SentenceListItemWidget.cs +++ b/src/Libraries/ACATCore/Widgets/SentenceListItemWidget.cs @@ -7,6 +7,7 @@ using ACAT.Core.ThemeManagement; using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Windows.Forms; @@ -18,13 +19,18 @@ namespace ACAT.Core.Widgets /// public class SentenceListItemWidget : ScannerButtonBase { + private readonly ILogger _logger; + /// /// Initializes a new instance of the class. /// /// the inner .NET Control for the widget - public SentenceListItemWidget(Control control) - : base(control) + /// Logger instance + public SentenceListItemWidget(Control control, ILogger logger) + : base(control, logger) { + _logger = logger; + if (button != null) { button.AutoEllipsis = true; @@ -43,7 +49,7 @@ public override bool CanAddForAnimation() { String text = GetText().Trim(); AddForAnimation = !String.IsNullOrEmpty(text) && text != ". . ."; - Log.Debug("SentenceListItem " + Name + ", AddForAnimation: " + AddForAnimation + ", Text: [" + text + "]"); + _logger.LogDebug("SentenceListItem {Name}, AddForAnimation: {AddForAnimation}, Text: [{Text}]", Name, AddForAnimation, text); return AddForAnimation; } } diff --git a/src/Libraries/ACATCore/Widgets/SliderWidget.cs b/src/Libraries/ACATCore/Widgets/SliderWidget.cs index e14ffbd6..fd3c8b21 100644 --- a/src/Libraries/ACATCore/Widgets/SliderWidget.cs +++ b/src/Libraries/ACATCore/Widgets/SliderWidget.cs @@ -8,6 +8,7 @@ using ACAT.Core.Utility; using ACAT.Core.WidgetManagement; using ACATResources; +using Microsoft.Extensions.Logging; using System; using System.Globalization; using System.Windows.Forms; @@ -62,6 +63,8 @@ public static void SetState(this SliderWidget sliderWidget, int sliderPosition, /// public class SliderWidget : Widget { + private readonly ILogger _logger; + public const decimal SliderUnitsHundredths = 0.01M; /// @@ -142,9 +145,11 @@ public class SliderWidget : Widget /// Initializes a new instance of the class. /// /// the inner .NET Control for the widget - public SliderWidget(Control uiControl) - : base(uiControl) + /// Logger instance + public SliderWidget(Control uiControl, ILogger logger) + : base(uiControl, logger) { + _logger = logger; EvtChildAdded += SliderWidget_EvtChildAdded; } @@ -192,7 +197,7 @@ public override void Load(XmlNode node) if (_decimalStep >= 1) { - Log.Error("SliderWidget::Load() - Warning! Decimal step is greater than/equal to 1!"); + _logger.LogError("SliderWidget::Load() - Warning! Decimal step is greater than/equal to 1!"); } _minValue = 0; @@ -304,8 +309,8 @@ private void _incrementWidget_EvtActuated(object sender, WidgetActuatedEventArgs /// event args private void _trackBar_ValueChanged(object sender, EventArgs e) { - Log.Debug("trackbar value: " + _trackBar.Value); - Log.Debug("Widget: " + _trackBar.Name + ". Setting value to " + ConvertTicksToRealValue(_trackBar.Value)); + _logger.LogDebug("trackbar value: {Value}", _trackBar.Value); + _logger.LogDebug("Widget: {Name}. Setting value to {RealValue}", _trackBar.Name, ConvertTicksToRealValue(_trackBar.Value)); Windows.SetText(_currentValueControl, ConvertTicksToRealValue(_trackBar.Value).ToString()); @@ -341,7 +346,7 @@ private void setTickPosition(int tickPosition) { if ((tickPosition > _maxTicks) || (tickPosition < _minTicks)) { - Log.Error("SetTickPosition() - tickPosition out of acceptable range!"); + _logger.LogError("SetTickPosition() - tickPosition out of acceptable range!"); } Windows.SetTrackBarValue(_trackBar, tickPosition); @@ -407,7 +412,7 @@ private void SliderWidget_EvtChildAdded(object sender, WidgetEventArgs e) break; default: - Log.Debug("Unrecognized subclass " + subclass); + _logger.LogDebug("Unrecognized subclass {Subclass}", subclass); break; } } @@ -428,7 +433,7 @@ private bool stringToDecimal(String inputString, ref decimal value) } catch (Exception ex) { - Log.Exception("Error parsing decimal " + inputString + ", ex: " + ex.ToString()); + _logger.LogError(ex, "Error parsing decimal {InputString}", inputString); retVal = false; } diff --git a/src/Libraries/ACATCore/Widgets/TabStopScannerButton.cs b/src/Libraries/ACATCore/Widgets/TabStopScannerButton.cs index 627d60d6..2e296f67 100644 --- a/src/Libraries/ACATCore/Widgets/TabStopScannerButton.cs +++ b/src/Libraries/ACATCore/Widgets/TabStopScannerButton.cs @@ -6,6 +6,7 @@ //////////////////////////////////////////////////////////////////////////// using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Drawing; using System.Windows.Forms; @@ -19,6 +20,8 @@ namespace ACAT.Core.Widgets /// public class TabStopScannerButton : ScannerButtonBase { + private readonly ILogger _logger; + /// /// First tab stop before the widget has been scaled /// @@ -53,9 +56,11 @@ public class TabStopScannerButton : ScannerButtonBase /// Initializes a new instance of the class. /// /// the inner .NET Control for the widget - public TabStopScannerButton(Control uiControl) - : base(uiControl) + /// Logger instance + public TabStopScannerButton(Control uiControl, ILogger logger) + : base(uiControl, logger) { + _logger = logger; _text = String.Empty; } @@ -170,7 +175,7 @@ protected override void UIControl_Paint(object sender, PaintEventArgs e) } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex, ex.Message); } } diff --git a/src/Libraries/ACATCore/Widgets/TextBoxWidget.cs b/src/Libraries/ACATCore/Widgets/TextBoxWidget.cs index fc234a12..b9efcb6c 100644 --- a/src/Libraries/ACATCore/Widgets/TextBoxWidget.cs +++ b/src/Libraries/ACATCore/Widgets/TextBoxWidget.cs @@ -8,6 +8,7 @@ using ACAT.Core.PanelManagement.Utils; using ACAT.Core.Utility; using ACAT.Core.WidgetManagement.Layout; +using Microsoft.Extensions.Logging; using System.Drawing; using System.Windows.Forms; @@ -19,6 +20,8 @@ namespace ACAT.Core.Widgets /// public class TextBoxWidget : ButtonWidgetBase { + private readonly ILogger _logger; + /// /// Has this been disposed? /// @@ -43,9 +46,11 @@ public class TextBoxWidget : ButtonWidgetBase /// Initializes a new instance of the class. /// /// the inner .NET Control for the widget - public TextBoxWidget(Control uiControl) - : base(uiControl) + /// Logger instance + public TextBoxWidget(Control uiControl, ILogger logger) + : base(uiControl, logger) { + _logger = logger; } /// @@ -102,7 +107,7 @@ protected override void Dispose(bool disposing) { try { - Log.Verbose(); + _logger.LogTrace(""); if (disposing) { diff --git a/src/Libraries/ACATCore/Widgets/WordListItemWidget.cs b/src/Libraries/ACATCore/Widgets/WordListItemWidget.cs index e8b58ecd..9e5ea6b1 100644 --- a/src/Libraries/ACATCore/Widgets/WordListItemWidget.cs +++ b/src/Libraries/ACATCore/Widgets/WordListItemWidget.cs @@ -7,6 +7,7 @@ using ACAT.Core.ThemeManagement; using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Windows.Forms; @@ -18,13 +19,18 @@ namespace ACAT.Core.Widgets /// public class WordListItemWidget : ScannerButtonBase { + private readonly ILogger _logger; + /// /// Initializes a new instance of the class. /// /// the inner .NET Control for the widget - public WordListItemWidget(Control control) - : base(control) + /// Logger instance + public WordListItemWidget(Control control, ILogger logger) + : base(control, logger) { + _logger = logger; + if (button != null) { button.AutoEllipsis = true; @@ -43,7 +49,7 @@ public override bool CanAddForAnimation() { String text = GetText().Trim(); AddForAnimation = !String.IsNullOrEmpty(text) && text != ". . ."; - Log.Debug("WordListItemWidget" + Name + ", AddForAnimation: " + AddForAnimation + ", Text: [" + text + "]"); + _logger.LogDebug("WordListItemWidget{Name}, AddForAnimation: {AddForAnimation}, Text: [{Text}]", Name, AddForAnimation, text); return AddForAnimation; } } diff --git a/src/Libraries/ACATCore/WordPredictorManagement/NullWordPredictor.cs b/src/Libraries/ACATCore/WordPredictorManagement/NullWordPredictor.cs index 5d84e940..3d105941 100644 --- a/src/Libraries/ACATCore/WordPredictorManagement/NullWordPredictor.cs +++ b/src/Libraries/ACATCore/WordPredictorManagement/NullWordPredictor.cs @@ -9,6 +9,7 @@ using ACAT.Core.PreferencesManagement.Interfaces; using ACAT.Core.Utility; using ACAT.Core.WordPredictorManagement.Interfaces; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Globalization; @@ -24,6 +25,8 @@ namespace ACAT.Core.WordPredictorManagement "Disable word prediction")] public class NullWordPredictor : IWordPredictor, ISupportsPreferences, IExtension { + private readonly ILogger _logger; + protected WordPredictionModes _wordPredictionMode = WordPredictionModes.Sentence; /// @@ -44,8 +47,10 @@ public class NullWordPredictor : IWordPredictor, ISupportsPreferences, IExtensio /// /// Creates an instance of the class /// - public NullWordPredictor() + /// Logger instance + public NullWordPredictor(ILogger logger = null) { + _logger = logger; _invoker = new ExtensionInvoker(this); } @@ -276,7 +281,7 @@ protected virtual void Dispose(bool disposing) // Check to see if Dispose has already been called. if (!_disposed) { - Log.Verbose(); + _logger?.LogTrace(""); if (disposing) { diff --git a/src/Libraries/ACATCore/WordPredictorManagement/WordPredictionManager.cs b/src/Libraries/ACATCore/WordPredictorManagement/WordPredictionManager.cs index fba3e28f..261a7f4b 100644 --- a/src/Libraries/ACATCore/WordPredictorManagement/WordPredictionManager.cs +++ b/src/Libraries/ACATCore/WordPredictorManagement/WordPredictionManager.cs @@ -11,6 +11,7 @@ using ACAT.Core.PreferencesManagement; using ACAT.Core.Utility; using ACAT.Core.WordPredictorManagement.Interfaces; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Globalization; @@ -28,6 +29,8 @@ namespace ACAT.Core.WordPredictorManagement /// public class WordPredictionManager : IDisposable { + private readonly ILogger _logger; + /// /// Name of the folder under which the Word predictor DLLs are located /// @@ -66,8 +69,11 @@ public class WordPredictionManager : IDisposable /// /// Initializes and instance of the WordPredictionManager class. /// - private WordPredictionManager() + /// Logger instance + private WordPredictionManager(ILogger logger = null) { + _logger = logger; + AppDomain currentDomain = AppDomain.CurrentDomain; Context.EvtCultureChanged += Context_EvtCultureChanged; @@ -385,7 +391,7 @@ protected virtual void Dispose(bool disposing) // Check to see if Dispose has already been called. if (!_disposed) { - Log.Verbose(); + _logger?.LogTrace(""); Context.EvtCultureChanged -= Context_EvtCultureChanged; @@ -436,7 +442,7 @@ private bool createAndSetActiveWordPredictor(Type type, CultureInfo ci) } catch (Exception ex) { - Log.Exception("Unable to load WordPredictor " + type + ", assembly: " + type.Assembly.FullName + ". Exception: " + ex); + _logger?.LogError(ex, "Unable to load WordPredictor {Type}, assembly: {Assembly}", type, type.Assembly.FullName); retVal = false; } diff --git a/src/Libraries/ACATCore/WordPredictorManagement/WordPredictors.cs b/src/Libraries/ACATCore/WordPredictorManagement/WordPredictors.cs index 6089e001..53e86e94 100644 --- a/src/Libraries/ACATCore/WordPredictorManagement/WordPredictors.cs +++ b/src/Libraries/ACATCore/WordPredictorManagement/WordPredictors.cs @@ -9,6 +9,7 @@ using ACAT.Core.Utility; using ACAT.Core.Utility.TypeLoader; using ACAT.Core.WordPredictorManagement.Interfaces; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Globalization; @@ -25,6 +26,8 @@ namespace ACAT.Core.WordPredictorManagement /// public class WordPredictors : IDisposable { + private readonly ILogger _logger; + /// /// Name of the config file where Id's of preferred word predictors are stored /// @@ -66,8 +69,10 @@ public class WordPredictors : IDisposable /// /// Initializes an instance of the WordPredictors class /// - public WordPredictors() + /// Logger instance + public WordPredictors(ILogger logger) { + _logger = logger; _wordPredictors = new List(); _wordPredictorsTypeCache = new Dictionary>(); @@ -171,7 +176,7 @@ public Guid GetDefaultByCulture(CultureInfo ci) ClassDescriptorAttribute descriptor = ClassDescriptorAttribute.GetDescriptor(foundTuple.Item2); if (descriptor != null) { - Log.Debug("Found word predictor for culture " + (ci != null ? ci.TwoLetterISOLanguageName : "Neutral") + "[" + descriptor.Name + "]"); + _logger.LogDebug("Found word predictor for culture {Culture}[{Name}]", (ci != null ? ci.TwoLetterISOLanguageName : "Neutral"), descriptor.Name); return descriptor.Id; } } @@ -263,12 +268,12 @@ public Type Lookup(Guid guid) ClassDescriptorAttribute descriptor = ClassDescriptorAttribute.GetDescriptor(type); if (descriptor != null && Equals(guid, descriptor.Id)) { - Log.Debug("Found word predictor of type " + type); + _logger.LogDebug("Found word predictor of type {Type}", type); return type; } } - Log.Error($"Could not find word predictor for id {guid}"); + _logger.LogError("Could not find word predictor for id {Guid}", guid); return null; } @@ -301,11 +306,11 @@ internal void Add(Guid guid, string language, Type type) { if (_wordPredictorsTypeCache.ContainsKey(guid)) { - Log.Debug("Wordpredictor " + type.FullName + ", guid " + guid.ToString() + " is already added"); + _logger.LogDebug("Wordpredictor {TypeName}, guid {Guid} is already added", type.FullName, guid.ToString()); return; } - Log.Debug("Adding Wordpredictor " + type.FullName + ", guid " + guid.ToString() + " to cache"); + _logger.LogDebug("Adding Wordpredictor {TypeName}, guid {Guid} to cache", type.FullName, guid.ToString()); _wordPredictorsTypeCache.Add(guid, new Tuple(language, type)); } @@ -318,7 +323,7 @@ protected virtual void Dispose(bool disposing) // Check to see if Dispose has already been called. if (!_disposed) { - Log.Verbose(); + _logger.LogTrace(""); _nullWordPredictor?.Dispose(); @@ -344,7 +349,7 @@ private void loadWordPredictorsTypesIntoCache(string dir, string culture, bool r { if (!Directory.Exists(dir)) { - Log.Warn($"Directory {dir} doesn't exist."); + _logger.LogWarning("Directory {Directory} doesn't exist.", dir); return; } DirectoryWalker walker = new(dir, "ACAT.Extensions.WordPredictors.*.dll"); @@ -371,7 +376,7 @@ private void onFileFound(string dllName) } catch (Exception ex) { - Log.Exception($"Error loading actuator from {dllName}: {ex.Message}"); + _logger.LogError(ex, "Error loading actuator from {DllName}", dllName); _DLLError = true; } } diff --git a/src/Libraries/ACATExtension/AppAgents/ACATApp/ACATAgentBase.cs b/src/Libraries/ACATExtension/AppAgents/ACATApp/ACATAgentBase.cs index 6a6769a2..d7ed14af 100644 --- a/src/Libraries/ACATExtension/AppAgents/ACATApp/ACATAgentBase.cs +++ b/src/Libraries/ACATExtension/AppAgents/ACATApp/ACATAgentBase.cs @@ -7,6 +7,7 @@ using ACAT.Core.AgentManagement; using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Diagnostics; @@ -18,6 +19,8 @@ namespace ACAT.Extension.AppAgents.ACATApp /// public class ACATAgentBase : AgentBase { + private readonly ILogger _logger; + /// /// Name of the executing assembly /// @@ -26,8 +29,9 @@ public class ACATAgentBase : AgentBase /// /// Initializes a new instance of the class. /// - public ACATAgentBase() + public ACATAgentBase(ILogger logger) { + _logger = logger; _currentProcessName = Process.GetCurrentProcess().ProcessName.ToLower(); } @@ -54,7 +58,7 @@ public override void OnContextMenuRequest(WindowActivityMonitorInfo monitorInfo) /// set to true if handled public override void OnFocusChanged(WindowActivityMonitorInfo monitorInfo, ref bool handled) { - Log.Verbose(); + _logger.LogTrace(); handled = true; } diff --git a/src/Libraries/ACATExtension/AppAgents/DialogControlAgent/DialogControlAgentBase.cs b/src/Libraries/ACATExtension/AppAgents/DialogControlAgent/DialogControlAgentBase.cs index 9c24e7a6..66088c72 100644 --- a/src/Libraries/ACATExtension/AppAgents/DialogControlAgent/DialogControlAgentBase.cs +++ b/src/Libraries/ACATExtension/AppAgents/DialogControlAgent/DialogControlAgentBase.cs @@ -8,6 +8,7 @@ using ACAT.Core.AgentManagement; using ACAT.Core.PanelManagement.Common; using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; @@ -21,6 +22,8 @@ namespace ACAT.Extension.AppAgents.DialogControlAgent /// public class DialogControlAgentBase : GenericAppAgentBase { + private readonly ILogger _logger; + /// /// If set to true, the agent will autoswitch the /// scanners depending on which element has focus. @@ -34,6 +37,11 @@ public class DialogControlAgentBase : GenericAppAgentBase /// private IntPtr _prevHwnd = IntPtr.Zero; + public DialogControlAgentBase(ILogger logger) + { + _logger = logger; + } + /// /// Gets which processes this agent supported. Use the /// 'magic string' for dialog agents that AgentManager requires @@ -63,13 +71,13 @@ public override void OnContextMenuRequest(WindowActivityMonitorInfo monitorInfo) /// set to true if handled public override void OnFocusChanged(WindowActivityMonitorInfo monitorInfo, ref bool handled) { - Log.Debug("prevHwnd: " + _prevHwnd + ", fgHwnd: " + monitorInfo.FgHwnd); + _logger.LogDebug("prevHwnd: " + _prevHwnd + ", fgHwnd: " + monitorInfo.FgHwnd); base.OnFocusChanged(monitorInfo, ref handled); if (autoSwitchScanners && _prevHwnd != monitorInfo.FgHwnd) { - Log.Debug("They are not equal. Show dialog panel"); + _logger.LogDebug("They are not equal. Show dialog panel"); showPanel(this, new PanelRequestEventArgs(PanelClasses.DialogContextMenu, monitorInfo.Title, diff --git a/src/Libraries/ACATExtension/AppAgents/Outlook/OutlookAgentBase.cs b/src/Libraries/ACATExtension/AppAgents/Outlook/OutlookAgentBase.cs index a3831e90..17f44885 100644 --- a/src/Libraries/ACATExtension/AppAgents/Outlook/OutlookAgentBase.cs +++ b/src/Libraries/ACATExtension/AppAgents/Outlook/OutlookAgentBase.cs @@ -22,6 +22,7 @@ using ACAT.Core.AgentManagement; using ACAT.Core.PanelManagement; using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using Microsoft.Win32; using System; using System.Collections.Generic; @@ -88,6 +89,8 @@ public enum OutlookWindowTypes /// public class OutlookAgentBase : GenericAppAgentBase { + private readonly ILogger _logger; + /// /// The window element (eg button, edit box) that has focus /// @@ -139,8 +142,9 @@ public class OutlookAgentBase : GenericAppAgentBase /// /// Initializes an instance of hte class /// - public OutlookAgentBase() + public OutlookAgentBase(ILogger logger) { + _logger = logger; outlookInspector = createOutlookInspector(); } @@ -214,7 +218,7 @@ public override void OnFocusChanged(WindowActivityMonitorInfo monitorInfo, ref b controlType = monitorInfo.FocusedElement.Current.ControlType; - Log.Debug("OutlookWindowType: " + outlookWindowType + ", subType: " + outlookControlSubType); + _logger.LogDebug("OutlookWindowType: " + outlookWindowType + ", subType: " + outlookControlSubType); String title = PanelTitle; @@ -256,7 +260,7 @@ public override void OnRunCommand(String command, object commandArg, ref bool ha { handled = true; - Log.Debug(command); + _logger.LogDebug(command); switch (command) { case "GotoInbox": @@ -588,7 +592,7 @@ protected async void attachFile() if (String.Compare(info1.Title, "TODO", true) == 0) { - Log.Debug("YES! Found Attach file window"); + _logger.LogDebug("YES! Found Attach file window"); var automationElement = AgentUtils.GetElementOrAncestorByAutomationId( info1.FocusedElement, "Edit", @@ -596,13 +600,13 @@ protected async void attachFile() "1148"); if (automationElement != null) { - Log.Debug("element is not null"); + _logger.LogDebug("element is not null"); AgentUtils.InsertTextIntoElement(automationElement, _fileAttachment); SendKeys.Send("{ENTER}"); } else { - Log.Debug("element is null"); + _logger.LogDebug("element is null"); } break; @@ -652,25 +656,25 @@ protected override TextControlAgentBase createKeyLoggerTextInterface( IntPtr handle, AutomationElement editTextElement) { - Log.Debug("subtype = " + outlookControlSubType); + _logger.LogDebug("subtype = " + outlookControlSubType); TextControlAgentBase textInterface; - Log.Debug("outlookcontrolsubtype: " + outlookControlSubType); + _logger.LogDebug("outlookcontrolsubtype: " + outlookControlSubType); if (isMessageBodyField(outlookControlSubType)) { - Log.Debug("creating outlookagentkeylogger with learn, spell and abbr" + outlookControlSubType); + _logger.LogDebug("creating outlookagentkeylogger with learn, spell and abbr" + outlookControlSubType); textInterface = new OutlookAgentKeyLoggerTextInterface(); } else if (isSubjectField(outlookControlSubType)) { - Log.Debug("iSSubjectfield creating outlookagentkeylogger WITHOUT learn"); + _logger.LogDebug("iSSubjectfield creating outlookagentkeylogger WITHOUT learn"); textInterface = new OutlookAgentKeyLoggerTextInterface(false); } else { - Log.Debug("creating outlookagentkeylogger WITHOUT learn, spellcheck and smart puncutationss"); + _logger.LogDebug("creating outlookagentkeylogger WITHOUT learn, spellcheck and smart puncutationss"); textInterface = new OutlookAgentKeyLoggerTextInterface(false, true, false, false); } @@ -687,7 +691,7 @@ protected override TextControlAgentBase createKeyLoggerTextInterface( /// name of the panel protected String getContextualMenuForWindow(OutlookWindowTypes windowType, ref String title) { - Log.Debug("windowType: " + windowType); + _logger.LogDebug("windowType: " + windowType); String scannerName; title = PanelTitle; @@ -993,9 +997,9 @@ private async Task getFileToAttach() fileBrowserAgent.GetInvoker().SetValue("IncludeFileExtensions", new[] { "*.", "txt", "doc", "docx" }); fileBrowserAgent.GetInvoker().SetValue("ActionVerb", "Attach"); - Log.Debug("Calling ActivateAgent"); + _logger.LogDebug("Calling ActivateAgent"); await Context.AppAgentMgr.ActivateAgent(fileBrowserAgent as IFunctionalAgent); - Log.Debug("Returned from ActivateAgent"); + _logger.LogDebug("Returned from ActivateAgent"); _fileAttachment = fileBrowserAgent.GetInvoker().GetStringValue("SelectedFile"); } diff --git a/src/Libraries/ACATExtension/AppAgents/WindowsExplorer/WindowsExplorerAgentBase.cs b/src/Libraries/ACATExtension/AppAgents/WindowsExplorer/WindowsExplorerAgentBase.cs index 9668bacd..440d0f2d 100644 --- a/src/Libraries/ACATExtension/AppAgents/WindowsExplorer/WindowsExplorerAgentBase.cs +++ b/src/Libraries/ACATExtension/AppAgents/WindowsExplorer/WindowsExplorerAgentBase.cs @@ -22,6 +22,7 @@ using ACAT.Core.AgentManagement; using ACAT.Core.PanelManagement; using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Windows.Automation; @@ -38,6 +39,8 @@ namespace ACAT.Extension.AppAgents.WindowsExplorer /// public class WindowsExplorerAgentBase : GenericAppAgentBase { + private readonly ILogger _logger; + /// /// If set to true, the agent will autoswitch the /// scanners depending on which element has focus. @@ -84,9 +87,10 @@ public override IEnumerable ProcessesSupported get { return new[] { new AgentProcessInfo(ExplorerProcessName) }; } } - public WindowsExplorerAgentBase() + public WindowsExplorerAgentBase(ILogger logger) { - Log.Debug("WindowsExplorerAgentBase Constructed"); + _logger = logger; + _logger.LogDebug("WindowsExplorerAgentBase Constructed"); //AgentName = "Windows Explorer Agent"; //AutoSwitchScanners = true; } @@ -290,7 +294,7 @@ protected bool getMenu(WindowActivityMonitorInfo monitorInfo, ref String panelCl { if (isFileExplorer(windowElement)) { - Log.Debug("isFileExploer is TRUE "); + _logger.LogDebug("isFileExploer is TRUE "); if (Windows.IsMinimized(monitorInfo.FgHwnd)) { retVal = false; @@ -302,16 +306,16 @@ protected bool getMenu(WindowActivityMonitorInfo monitorInfo, ref String panelCl } else { - Log.Debug("isFileExploer is FALSE"); + _logger.LogDebug("isFileExploer is FALSE"); retVal = false; } } else { - Log.Debug("windowElement is NULL"); + _logger.LogDebug("windowElement is NULL"); } - Log.Debug("return from getmenu : " + retVal); + _logger.LogDebug("return from getmenu : " + retVal); return retVal; } @@ -347,7 +351,7 @@ protected bool isDesktopWindow(AutomationElement focusedElement) while (parent != null) { - Log.Debug("class: " + parent.Current.ClassName + ", ctrltype: " + parent.Current.ControlType.ProgrammaticName + ", name: " + parent.Current.Name); + _logger.LogDebug("class: " + parent.Current.ClassName + ", ctrltype: " + parent.Current.ControlType.ProgrammaticName + ", name: " + parent.Current.Name); if (parent == AutomationElement.RootElement || (String.Compare(parent.Current.ClassName, "SysListView32", true) == 0 && String.Compare(parent.Current.ControlType.ProgrammaticName, "ControlType.List", true) == 0 && @@ -356,12 +360,12 @@ protected bool isDesktopWindow(AutomationElement focusedElement) (String.Compare(parent.Current.ClassName, "Shell_TrayWnd", true) == 0 && String.Compare(parent.Current.ControlType.ProgrammaticName, "ControlType.Pane", true) == 0)) { - Log.Debug("Returning true"); + _logger.LogDebug("Returning true"); return true; } parent = walker.GetParent(parent); } - Log.Debug("Returning false"); + _logger.LogDebug("Returning false"); return false; } @@ -384,11 +388,11 @@ protected bool isFileExplorer(AutomationElement windowElement) /// set to true if handled private void displayScanner(WindowActivityMonitorInfo monitorInfo, ref bool handled) { - Log.Debug("Entered"); + _logger.LogDebug("Entered"); if (monitorInfo != null && monitorInfo.FocusedElement != null && monitorInfo.FocusedElement.Current.ControlType.ProgrammaticName == "ControlType.Edit") { - Log.Debug("controtype edit"); + _logger.LogDebug("controtype edit"); //base.OnFocusChanged(monitorInfo, ref handled); //showPanel(this, new PanelRequestEventArgs(PanelClasses.Alphabet, monitorInfo)); @@ -396,7 +400,7 @@ private void displayScanner(WindowActivityMonitorInfo monitorInfo, ref bool hand } else// if (monitorInfo.IsNewWindow) { - Log.Debug("calling getmenu"); + _logger.LogDebug("calling getmenu"); String panel = PanelClasses.None; handled = getMenu(monitorInfo, ref panel); diff --git a/src/Libraries/ACATExtension/CommandHandlers/AppWindowManagementHandler.cs b/src/Libraries/ACATExtension/CommandHandlers/AppWindowManagementHandler.cs index d7124da5..5c1e66fb 100644 --- a/src/Libraries/ACATExtension/CommandHandlers/AppWindowManagementHandler.cs +++ b/src/Libraries/ACATExtension/CommandHandlers/AppWindowManagementHandler.cs @@ -14,6 +14,7 @@ using ACAT.Core.Utility; using ACAT.Extension.UI; using ACATResources; +using Microsoft.Extensions.Logging; using System; using System.Windows.Automation; using System.Windows.Forms; @@ -27,13 +28,17 @@ namespace ACAT.Extension.CommandHandlers /// public class AppWindowManagementHandler : RunCommandHandler { + private readonly ILogger _logger; + /// /// Initializes a new instance of the class. /// /// The command to be executed - public AppWindowManagementHandler(String cmd) + /// Logger instance + public AppWindowManagementHandler(String cmd, ILogger logger) : base(cmd) { + _logger = logger; } /// @@ -241,7 +246,7 @@ private bool isWindowMaximizable(IntPtr fgHandle) if (!Windows.IsApplicationFrameHostProcessWindow(fgHandle)) { - Log.Debug("controltype: " + window.Current.ControlType.ProgrammaticName); + _logger.LogDebug("controltype: " + window.Current.ControlType.ProgrammaticName); bool retVal = false; if (window.TryGetCurrentPattern(WindowPattern.Pattern, out object objPattern)) @@ -249,7 +254,7 @@ private bool isWindowMaximizable(IntPtr fgHandle) var windowPattern = objPattern as WindowPattern; retVal = (windowPattern.Current.CanMaximize) && !windowPattern.Current.IsModal; - Log.Debug("canmaximize: " + windowPattern.Current.CanMaximize + ", ismodal: " + windowPattern.Current.IsModal); + _logger.LogDebug("canmaximize: " + windowPattern.Current.CanMaximize + ", ismodal: " + windowPattern.Current.IsModal); } return retVal; @@ -284,7 +289,7 @@ private bool isWindowMinimizable(IntPtr fgHandle) if (!Windows.IsApplicationFrameHostProcessWindow(fgHandle)) { - Log.Debug("controltype: " + window.Current.ControlType.ProgrammaticName); + _logger.LogDebug("controltype: " + window.Current.ControlType.ProgrammaticName); bool retVal = false; if (window.TryGetCurrentPattern(WindowPattern.Pattern, out object objPattern)) @@ -292,7 +297,7 @@ private bool isWindowMinimizable(IntPtr fgHandle) var windowPattern = objPattern as WindowPattern; retVal = (windowPattern.Current.CanMinimize) && !windowPattern.Current.IsModal; - Log.Debug("canminimize: " + windowPattern.Current.CanMinimize + ", ismodal: " + windowPattern.Current.IsModal); + _logger.LogDebug("canminimize: " + windowPattern.Current.CanMinimize + ", ismodal: " + windowPattern.Current.IsModal); } return retVal; @@ -322,7 +327,7 @@ private bool isWindowSizeable(IntPtr fgHandle) bool retVal = isWindowMaximizable(fgHandle) || isWindowMinimizable(fgHandle); - Log.Debug("returning " + retVal); + _logger.LogDebug("returning " + retVal); return retVal; } diff --git a/src/Libraries/ACATExtension/CommandHandlers/DocumentEditingHandler.cs b/src/Libraries/ACATExtension/CommandHandlers/DocumentEditingHandler.cs index edd0c955..60132204 100644 --- a/src/Libraries/ACATExtension/CommandHandlers/DocumentEditingHandler.cs +++ b/src/Libraries/ACATExtension/CommandHandlers/DocumentEditingHandler.cs @@ -9,6 +9,7 @@ using ACAT.Core.PanelManagement; using ACAT.Core.PanelManagement.CommandDispatcher; using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Windows.Forms; @@ -21,13 +22,17 @@ namespace ACAT.Extension.CommandHandlers /// public class DocumentEditingHandler : RunCommandHandler { + private readonly ILogger _logger; + /// /// Initializes a new instance of the class. /// /// The command to be executed - public DocumentEditingHandler(String cmd) + /// Logger instance + public DocumentEditingHandler(String cmd, ILogger logger) : base(cmd) { + _logger = logger; } /// @@ -128,7 +133,7 @@ public override bool Execute(ref bool handled) } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, ex.Message); retVal = false; } @@ -149,7 +154,7 @@ private void turnOffSelectMode() } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, ex.Message); } } } diff --git a/src/Libraries/ACATExtension/CommandHandlers/FunctionKeyHandler.cs b/src/Libraries/ACATExtension/CommandHandlers/FunctionKeyHandler.cs index 17fff096..cfccf524 100644 --- a/src/Libraries/ACATExtension/CommandHandlers/FunctionKeyHandler.cs +++ b/src/Libraries/ACATExtension/CommandHandlers/FunctionKeyHandler.cs @@ -8,6 +8,7 @@ using ACAT.Core.PanelManagement; using ACAT.Core.PanelManagement.CommandDispatcher; using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Windows.Forms; @@ -21,13 +22,17 @@ namespace ACAT.Extension.CommandHandlers /// public class FunctionKeyHandler : RunCommandHandler { + private readonly ILogger _logger; + /// /// Initializes a new instance of the class. /// /// The command to be executed - public FunctionKeyHandler(String cmd) + /// Logger instance + public FunctionKeyHandler(String cmd, ILogger logger) : base(cmd) { + _logger = logger; } /// @@ -63,7 +68,7 @@ protected bool sendFunctionKey(String keyString) } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, ex.Message); retVal = false; } diff --git a/src/Libraries/ACATExtension/CommandHandlers/GoBackHandler.cs b/src/Libraries/ACATExtension/CommandHandlers/GoBackHandler.cs index 3bf8a315..60c17b41 100644 --- a/src/Libraries/ACATExtension/CommandHandlers/GoBackHandler.cs +++ b/src/Libraries/ACATExtension/CommandHandlers/GoBackHandler.cs @@ -10,6 +10,7 @@ using ACAT.Core.PanelManagement.Common; using ACAT.Core.PanelManagement.Interfaces; using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Windows.Forms; @@ -23,13 +24,17 @@ namespace ACAT.Extension.CommandHandlers /// public class GoBackHandler : RunCommandHandler { + private readonly ILogger _logger; + /// /// Initializes a new instance of the class. /// /// The command to be executed - public GoBackHandler(String cmd) + /// Logger instance + public GoBackHandler(String cmd, ILogger logger) : base(cmd) { + _logger = logger; } /// @@ -48,7 +53,7 @@ public override bool Execute(ref bool handled) bool hasParent = form.Owner != null; - Log.Debug("form: " + form.Name + ", hasParent: " + hasParent); + _logger.LogDebug("form: " + form.Name + ", hasParent: " + hasParent); Windows.CloseForm(form); if (!hasParent) diff --git a/src/Libraries/ACATExtension/CommandHandlers/NavigationHandler.cs b/src/Libraries/ACATExtension/CommandHandlers/NavigationHandler.cs index f67b8ca5..220a39e1 100644 --- a/src/Libraries/ACATExtension/CommandHandlers/NavigationHandler.cs +++ b/src/Libraries/ACATExtension/CommandHandlers/NavigationHandler.cs @@ -10,6 +10,7 @@ using ACAT.Core.PanelManagement; using ACAT.Core.PanelManagement.CommandDispatcher; using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; namespace ACAT.Extension.CommandHandlers @@ -20,13 +21,17 @@ namespace ACAT.Extension.CommandHandlers /// public class NavigationHandler : RunCommandHandler { + private readonly ILogger _logger; + /// /// Initializes a new instance of the class. /// /// The command to be executed - public NavigationHandler(String cmd) + /// Logger instance + public NavigationHandler(String cmd, ILogger logger) : base(cmd) { + _logger = logger; } /// @@ -132,7 +137,7 @@ public override bool Execute(ref bool handled) } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, ex.Message); retVal = false; } @@ -156,7 +161,7 @@ private void turnOnSelectModeIfStickyShiftEnabled() } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, ex.Message); } } } diff --git a/src/Libraries/ACATExtension/CommandHandlers/ShowDialogsHandler.cs b/src/Libraries/ACATExtension/CommandHandlers/ShowDialogsHandler.cs index 8e3dd08c..db1239f4 100644 --- a/src/Libraries/ACATExtension/CommandHandlers/ShowDialogsHandler.cs +++ b/src/Libraries/ACATExtension/CommandHandlers/ShowDialogsHandler.cs @@ -11,6 +11,7 @@ using ACAT.Core.Utility; using ACAT.Extension.UI; using ACATResources; +using Microsoft.Extensions.Logging; using System; using System.Reflection; using System.Windows.Forms; @@ -24,13 +25,17 @@ namespace ACAT.Extension.CommandHandlers /// public class ShowDialogsHandler : RunCommandHandler { + private readonly ILogger _logger; + /// /// Initializes a new instance of the class. /// /// The command to be executed - public ShowDialogsHandler(String cmd) + /// Logger instance + public ShowDialogsHandler(String cmd, ILogger logger) : base(cmd) { + _logger = logger; } /// @@ -124,7 +129,7 @@ private void showDialog(String name) } catch (Exception e) { - Log.Exception("Error creating dialog of type " + name + ". Exception: " + e); + _logger.LogError(e, "Error creating dialog of type " + name + ". Exception: " + e); } } } diff --git a/src/Libraries/ACATExtension/UI/AlphabetScannerCommon.cs b/src/Libraries/ACATExtension/UI/AlphabetScannerCommon.cs index ac2fecb4..e591ebf6 100644 --- a/src/Libraries/ACATExtension/UI/AlphabetScannerCommon.cs +++ b/src/Libraries/ACATExtension/UI/AlphabetScannerCommon.cs @@ -16,6 +16,7 @@ using ACAT.Core.Widgets; using ACAT.Extension.CommandHandlers; using ACATResources; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; @@ -33,6 +34,8 @@ namespace ACAT.Extension.UI /// public class AlphabetScannerCommon : IDisposable { + private readonly ILogger _logger; + /// /// Widget that represents the alphabet scanner /// @@ -83,8 +86,9 @@ public class AlphabetScannerCommon : IDisposable /// Constructor. Initialize the various controls and /// display the UI /// - public AlphabetScannerCommon(IScannerPanel scannerPanel) + public AlphabetScannerCommon(IScannerPanel scannerPanel, ILogger logger) { + _logger = logger; _scannerPanel = scannerPanel; _form = scannerPanel.Form; Dispatcher = new CmdDispatcher(this, scannerPanel); @@ -233,7 +237,7 @@ public bool Initialize(StartupArg startupArg) if (!_scannerCommon.Initialize(startupArg)) { - Log.Error($"Could not initialize form {_form.Name}"); + _logger.LogError($"Could not initialize form {_form.Name}"); return false; } @@ -262,7 +266,7 @@ public void OnClientSizeChanged() /// public void OnClosing(object sender, FormClosingEventArgs e) { - Log.Verbose(); + _logger.LogTrace(); KeyStateTracker.EvtKeyStateChanged -= KeyStateTracker_EvtKeyStateChanged; @@ -335,7 +339,7 @@ public void OnLoad(object sender, EventArgs e) /// public void OnPause() { - Log.Verbose(); + _logger.LogTrace(); _scannerCommon.OnPause(); } @@ -346,7 +350,7 @@ public void OnPause() /// public void OnResume() { - Log.Verbose(); + _logger.LogTrace(); _scannerCommon.OnResume(); @@ -492,7 +496,7 @@ protected virtual void Dispose(bool disposing) // Check to see if Dispose has already been called. if (!_disposed) { - Log.Verbose(); + _logger.LogTrace(); if (disposing) { @@ -514,7 +518,7 @@ protected virtual void Dispose(bool disposing) /// event args private void AppAgent_EvtTextChanged(object sender, EventArgs e) { - Log.Verbose(); + _logger.LogTrace(); try { if (_form.Visible) @@ -524,15 +528,15 @@ private void AppAgent_EvtTextChanged(object sender, EventArgs e) } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex, ex.Message); } - Log.Debug("returning"); + _logger.LogDebug("returning"); } private void autoComplete(WordListItemWidget wordListItemWidget) { - Log.Debug("wordListItemName : " + wordListItemWidget.Name + ", value: " + wordListItemWidget.Value); + _logger.LogDebug("wordListItemName : " + wordListItemWidget.Name + ", value: " + wordListItemWidget.Value); var wordSelected = wordListItemWidget.Value.Trim(); @@ -548,7 +552,7 @@ private void autoComplete(WordListItemWidget wordListItemWidget) private void autoComplete(LetterListItemWidget letterListItemWidget) { - Log.Debug("leterListItemName : " + letterListItemWidget.Name + ", value: " + letterListItemWidget.Value); + _logger.LogDebug("leterListItemName : " + letterListItemWidget.Name + ", value: " + letterListItemWidget.Value); var letterSelected = letterListItemWidget.Value.Trim(); @@ -578,7 +582,7 @@ private void KeyStateTracker_EvtKeyStateChanged() } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, ex.Message); } } @@ -601,7 +605,7 @@ private void refreshWordPredictionsAndSetCurrentWord() CoreGlobals.Stopwatch3.Stop(); - Log.Debug("TimeElapsed for tryRefreshWordPredictionsAndSetCurrentWord: " + CoreGlobals.Stopwatch3.ElapsedMilliseconds); + _logger.LogDebug("TimeElapsed for tryRefreshWordPredictionsAndSetCurrentWord: " + CoreGlobals.Stopwatch3.ElapsedMilliseconds); } /// @@ -651,12 +655,12 @@ private bool tryRefreshWordPredictionsAndSetCurrentWord() // we need the word at the cursor and also the previous n-words // in the current sentence int caretPos = agentContext.TextAgent().GetCaretPos(); - Log.Debug("Perform WordPrediction at caretPos " + caretPos); + _logger.LogDebug("Perform WordPrediction at caretPos " + caretPos); agentContext.TextAgent().GetPrefixAndWordAtCaret(out nwords, out wordAtCaret); - Log.Debug("wordAtCaret: [" + wordAtCaret + "]"); + _logger.LogDebug("wordAtCaret: [" + wordAtCaret + "]"); agentContext.TextAgent().GetCharAtCaret(out charAtCaret); - Log.Debug("charAtCaret: [" + charAtCaret + "]"); + _logger.LogDebug("charAtCaret: [" + charAtCaret + "]"); } if (string.IsNullOrEmpty(nwords) && string.IsNullOrEmpty(wordAtCaret)) @@ -669,12 +673,12 @@ private bool tryRefreshWordPredictionsAndSetCurrentWord() wordAtCaret = string.Empty; } - Log.Debug("wordatcaret length: " + wordAtCaret.Length); + _logger.LogDebug("wordatcaret length: " + wordAtCaret.Length); //Log.Debug("Text: [" + text + "], caretPos: " + caretPos.ToString()); - Log.Debug("Prefix: [" + nwords + "]"); - Log.Debug("CurrentWord: [" + wordAtCaret + "]"); + _logger.LogDebug("Prefix: [" + nwords + "]"); + _logger.LogDebug("CurrentWord: [" + wordAtCaret + "]"); // do the word prediction if (wordAtCaret.Length > 1 && char.IsPunctuation(wordAtCaret[0])) @@ -686,11 +690,11 @@ private bool tryRefreshWordPredictionsAndSetCurrentWord() } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex, ex.Message); retVal = false; } - Log.Debug("Returning"); + _logger.LogDebug("Returning"); return retVal; } diff --git a/src/Libraries/ACATExtension/UI/DialogUtils.cs b/src/Libraries/ACATExtension/UI/DialogUtils.cs index 612ff1c2..b5415bcb 100644 --- a/src/Libraries/ACATExtension/UI/DialogUtils.cs +++ b/src/Libraries/ACATExtension/UI/DialogUtils.cs @@ -10,6 +10,7 @@ using ACAT.Core.PanelManagement; using ACAT.Core.PanelManagement.Interfaces; using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Windows.Forms; @@ -23,6 +24,13 @@ namespace ACAT.Extension.UI /// public class DialogUtils { + private static ILogger _logger; + + static DialogUtils() + { + _logger = LoggerFactory.Create(builder => builder.AddConsole()).CreateLogger(); + } + /// /// Displays a yes no confirmation dialog box. /// @@ -218,7 +226,7 @@ public static async void ShowFileBrowser(string action) } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex, ex.Message); } } @@ -247,11 +255,11 @@ public static async void ShowTaskSwitcher(string taskName = "") IExtension extension = switchWindowsAgent; extension.GetInvoker().SetValue("FilterByProcessName", taskName); await Context.AppAgentMgr.ActivateAgent(switchWindowsAgent as IFunctionalAgent); - Log.Debug("Returned from activate agent"); + _logger.LogDebug("Returned from activate agent"); } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex, ex.Message); } } @@ -280,7 +288,7 @@ public static void ShowTaskSwitcherAltTab(string taskName = "") } catch (Exception e) { - Log.Exception("Error creating task switcher dialog. Exception: " + e); + _logger.LogError(e, "Error creating task switcher dialog. Exception: " + e); } } @@ -309,7 +317,7 @@ private static Form initYesNoDialog(string title, string caption) { const string panelClass = "YesNoDialog"; - Log.Debug("Creating panel " + panelClass); + _logger.LogDebug("Creating panel " + panelClass); Form form = Context.AppPanelManager.CreatePanel(panelClass); if (form == null) { @@ -334,11 +342,11 @@ private static Form initYesNoDialog(string title, string caption) /// The dialog form object private static Form initYesNoScanner(string panelClass, string title, string caption) { - Log.Debug("Creating panel " + panelClass); + _logger.LogDebug("Creating panel " + panelClass); Form form = Context.AppPanelManager.CreatePanel(panelClass, title); if (form == null) { - Log.Debug("Unable to create panel " + panelClass); + _logger.LogDebug("Unable to create panel " + panelClass); return null; } diff --git a/src/Libraries/ACATExtension/UI/HorizontalStripScanner.cs b/src/Libraries/ACATExtension/UI/HorizontalStripScanner.cs index 73120c2a..f407211f 100644 --- a/src/Libraries/ACATExtension/UI/HorizontalStripScanner.cs +++ b/src/Libraries/ACATExtension/UI/HorizontalStripScanner.cs @@ -11,6 +11,7 @@ using ACAT.Core.Utility; using ACAT.Core.WidgetManagement; using ACAT.Extension.CommandHandlers; +using Microsoft.Extensions.Logging; using System; namespace ACAT.Extension @@ -23,6 +24,8 @@ namespace ACAT.Extension "Horizontal strip of buttons")] public partial class HorizontalStripScanner : HorizontalStripScannerBase { + private readonly ILogger _logger; + /// /// The command dispatcher. If the derived class as additional /// commands, just call Commands.Add on this object @@ -37,7 +40,8 @@ public partial class HorizontalStripScanner : HorizontalStripScannerBase /// /// The panel class of the contextual menu /// title of the contextual - public HorizontalStripScanner(String panelClass, String panelTitle) + /// Logger instance + public HorizontalStripScanner(String panelClass, String panelTitle, ILogger logger) : base(panelClass, panelTitle) { commandDispatcher = new Dispatcher(this); @@ -59,7 +63,7 @@ public override RunCommandDispatcher CommandDispatcher /// was this handled here? public override void OnWidgetActuated(WidgetActuatedEventArgs e, ref bool handled) { - Log.Debug("HorizontalStripScanner onWidgetActuated"); + _logger.LogDebug("HorizontalStripScanner onWidgetActuated"); Windows.CloseAsync(this); handled = false; } diff --git a/src/Libraries/ACATExtension/UI/ScannerForms/GenericScannerForm.cs b/src/Libraries/ACATExtension/UI/ScannerForms/GenericScannerForm.cs index f4fb90a3..fe49e68c 100644 --- a/src/Libraries/ACATExtension/UI/ScannerForms/GenericScannerForm.cs +++ b/src/Libraries/ACATExtension/UI/ScannerForms/GenericScannerForm.cs @@ -19,6 +19,7 @@ using ACAT.Core.Utility; using ACAT.Core.WidgetManagement; using ACAT.Extension.CommandHandlers; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; @@ -29,6 +30,7 @@ namespace ACAT.Extension.UI.ScannerForms { public partial class GenericScannerForm : Form, IScannerPanel { + private readonly ILogger _logger; private readonly object _lock = new object(); private ScannerCommon _scannerCommon; @@ -54,8 +56,9 @@ public ScannerCommon ScannerCommon protected string _panelClass; protected ScannerHelper _scannerHelper; private Label label1; - public GenericScannerForm() + public GenericScannerForm(ILogger logger) { + _logger = logger; InitializeComponent(); SubscribeToEvents(); @@ -134,10 +137,10 @@ public void OnFocusChanged(WindowActivityMonitorInfo monitorInfo) public virtual void OnPause() { - Log.Debug("CALIBTEST calling usercontrolmanager.pause"); + _logger.LogDebug("CALIBTEST calling usercontrolmanager.pause"); ScannerCommon.UserControlManager.OnPause(); - Log.Debug("CALIBTEST calling scannercommon2.pause"); + _logger.LogDebug("CALIBTEST calling scannercommon2.pause"); ScannerCommon.OnPause(_dimScanner ? ScannerCommon.PauseDisplayMode.FadeScanner : ScannerCommon.PauseDisplayMode.None); @@ -154,14 +157,14 @@ public virtual void OnResume() { HandleResume(); - Log.Debug("CALIBTEST TalkScanner OnResume. Resuming watchdog"); + _logger.LogDebug("CALIBTEST TalkScanner OnResume. Resuming watchdog"); _dimScanner = true; - Log.Debug("CALIBTEST TalkScanner OnResume. calling user control manager.OnREsume"); + _logger.LogDebug("CALIBTEST TalkScanner OnResume. calling user control manager.OnREsume"); ScannerCommon.UserControlManager.OnResume(); - Log.Debug("CALIBTEST TalkScanner OnResume. calling scannercommon2 resume"); + _logger.LogDebug("CALIBTEST TalkScanner OnResume. calling scannercommon2 resume"); ScannerCommon.OnResume(); ScannerCommon.ResizeToFitDesktop(this); @@ -177,11 +180,11 @@ public virtual void SetTargetControl(Form parent, Widget widget) protected virtual void HandlePause() { - Log.Warn($"No pause handler defined for {GetType().Name}. Defaulting to do nothing."); + _logger.LogWarning($"No pause handler defined for {GetType().Name}. Defaulting to do nothing."); } protected virtual void HandleResume() { - Log.Warn($"No resume handler defined for {GetType().Name}. Defaulting to do nothing."); + _logger.LogWarning($"No resume handler defined for {GetType().Name}. Defaulting to do nothing."); } protected virtual void InitializeComponent() { @@ -245,12 +248,12 @@ protected virtual void SetColorScheme() protected virtual void SubscribeToEvents() { //Default to subscribe to nothing. - Log.Warn($"No event handlers defined for {GetType().Name}"); + _logger.LogWarning($"No event handlers defined for {GetType().Name}"); } protected virtual void updateControlsFromTheme(ColorScheme colorScheme) { - Log.Warn($"Not updating theme for {GetType().Name}"); + _logger.LogWarning($"Not updating theme for {GetType().Name}"); } [EnvironmentPermission(SecurityAction.LinkDemand, Unrestricted = true)] diff --git a/src/Libraries/ACATExtension/UI/ScannerHelper.cs b/src/Libraries/ACATExtension/UI/ScannerHelper.cs index 3011989c..55b5736f 100644 --- a/src/Libraries/ACATExtension/UI/ScannerHelper.cs +++ b/src/Libraries/ACATExtension/UI/ScannerHelper.cs @@ -10,6 +10,7 @@ using ACAT.Core.PanelManagement.Common; using ACAT.Core.PanelManagement.Interfaces; using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Reflection; using System.Windows.Forms; @@ -21,14 +22,16 @@ namespace ACAT.Extension.UI /// public class ScannerHelper { + private readonly ILogger _logger; + /// /// Initializes an instances of the class /// /// the scanner object /// initialization arguments - public ScannerHelper(IScannerPanel panel, StartupArg startupArg) - { - DialogMode = startupArg.DialogMode; + /// Logger instance + public ScannerHelper(IScannerPanel panel, StartupArg startupArg, ILogger logger) + { _logger = logger; DialogMode = startupArg.DialogMode; AppDomain currentDomain = AppDomain.CurrentDomain; currentDomain.AssemblyResolve += currentDomain_AssemblyResolve; @@ -95,7 +98,7 @@ public void OnFormClosing(FormClosingEventArgs e) /// private Assembly currentDomain_AssemblyResolve(object sender, ResolveEventArgs args) { - Log.Debug("ScannerHelper. Assembly resolve raised"); + _logger.LogDebug("ScannerHelper. Assembly resolve raised"); return FileUtils.AssemblyResolve(Assembly.GetExecutingAssembly(), args); } } diff --git a/src/Libraries/ACATExtension/UI/UserControlWordPredictionCommon.cs b/src/Libraries/ACATExtension/UI/UserControlWordPredictionCommon.cs index 746d6944..753c8f12 100644 --- a/src/Libraries/ACATExtension/UI/UserControlWordPredictionCommon.cs +++ b/src/Libraries/ACATExtension/UI/UserControlWordPredictionCommon.cs @@ -12,6 +12,7 @@ using ACAT.Core.Utility; using ACAT.Core.WidgetManagement; using ACAT.Core.Widgets; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; @@ -33,6 +34,8 @@ namespace ACAT.Extension.UI /// public class UserControlWordPredictionCommon : IDisposable { + private readonly ILogger _logger; + /// /// Widget that represents the alphabet scanner /// @@ -73,8 +76,9 @@ public class UserControlWordPredictionCommon : IDisposable /// Constructor. Initialize the various controls and /// display the UI /// - public UserControlWordPredictionCommon(IUserControl userControl, TextController textController, IScannerPanel scannerPanel, PredictionTypes[] predictionTypes) + public UserControlWordPredictionCommon(IUserControl userControl, TextController textController, IScannerPanel scannerPanel, PredictionTypes[] predictionTypes, ILogger logger) { + _logger = logger; _form = scannerPanel.Form; _textController = textController; _predictionTypes = predictionTypes; @@ -137,7 +141,7 @@ public bool Initialize(Widget rootWidget) /// public void OnClosing(object sender, FormClosingEventArgs e) { - Log.Verbose(); + _logger.LogTrace(); } /// @@ -188,7 +192,7 @@ public void OnLoad() /// public void OnPause() { - Log.Verbose(); + _logger.LogTrace(); } /// @@ -197,7 +201,7 @@ public void OnPause() /// public void OnResume() { - Log.Verbose(); + _logger.LogTrace(); refreshWordPredictionsAndSetCurrentWord(); } @@ -281,7 +285,7 @@ protected virtual void Dispose(bool disposing) // Check to see if Dispose has already been called. if (!_disposed) { - Log.Verbose(); + _logger.LogTrace(); if (disposing) { @@ -321,7 +325,7 @@ private void ActiveWordPredictor_EvtWordPredictionAsyncResponse(WordPredictionRe /// event args private void AppAgent_EvtTextChanged(object sender, EventArgs e) { - Log.Verbose(); + _logger.LogTrace(); try { if (_form.Visible) @@ -331,15 +335,15 @@ private void AppAgent_EvtTextChanged(object sender, EventArgs e) } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex, ex.Message); } - Log.Debug("returning"); + _logger.LogDebug("returning"); } private void autoComplete(WordListItemWidget wordListItemWidget) { - Log.Debug("wordListItemName : " + wordListItemWidget.Name + ", value: " + wordListItemWidget.Value); + _logger.LogDebug("wordListItemName : " + wordListItemWidget.Name + ", value: " + wordListItemWidget.Value); var wordSelected = wordListItemWidget.Value.Trim(); @@ -355,7 +359,7 @@ private void autoComplete(WordListItemWidget wordListItemWidget) private void autoComplete(LetterListItemWidget letterListItemWidget) { - Log.Debug("leterListItemName : " + letterListItemWidget.Name + ", value: " + letterListItemWidget.Value); + _logger.LogDebug("leterListItemName : " + letterListItemWidget.Name + ", value: " + letterListItemWidget.Value); var letterSelected = letterListItemWidget.Value.Trim(); @@ -369,7 +373,7 @@ private void autoComplete(LetterListItemWidget letterListItemWidget) private void autoComplete(SentenceListItemWidget sentenceListItemWidget) { - Log.Debug("sentenceListItemName : " + sentenceListItemWidget.Name + ", value: " + sentenceListItemWidget.Value); + _logger.LogDebug("sentenceListItemName : " + sentenceListItemWidget.Name + ", value: " + sentenceListItemWidget.Value); var wordSelected = sentenceListItemWidget.Value.Trim(); @@ -420,7 +424,7 @@ private void KeyStateTracker_EvtKeyStateChanged() } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, ex.Message); } } @@ -456,12 +460,12 @@ private void processSentencePredictionResponse(WordPredictionResponse response) } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex, ex.Message); } } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex, ex.Message); } if (_sentenceListWidget != null) @@ -546,18 +550,11 @@ private void processWordPredictionResponse(WordPredictionResponse response) try { agentContext.TextAgent().GetCharAtCaret(out charAtCaret); - Log.Debug("charAtCaret: [" + charAtCaret + "]"); - } - catch (InvalidAgentContextException ex) - { - Log.Exception(ex.ToString()); - } - } - - if (!string.IsNullOrEmpty(wordAtCaret) && - ResourceHelper.IsCurrentCultureEnglish() && - Context.AppAgentMgr.CurrentEditingMode == EditingMode.Edit && - !wordAtCaret.EndsWith("'s", StringComparison.InvariantCultureIgnoreCase) && + _logger.LogDebug("charAtCaret: [" + charAtCaret + "]"); + } + catch (InvalidAgentContextException ex) + { + _logger.LogError(ex, ex.Message); (charAtCaret == '\0' || charAtCaret == 0x0D || charAtCaret == 0x0A || TextUtils.IsPunctuationOrWhiteSpace(charAtCaret) || TextUtils.IsTerminatorOrWhiteSpace(charAtCaret))) @@ -575,7 +572,7 @@ private void processWordPredictionResponse(WordPredictionResponse response) break; } - Log.Debug("setting Word for " + ii + ": " + word + " "); + _logger.LogDebug("setting Word for " + ii + ": " + word + " "); if (_wordListWidgetWidget.Children.ElementAt(ii) is WordListItemWidget) { _wordListWidgetWidget.Children.ElementAt(ii).SetText(word); @@ -612,7 +609,7 @@ private void processWordPredictionResponse(WordPredictionResponse response) if (_currentWordWidget != null) { - Log.Debug("Calling SetCurrentWord with : [" + wordAtCaret + "]"); + _logger.LogDebug("Calling SetCurrentWord with : [" + wordAtCaret + "]"); _currentWordWidget.SetCurrentWord(wordAtCaret); } // Validation for the character predictions if there any value the proceed to add the element to the childs @@ -625,7 +622,7 @@ private void processWordPredictionResponse(WordPredictionResponse response) { break; } - Log.Debug("setting letter for " + ii + ": " + letter.Trim('\'') + " "); + _logger.LogDebug("setting letter for " + ii + ": " + letter.Trim('\'') + " "); if (_letterListWidgetWidget.Children.ElementAt(ii) is LetterListItemWidget) { string textValue = letter.Trim('\'', ' '); @@ -654,7 +651,7 @@ private void refreshWordPredictionsAndSetCurrentWord() CoreGlobals.Stopwatch3.Stop(); - Log.Debug("TimeElapsed for tryRefreshWordPredictionsAndSetCurrentWord: " + CoreGlobals.Stopwatch3.ElapsedMilliseconds); + _logger.LogDebug("TimeElapsed for tryRefreshWordPredictionsAndSetCurrentWord: " + CoreGlobals.Stopwatch3.ElapsedMilliseconds); } /// @@ -694,12 +691,12 @@ private bool tryRefreshWordPredictionsAndSetCurrentWord() // we need the word at the cursor and also the previous n-words // in the current sentence int caretPos = agentContext.TextAgent().GetCaretPos(); - Log.Debug("Perform WordPrediction at caretPos " + caretPos); + _logger.LogDebug("Perform WordPrediction at caretPos " + caretPos); agentContext.TextAgent().GetPrefixAndWordAtCaret(out nwords, out wordAtCaret); - Log.Debug("wordAtCaret: [" + wordAtCaret + "]"); + _logger.LogDebug("wordAtCaret: [" + wordAtCaret + "]"); agentContext.TextAgent().GetCharAtCaret(out charAtCaret); - Log.Debug("charAtCaret: [" + charAtCaret + "]"); + _logger.LogDebug("charAtCaret: [" + charAtCaret + "]"); } if (string.IsNullOrEmpty(nwords) && string.IsNullOrEmpty(wordAtCaret)) @@ -712,12 +709,12 @@ private bool tryRefreshWordPredictionsAndSetCurrentWord() wordAtCaret = string.Empty; } - Log.Debug("wordatcaret length: " + wordAtCaret.Length); + _logger.LogDebug("wordatcaret length: " + wordAtCaret.Length); //Log.Debug("Text: [" + text + "], caretPos: " + caretPos.ToString()); - Log.Debug("Prefix: [" + nwords + "]"); - Log.Debug("CurrentWord: [" + wordAtCaret + "]"); + _logger.LogDebug("Prefix: [" + nwords + "]"); + _logger.LogDebug("CurrentWord: [" + wordAtCaret + "]"); /* if (_wordListWidgetWidget != null) @@ -782,11 +779,11 @@ private bool tryRefreshWordPredictionsAndSetCurrentWord() } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex, ex.Message); retVal = false; } - Log.Debug("Returning"); + _logger.LogDebug("Returning"); return retVal; } } diff --git a/src/Libraries/ACATExtension/UI/UserControls/GenericUserControl.cs b/src/Libraries/ACATExtension/UI/UserControls/GenericUserControl.cs index 02432716..2cd9eb4a 100644 --- a/src/Libraries/ACATExtension/UI/UserControls/GenericUserControl.cs +++ b/src/Libraries/ACATExtension/UI/UserControls/GenericUserControl.cs @@ -17,6 +17,7 @@ using ACAT.Core.UserControlManagement.Interfaces; using ACAT.Core.Utility; using ACAT.Core.WidgetManagement; +using Microsoft.Extensions.Logging; using System; using System.ComponentModel; using System.Windows.Forms; @@ -26,6 +27,8 @@ namespace ACAT.Extension.UI.UserControls [DesignerCategory("Code")] public abstract class GenericUserControl : UserControl, IUserControl { + protected ILogger _logger; + public event AnimationPlayerStateChanged EvtPlayerStateChanged; /// @@ -73,7 +76,7 @@ public virtual void OnResume() public virtual void OnWidgetActuated(WidgetActuatedEventArgs e, ref bool handled) { - Log.Debug("GenericUserControl onWidgetActuated"); + _logger?.LogDebug("GenericUserControl onWidgetActuated"); handled = false; }