diff --git a/src/Applications/ACATConfigNext/Forms/SettingsForm.cs b/src/Applications/ACATConfigNext/Forms/SettingsForm.cs index fc33658f..aa1c271e 100644 --- a/src/Applications/ACATConfigNext/Forms/SettingsForm.cs +++ b/src/Applications/ACATConfigNext/Forms/SettingsForm.cs @@ -159,7 +159,7 @@ private void ButtonClicked_Save(object sender, EventArgs e) } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, "Error occurred while saving settings"); MessageBox.Show("An error occurred while saving settings.", "Save Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } diff --git a/src/Extensions/ACAT.Extensions.Onboarding/Onboarding/OnboardingLanguageSelect.cs b/src/Extensions/ACAT.Extensions.Onboarding/Onboarding/OnboardingLanguageSelect.cs index 030ede7e..9e28a146 100644 --- a/src/Extensions/ACAT.Extensions.Onboarding/Onboarding/OnboardingLanguageSelect.cs +++ b/src/Extensions/ACAT.Extensions.Onboarding/Onboarding/OnboardingLanguageSelect.cs @@ -9,6 +9,7 @@ using ACAT.Extensions.Onboarding.UI.UserControls; using ACAT.Extensions.Onboarding.UI; using ACAT.Core.CoreInterfaces; +using Microsoft.Extensions.Logging; using System.Globalization; namespace ACAT.Extensions.Onboarding.Onboarding @@ -25,8 +26,14 @@ public class OnboardingLanguageSelect : OnboardingExtensionBase // TODO - Localize Me private const string Step1 = "STEP 1"; + private readonly ILogger _logger; private IOnboardingWizard _wizard; + public OnboardingLanguageSelect() + { + _logger = LoggingConfiguration.CreateLogger(); + } + public override ClassDescriptorAttribute Descriptor { get { return ClassDescriptorAttribute.GetDescriptor(GetType()); } @@ -85,7 +92,7 @@ public override void OnEndStep(IOnboardingUserControl userControl, Reason reason { case Step1: var cultureInfo = userControlLang.currentCulture; - Log.Debug ("User selected language: " + cultureInfo.DisplayName); + _logger.LogDebug("User selected language: {LanguageName}", cultureInfo.DisplayName); CoreGlobals.AppPreferences.Language = cultureInfo.TwoLetterISOLanguageName; CoreGlobals.AppPreferences.Save(); diff --git a/src/Extensions/ACAT.Extensions.Onboarding/UI/UserControls/UserControlHardwareSwitchSetup.cs b/src/Extensions/ACAT.Extensions.Onboarding/UI/UserControls/UserControlHardwareSwitchSetup.cs index 9608c041..ba664330 100644 --- a/src/Extensions/ACAT.Extensions.Onboarding/UI/UserControls/UserControlHardwareSwitchSetup.cs +++ b/src/Extensions/ACAT.Extensions.Onboarding/UI/UserControls/UserControlHardwareSwitchSetup.cs @@ -481,7 +481,7 @@ private void UserControlHardwareSwitchSetup_Load(object sender, EventArgs e) } String html = String.Format(_htmlTemplate, headStyle, bodyStyle, textStyle, "Click here for help"); - Log.Debug(html); + _logger.LogDebug("Generated HTML: {Html}", html); webBrowser.DocumentText = html; //webBrowser.DocumentText = diff --git a/src/Extensions/ACAT.Extensions.Onboarding/UI/UserControls/UserControlHardwareSwitchTest.cs b/src/Extensions/ACAT.Extensions.Onboarding/UI/UserControls/UserControlHardwareSwitchTest.cs index 72046ee3..23a0a191 100644 --- a/src/Extensions/ACAT.Extensions.Onboarding/UI/UserControls/UserControlHardwareSwitchTest.cs +++ b/src/Extensions/ACAT.Extensions.Onboarding/UI/UserControls/UserControlHardwareSwitchTest.cs @@ -334,7 +334,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/ACAT.Extensions.UI/UserControls/Toolbars/LargeToolbarUserControl.cs b/src/Extensions/ACAT.Extensions.UI/UserControls/Toolbars/LargeToolbarUserControl.cs index 6379b534..20a40f2e 100644 --- a/src/Extensions/ACAT.Extensions.UI/UserControls/Toolbars/LargeToolbarUserControl.cs +++ b/src/Extensions/ACAT.Extensions.UI/UserControls/Toolbars/LargeToolbarUserControl.cs @@ -1,6 +1,7 @@ using ACAT.Core.Utility; using ACAT.Core.WidgetManagement; using ACAT.Extension.UI.UserControls; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.ComponentModel; @@ -13,6 +14,7 @@ namespace ACAT.Extensions.UI.UserControls.Toolbars [DesignerCategory("code")] public abstract class LargeToolbarUserControl : KeyboardUserControl { + private readonly ILogger _logger; private readonly TableLayoutPanel ToolbarBox = new() { Name = "ToolbarBox", @@ -55,6 +57,7 @@ protected class ButtonSpec } public LargeToolbarUserControl(string name) { + _logger = LoggingConfiguration.CreateLogger(); Name = name; InitializeButtonsList(); InitializeComponent(); @@ -154,7 +157,7 @@ protected virtual void InitializeComponent() protected override void OnPaint(PaintEventArgs e) { - Log.Debug($"{e.Graphics.DpiX} x {e.Graphics.DpiY}"); + _logger.LogDebug("{DpiX} x {DpiY}", e.Graphics.DpiX, e.Graphics.DpiY); e.Graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit; base.OnPaint(e); diff --git a/src/Extensions/ACAT.Extensions.UI/UserControls/Toolbars/LaunchAppUserControl.cs b/src/Extensions/ACAT.Extensions.UI/UserControls/Toolbars/LaunchAppUserControl.cs index 561412f9..3c2e72cd 100644 --- a/src/Extensions/ACAT.Extensions.UI/UserControls/Toolbars/LaunchAppUserControl.cs +++ b/src/Extensions/ACAT.Extensions.UI/UserControls/Toolbars/LaunchAppUserControl.cs @@ -1,6 +1,7 @@ using ACAT.Core.PanelManagement; using ACAT.Core.Utility; using ACAT.Core.WidgetManagement; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.ComponentModel; @@ -14,6 +15,8 @@ namespace ACAT.Extensions.UI.UserControls.Toolbars [DesignerCategory("code")] public class LaunchAppUserControl : LargeToolbarUserControl { + private static readonly ILogger _logger = LoggingConfiguration.CreateLogger(); + private class LaunchButtonSpec : ButtonSpec { public AppInfo AppInfo { get; set; } @@ -51,7 +54,7 @@ public LaunchAppUserControl() : base("LaunchAppUserControl") public override void OnButtonClicked(object s, EventArgs e) { string buttonName = e.ToString(); - Log.Info($"Button clicked: {buttonName}"); + _logger.LogInformation("Button clicked: {ButtonName}", buttonName); var dict = Buttons.ToDictionary(x => x.Name); diff --git a/src/Extensions/BCI/ACAT.Extensions.BCI.UI/Scanners/TalkApplicationBCIScanner.cs b/src/Extensions/BCI/ACAT.Extensions.BCI.UI/Scanners/TalkApplicationBCIScanner.cs index 4913dfa5..2b8267f8 100644 --- a/src/Extensions/BCI/ACAT.Extensions.BCI.UI/Scanners/TalkApplicationBCIScanner.cs +++ b/src/Extensions/BCI/ACAT.Extensions.BCI.UI/Scanners/TalkApplicationBCIScanner.cs @@ -34,6 +34,7 @@ using ACAT.Extensions.BCI.Common.BCIInterfaceUtilities; using ACAT.Extensions.BCI.UI.UserControls; using ACATResources; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; @@ -65,6 +66,11 @@ public partial class TalkApplicationBCIScanner : Form, IScannerPanel, ISupportsS /// private readonly Dispatcher _dispatcher; + /// + /// Logger instance for this class + /// + private readonly ILogger _logger; + /// /// The AlphabetScannerCommon object. Has a number of /// helper functions @@ -187,8 +193,9 @@ public partial class TalkApplicationBCIScanner : Form, IScannerPanel, ISupportsS /// /// Initializes a new instance of the class. /// - public TalkApplicationBCIScanner() + public TalkApplicationBCIScanner(ILogger logger = null) { + _logger = logger; _scannerCommon = new ScannerCommon(this); InitializeComponent(); this.DoubleBuffered = true; @@ -737,7 +744,7 @@ private void BciActuator_EvtIoctlResponse(int opcode, object response) { if (!_RequestCalibration)//have a delay before start typing so the user can see the options and suggestions and start looking where is desired { - Log.Debug("BCI LOG | Delay before Typing ");//Run the delay in another therad to avoid blocking the UI + _logger?.LogDebug("BCI LOG | Delay before Typing ");//Run the delay in another therad to avoid blocking the UI _ = ShowTimedMessageBoxAsync().ConfigureAwait(false); } else @@ -752,14 +759,14 @@ private void BciActuator_EvtIoctlResponse(int opcode, object response) if (_BCIState == BCIState.BCIStartSession) { _BCIState = BCIState.BCIInitDone; - Log.Debug("BCI LOG | BCI Init state: " + BCIState.BCIInitDone); + _logger?.LogDebug("BCI LOG | BCI Init state: {State}", BCIState.BCIInitDone); } break; case (int)OpCodes.SendCalibrationStatus: //STEP - 1 var bciCalibrationStatus = response as BCICalibrationStatus; - Log.Debug("BCI LOG | bciCalibrationStatus.OkToGoToTyping: " + bciCalibrationStatus.OkToGoToTyping); + _logger?.LogDebug("BCI LOG | bciCalibrationStatus.OkToGoToTyping: {OkToGoToTyping}", bciCalibrationStatus.OkToGoToTyping); if (_ShowMainOptions)//This window should only display once { _ShowMainOptions = false; @@ -988,7 +995,7 @@ private void BCIShowRecalibrationWindowMessage() } catch (Exception es) { - Log.Exception("BCI LOG | " + es.Message.ToString()); + _logger?.LogError("BCI LOG | {Message}", es.Message.ToString()); } } @@ -1006,32 +1013,32 @@ private void BCIUpdateBCI(BCIState bCIState) break; case BCIState.UIRefresh://1 Init state - Log.Debug("BCI LOG | BCI Init state: " + BCIState.UIRefresh); + _logger?.LogDebug("BCI LOG | BCI Init state: {State}", BCIState.UIRefresh); _BCIState = BCIState.UIRefresh; _ = ControlsUIAdjustment().ConfigureAwait(false); break; case BCIState.Initializing://2 Init state - Log.Debug("BCI LOG | BCI Init state: " + BCIState.Initializing); + _logger?.LogDebug("BCI LOG | BCI Init state: {State}", BCIState.Initializing); _BCIState = BCIState.Initializing; _ = InitializeBCI().ConfigureAwait(false); break; case BCIState.ReqCalibrationStatus://3 Init state _BCIState = BCIState.ReqCalibrationStatus; - Log.Debug("BCI LOG | BCI Init state: " + BCIState.ReqCalibrationStatus); + _logger?.LogDebug("BCI LOG | BCI Init state: {State}", BCIState.ReqCalibrationStatus); _ = BCIRequestCalibrationStatus().ConfigureAwait(false); break; case BCIState.StartBCIReqParams://4 Init state //STEP - 4 - Log.Debug("BCI LOG | BCI Init state: " + BCIState.StartBCIReqParams); + _logger?.LogDebug("BCI LOG | BCI Init state: {State}", BCIState.StartBCIReqParams); _BCIState = BCIState.StartBCIReqParams; _ = BCIStartBCIReqParams().ConfigureAwait(false); break; case BCIState.BCIStartSession://5 Init state - Log.Debug("BCI LOG | BCI Init state: " + BCIState.BCIStartSession); + _logger?.LogDebug("BCI LOG | BCI Init state: {State}", BCIState.BCIStartSession); _BCIState = BCIState.BCIStartSession; _ = BCIStartSession().ConfigureAwait(false); break; @@ -1039,7 +1046,7 @@ private void BCIUpdateBCI(BCIState bCIState) } catch (Exception ex) { - Log.Exception("BCI LOG | Error in BCI Init state: " + bCIState + " Messagge: " + ex.Message); + _logger?.LogError("BCI LOG | Error in BCI Init state: {State} Message: {Message}", bCIState, ex.Message); } } @@ -1129,7 +1136,7 @@ private void ExitApplication() } catch (Exception e) { - Log.Exception("BCI LOG | Error in ExitApplication() BCI: " + e.Message); + _logger?.LogError("BCI LOG | Error in ExitApplication() BCI: {Message}", e.Message); } } @@ -1250,8 +1257,8 @@ private void LearnCannedPhrases(string textToLearn) private void LogAssemblyVersion() { var version = ACATPreferences.ApplicationAssembly.GetName().Version.Major + "." + ACATPreferences.ApplicationAssembly.GetName().Version.Minor; - Log.Debug("BCI LOG | ACAT - Assembly version info"); - Log.Debug("BCI LOG | AssemblyVersion: " + version); + _logger?.LogDebug("BCI LOG | ACAT - Assembly version info"); + _logger?.LogDebug("BCI LOG | AssemblyVersion: {Version}", version); } /// @@ -1348,7 +1355,7 @@ private void SetCaretPositionForTextBoxUC(UserControl userControl, Control panel if (BCIInterfaceUtils.GetCaretPositionOfTextBoxUC() != currentCaretPosition) { Windows.SetCaretPosition(_textBoxTalkWindow, BCIInterfaceUtils.GetCaretPositionOfTextBoxUC()); - Log.Debug("BCI LOG | Caret position reestablish | Textbox user control changed"); + _logger?.LogDebug("BCI LOG | Caret position reestablish | Textbox user control changed"); } } } @@ -1359,14 +1366,14 @@ private void SetCaretPositionForTextBoxUC(UserControl userControl, Control panel if (BCIInterfaceUtils.GetCaretPhrasePositionOfTextBoxUC() != currentCaretPosition) { Windows.SetCaretPosition(_textBoxTalkWindow, BCIInterfaceUtils.GetCaretPhrasePositionOfTextBoxUC()); - Log.Debug("BCI LOG | Caret position reestablish | Textbox user control changed"); + _logger?.LogDebug("BCI LOG | Caret position reestablish | Textbox user control changed"); } } } } catch (Exception ex) { - Log.Debug("BCI LOG | Error | SetCaretPositionForTextBoxUC: " + ex.Message); + _logger?.LogDebug("BCI LOG | Error | SetCaretPositionForTextBoxUC: {Message}", ex.Message); } } @@ -1540,7 +1547,7 @@ private void TextBoxTalkWindowOnKeyPress(object sender, KeyPressEventArgs keyPre } catch (Exception ex) { - Log.Exception(ex); + _logger?.LogError(ex, ex.Message); } } @@ -1552,9 +1559,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)); } @@ -1660,7 +1667,7 @@ public override bool Execute(ref bool handled) { handled = true; List[] widgets; - Log.Debug("BCI LOG | Command | selected | Pressed | " + Command.ToString()); + _logger?.LogDebug("BCI LOG | Command | selected | Pressed | {Command}", Command.ToString()); switch (Command) { case "CmdEditScanner": @@ -1871,7 +1878,7 @@ public override bool Execute(ref bool handled) } } else - Log.Debug("BCI LOG | Command | selected | Pressed in calibration | No action | " + Command.ToString()); + _logger?.LogDebug("BCI LOG | Command | selected | Pressed in calibration | No action | {Command}", Command.ToString()); return true; } } diff --git a/src/Extensions/BCI/Actuators/BCIActuator/BCIActuator.cs b/src/Extensions/BCI/Actuators/BCIActuator/BCIActuator.cs index dea1f592..34046456 100644 --- a/src/Extensions/BCI/Actuators/BCIActuator/BCIActuator.cs +++ b/src/Extensions/BCI/Actuators/BCIActuator/BCIActuator.cs @@ -1,4 +1,4 @@ -//////////////////////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////////////////// // // Copyright 2013-2019; 2023 Intel Corporation // SPDX-License-Identifier: Apache-2.0 @@ -29,6 +29,7 @@ using ACAT.Extensions.BCI.Actuators.openBCISensorUI; using ACAT.Extensions.BCI.Common.BCIControl; using ACATResources; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.IO; @@ -45,6 +46,8 @@ namespace ACAT.Extensions.BCI.Actuators.BCIActuator "BCI Actuator")] internal class BCIActuator : ActuatorBase, ISupportsPreferences { + private readonly ILogger _logger; + /// /// The setting object for the box calibration /// @@ -214,6 +217,7 @@ internal class BCIActuator : ActuatorBase, ISupportsPreferences /// public BCIActuator() { + _logger = LoggingConfiguration.CreateLogger(); try { // Load settings @@ -249,7 +253,7 @@ public BCIActuator() } catch (Exception e) { - Log.Exception(e.Message); + _logger.LogError(e, "Failed to initialize BCIActuator"); } } @@ -273,7 +277,7 @@ private bool AreChannelsEqual(bool[] currentChannels, int[] classifierChannels) } catch (Exception e) { - Log.Exception("Exception: " + e.Message); + _logger.LogError(e, "Failed to compare channels"); } return equalChannels; } @@ -290,7 +294,7 @@ private Dictionary GetAvailableClassifiers() //If recheck needed, all classifiers need to be recalibrated if (BCISettingsFixed.SignalControl_RecheckNeeded) { - Log.Debug("Signal recheck needed.No available classifiers"); + _logger.LogDebug("Signal recheck needed.No available classifiers"); return availableClassifiers; } @@ -323,7 +327,7 @@ private Dictionary GetAvailableClassifiers() // NOTE: Status set to Expired, in a future release a new status should be created for this condition if (!AreChannelsEqual(currentChannels, tmpDecisionMaker.TrainedClassifiersObj.channelSubset)) { - Log.Debug("Classifier: " + scanSection + " - Different channels than calibration. Current channels will be used in calibration."); + _logger.LogDebug("Classifier: " + scanSection + " - Different channels than calibration. Current channels will be used in calibration."); classifierStatus = BCIClassifierStatus.Mismatch; } // Check if classifier expired @@ -338,14 +342,14 @@ private Dictionary GetAvailableClassifiers() // Add classifier to dictionary BCIClassifierInfo classifierInfo = new(isRequired, scanSection, classifierStatus, auc); availableClassifiers.Add(scanSection, classifierInfo); - Log.Debug("Classifier: " + scanSection + " found | AUC:" + availableClassifiers[scanSection].Auc + " isRequired:" + isRequired + " Status:" + classifierStatus); + _logger.LogDebug("Classifier: " + scanSection + " found | AUC:" + availableClassifiers[scanSection].Auc + " isRequired:" + isRequired + " Status:" + classifierStatus); } } } } catch (Exception e) { - Log.Exception(e.Message); + _logger.LogError(e, "Failed to get available classifiers"); } return availableClassifiers; } @@ -370,11 +374,11 @@ private void LoadTypingMappings() }; foreach (KeyValuePair mapping in DictTypingCalibrationMappings) - Log.Debug("Typing section:" + mapping.Key + " Using classifier:" + mapping.Value); + _logger.LogDebug("Typing section:" + mapping.Key + " Using classifier:" + mapping.Value); } catch (Exception e) { - Log.Exception(e.Message); + _logger.LogError(e, "Failed to load typing mappings"); } } @@ -416,7 +420,7 @@ private bool LoadClassifiers() if (File.Exists(classifierFilePath)) { - Log.Debug("Section: " + typingMapping.Key + " | Loading classifier:" + typingMapping.Value + " from:" + classifierFilePath); + _logger.LogDebug("Section: " + typingMapping.Key + " | Loading classifier:" + typingMapping.Value + " from:" + classifierFilePath); DecisionMaker tmpDecisionMaker = new(classifierFilePath); if (tmpDecisionMaker != null && tmpDecisionMaker.TrainedClassifiersObj != null) @@ -430,7 +434,7 @@ private bool LoadClassifiers() { EEGProcessingGlobals.DecisionMakerDict.Add(typingMapping.Key, tmpDecisionMaker); - Log.Debug(typingMapping.Key.ToString() + " typing section - Using " + typingMapping.Value.ToString() + " classifier. Status: loaded"); + _logger.LogDebug(typingMapping.Key.ToString() + " typing section - Using " + typingMapping.Value.ToString() + " classifier. Status: loaded"); var bciLogEntry = new BCILogEntryClassifierLoaded() { @@ -451,19 +455,19 @@ private bool LoadClassifiers() else { missingClassifier = true; - Log.Warn(typingMapping.Key.ToString() + " typing section - Using " + typingMapping.Value.ToString() + " classifier. Status: missing!!"); + _logger.LogWarning(typingMapping.Key.ToString() + " typing section - Using " + typingMapping.Value.ToString() + " classifier. Status: missing!!"); } } else { missingClassifier = true; - Log.Warn(typingMapping.Key.ToString() + " typing section. Classifier file not found. - Using " + typingMapping.Value.ToString() + " classifier. Status: missing!!"); + _logger.LogWarning(typingMapping.Key.ToString() + " typing section. Classifier file not found. - Using " + typingMapping.Value.ToString() + " classifier. Status: missing!!"); } } } catch (Exception e) { - Log.Exception(e.Message); + _logger.LogError(e, "Failed to load classifiers"); return false; } return !missingClassifier; @@ -556,12 +560,12 @@ public override bool PostInit() if (_daqInstance.GetType() == typeof(DAQ_gTecBCI)) { - Log.Debug("startgTecUnicornTesting"); + _logger.LogDebug("startgTecUnicornTesting"); TestGtecDevice(); } else { - Log.Debug("startOpenBCITesting"); + _logger.LogDebug("startOpenBCITesting"); TestBCIDevices(); } @@ -584,7 +588,7 @@ public override bool IoctlRequest(int opcode, object request) { bool retVal = false; - Log.Debug("IoctRequest received: " + (OpCodes)opcode + " | Request: " + request); + _logger.LogDebug("IoctRequest received: " + (OpCodes)opcode + " | Request: " + request); switch (opcode) { @@ -716,7 +720,7 @@ protected override void Dispose(bool disposing) { try { - Log.Verbose(); + _logger.LogTrace("Disposing BCIActuator resources"); if (disposing) { @@ -754,10 +758,10 @@ private void bciDeviceTestingCompleted() actuatorState = (GTecDeviceTester.ExitOnboardingEarly) ? State.Stopped : State.Running; } - Log.Debug("\nbciDeviceTestingCompleted | actuatorState: " + actuatorState.ToString()); + _logger.LogDebug("\nbciDeviceTestingCompleted | actuatorState: " + actuatorState.ToString()); SendIoctlResponse((int)OpCodes.CalibrationWindowClose, String.Empty); - Log.Debug("IoctRequest " + OpCodes.CalibrationWindowClose + " sent. Message: empty"); + _logger.LogDebug("IoctRequest " + OpCodes.CalibrationWindowClose + " sent. Message: empty"); } /// @@ -788,13 +792,13 @@ private IActuatorSwitch find(String switchSource) /// private void OnTriggerTestRequestParameters(object request) { - Log.Debug("TriggerTest parameters requested"); + _logger.LogDebug("TriggerTest parameters requested"); // Send parameters to ACAT var bciTriggerTestParameters = new BCITriggerTestParameters(BCIActuatorSettings.Settings.TriggerTest_NumRepetitions, BCIActuatorSettings.Settings.TriggerTest_ScanTime); - Log.Debug(" Sending parameters. Scan time: " + bciTriggerTestParameters.ScanTime + " | Num repetitions: " + bciTriggerTestParameters.NumRepetitions); + _logger.LogDebug(" Sending parameters. Scan time: " + bciTriggerTestParameters.ScanTime + " | Num repetitions: " + bciTriggerTestParameters.NumRepetitions); SendIoctlResponse((int)OpCodes.TriggerTestSendParameters, bciTriggerTestParameters); - Log.Debug("IoctRequest " + OpCodes.TriggerTestSendParameters + " sent. Message: empty"); + _logger.LogDebug("IoctRequest " + OpCodes.TriggerTestSendParameters + " sent. Message: empty"); } /// @@ -803,7 +807,7 @@ private void OnTriggerTestRequestParameters(object request) /// private void OnRequestCalibrationStatus(object request) { - Log.Debug("Request Calibration Status received"); + _logger.LogDebug("Request Calibration Status received"); BCIError error; BCIClassifierStatus overallStatus = BCIClassifierStatus.NotFound; @@ -840,7 +844,7 @@ private void OnRequestCalibrationStatus(object request) // Add classifier to dictionary DictClassifierInfo.Add(calibrationSection, classifierInfo); - Log.Warn("Calibration:" + calibrationSection + " isRequired:" + classifierInfo.IsRequired + " Status:" + classifierInfo.ClassifierStatus.ToString() + " Auc:" + classifierInfo.Auc); + _logger.LogDebug("Calibration:" + calibrationSection + " isRequired:" + classifierInfo.IsRequired + " Status:" + classifierInfo.ClassifierStatus.ToString() + " Auc:" + classifierInfo.Auc); // Set overall status if (classifierInfo.IsRequired && classifierInfo.ClassifierStatus != BCIClassifierStatus.Ok) @@ -863,7 +867,7 @@ private void OnRequestCalibrationStatus(object request) showOnlyDefaults = false; } - Log.Debug("Additional classifier:" + calibrationSection + "Set showOnlyDefaults to:" + showOnlyDefaults); + _logger.LogDebug("Additional classifier:" + calibrationSection + "Set showOnlyDefaults to:" + showOnlyDefaults); } } error = new BCIError(BCIErrorCodes.Status_Ok, BCIMessages.Status_Ok); @@ -871,7 +875,7 @@ private void OnRequestCalibrationStatus(object request) catch (Exception e) { error = new BCIError(BCIErrorCodes.CalibrationError_LoadingClassifiers, StringResources.ClassifiersNotLoadedError); - Log.Exception("Error " + BCIErrorCodes.CalibrationError_LoadingClassifiers.ToString() + " " + "Excepction: " + e.Message); + _logger.LogError(e, "Error " + BCIErrorCodes.CalibrationError_LoadingClassifiers.ToString()); } // Set oKToGoToTyping status @@ -879,9 +883,9 @@ private void OnRequestCalibrationStatus(object request) // Send parameters to ACAT var bciCalibrationStatus = new BCICalibrationStatus(showOnlyDefaults, areMoreClassifiersThanMapping, okToGoToTyping, overallStatus, DictClassifierInfo, error); - Log.Debug("Sending Calibration Status. ShowOnlyDefaults:" + showOnlyDefaults + " | areMoreClassifiersThanMappings:" + areMoreClassifiersThanMapping + " | okToGoToTyping:" + okToGoToTyping + " | OverallStatus:" + overallStatus.ToString()); + _logger.LogDebug("Sending Calibration Status. ShowOnlyDefaults:" + showOnlyDefaults + " | areMoreClassifiersThanMappings:" + areMoreClassifiersThanMapping + " | okToGoToTyping:" + okToGoToTyping + " | OverallStatus:" + overallStatus.ToString()); SendIoctlResponse((int)OpCodes.SendCalibrationStatus, bciCalibrationStatus); - Log.Debug("IoctRequest: " + OpCodes.SendCalibrationStatus + " sent. Message: " + bciCalibrationStatus.ToString()); + _logger.LogDebug("IoctRequest: " + OpCodes.SendCalibrationStatus + " sent. Message: " + bciCalibrationStatus.ToString()); } /// @@ -890,7 +894,7 @@ private void OnRequestCalibrationStatus(object request) /// private void OnRequestMapOptions(object request) { - Log.Debug("Request Map options received"); + _logger.LogDebug("Request Map options received"); BCIError error; @@ -946,10 +950,10 @@ private void OnRequestMapOptions(object request) if (availableClassifiers.ContainsKey(availableClassifierForSection) && availableClassifiers[availableClassifierForSection].ClassifierStatus == BCIClassifierStatus.Ok) { availableClassifiersForSection.Add(availableClassifiers[availableClassifierForSection]); - Log.Debug("Section:" + typingSection + " Available classifier:" + availableClassifierForSection + " Auc:" + availableClassifiers[availableClassifierForSection].Auc); + _logger.LogDebug("Section:" + typingSection + " Available classifier:" + availableClassifierForSection + " Auc:" + availableClassifiers[availableClassifierForSection].Auc); } else - Log.Debug("Section:" + typingSection + " Classsifier:" + DictAllowedMappings[typingSection] + " is not available"); + _logger.LogDebug("Section:" + typingSection + " Classsifier:" + DictAllowedMappings[typingSection] + " is not available"); } // Add classifier found in dictionary DictClassifierInfoForAvailableMappings.Add(typingSection, availableClassifiersForSection); @@ -959,14 +963,14 @@ private void OnRequestMapOptions(object request) catch (Exception e) { error = new BCIError(BCIErrorCodes.CalibrationError_LoadingClassifiers, StringResources.ClassifiersNotLoadedError); - Log.Exception("Error " + BCIErrorCodes.CalibrationError_LoadingClassifiers.ToString() + " " + "Excepction: " + e.Message); + _logger.LogError(e, "Error " + BCIErrorCodes.CalibrationError_LoadingClassifiers.ToString()); } // Send response to ACAT var bciMapOptions = new BCIMapOptions(BCIActuatorSettings.Settings.Calibration_UseAdvanceModeForTypingMappings, DictClassifierInfoForAvailableMappings, DictTypingCalibrationMappings, error); - Log.Debug("Sending map options. Is advanced: " + bciMapOptions.IsAdvanced + " | error: " + (BCIErrorCodes)error.ErrorCode); + _logger.LogDebug("Sending map options. Is advanced: " + bciMapOptions.IsAdvanced + " | error: " + (BCIErrorCodes)error.ErrorCode); SendIoctlResponse((int)OpCodes.SendMapOptions, bciMapOptions); - Log.Debug("IoctRequest " + OpCodes.SendMapOptions + " sent. Message: " + bciMapOptions.ToString()); + _logger.LogDebug("IoctRequest " + OpCodes.SendMapOptions + " sent. Message: " + bciMapOptions.ToString()); } /// @@ -975,7 +979,7 @@ private void OnRequestMapOptions(object request) /// private void OnSendUpdatedMappings(object request) { - Log.Debug("Send Updated mappings called"); + _logger.LogDebug("Send Updated mappings called"); try { var bciUpdatedMappings = request as BCICalibrationUpdatedMappings; @@ -1008,21 +1012,21 @@ private void OnSendUpdatedMappings(object request) TypingCalibrationMappings.KeyboardRCalibrationMapping = mappingForTypingSection.Value.ToString(); break; } - Log.Debug("Typing section:" + mappingForTypingSection.Key.ToString() + " Classifier used:" + mappingForTypingSection.Value.ToString()); + _logger.LogDebug("Typing section:" + mappingForTypingSection.Key.ToString() + " Classifier used:" + mappingForTypingSection.Value.ToString()); } // Save settings TypingCalibrationMappings.Save(); - Log.Debug("Settings updated and saved"); + _logger.LogDebug("Settings updated and saved"); // Reload classifiers LoadClassifiers(); - Log.Debug("Classifiers re-loaded"); + _logger.LogDebug("Classifiers re-loaded"); } } catch (Exception e) { - Log.Exception(e.Message); + _logger.LogError(e, "Failed to send updated mappings"); } } @@ -1032,7 +1036,7 @@ private void OnSendUpdatedMappings(object request) /// private void OnTriggerTestSaveParameters(object request) { - Log.Debug("Received OnTriggerTestSaveParameters"); + _logger.LogDebug("Received OnTriggerTestSaveParameters"); // Receive parameters from ACAT var bciTriggerTestParameters = request as BCITriggerTestParameters; @@ -1042,7 +1046,7 @@ private void OnTriggerTestSaveParameters(object request) BCIActuatorSettings.Settings.TriggerTest_ScanTime = bciTriggerTestParameters.ScanTime; BCIActuatorSettings.Settings.Save(); - Log.Debug("Eyes closed parameters (Scan time: " + BCIActuatorSettings.Settings.TriggerTest_ScanTime + " , num repetitions: " + BCIActuatorSettings.Settings.TriggerTest_NumRepetitions + ") received from ACAT and saved to BCISettings file"); + _logger.LogDebug("Eyes closed parameters (Scan time: " + BCIActuatorSettings.Settings.TriggerTest_ScanTime + " , num repetitions: " + BCIActuatorSettings.Settings.TriggerTest_NumRepetitions + ") received from ACAT and saved to BCISettings file"); } /// @@ -1051,15 +1055,15 @@ private void OnTriggerTestSaveParameters(object request) /// private void OnTriggerTestStart(object request) { - Log.Debug("Trigger test start"); + _logger.LogDebug("Trigger test start"); if (_daqInstance.GetType() == typeof(DAQ_OpenBCI)) { _ = ((DAQ_OpenBCI)_daqInstance).TriggerTestStart(); } - Log.Debug("Trigger test started"); + _logger.LogDebug("Trigger test started"); SendIoctlResponse((int)OpCodes.TriggerTestStartReady, null); - Log.Debug("IoctRequest " + OpCodes.TriggerTestStartReady + " sent. Message:null "); + _logger.LogDebug("IoctRequest " + OpCodes.TriggerTestStartReady + " sent. Message:null "); } /// @@ -1068,7 +1072,7 @@ private void OnTriggerTestStart(object request) /// private void OnTriggerTestStop(object request) { - Log.Debug("Trigger test stop"); + _logger.LogDebug("Trigger test stop"); BaseDAQ.ExitCodes exitCode = ((DAQ_OpenBCI)_daqInstance).TriggerTestStop(BCIActuatorSettings.Settings.TriggerTest_NumRepetitions, out _, out List dutyCycleList, out double dutyCycleAvg); bool triggerTestSuccesful = false; @@ -1077,9 +1081,9 @@ private void OnTriggerTestStop(object request) // Send parameters to ACAT var bciTriggerTest = new BCITriggerTestResult(triggerTestSuccesful, dutyCycleList, dutyCycleAvg); - Log.Debug("Sending trigger test results. TriggerTestSuccesful: " + triggerTestSuccesful + " | dutyCycleAvg: " + dutyCycleAvg + " | dutyCycle for individual pulses: " + dutyCycleList.ToArray().ToString()); + _logger.LogDebug("Sending trigger test results. TriggerTestSuccesful: " + triggerTestSuccesful + " | dutyCycleAvg: " + dutyCycleAvg + " | dutyCycle for individual pulses: " + dutyCycleList.ToArray().ToString()); SendIoctlResponse((int)OpCodes.TriggerTestResult, bciTriggerTest); - Log.Debug("IoctRequest " + OpCodes.TriggerTestResult + " sent. Message: " + bciTriggerTest.ToString()); + _logger.LogDebug("IoctRequest " + OpCodes.TriggerTestResult + " sent. Message: " + bciTriggerTest.ToString()); } /// @@ -1088,12 +1092,12 @@ private void OnTriggerTestStop(object request) /// private void OnCalibrationEyesClosedRequestParameters(object request) { - Log.Debug("Requesting calibration for eyes close parameters"); + _logger.LogDebug("Requesting calibration for eyes close parameters"); // Send parameters to ACAT var bciCalibrationEyesClosedParameters = new BCICalibrationEyesClosedParameters(BCIActuatorSettings.Settings.EyesClosedCalibration_NumRepetitions, BCIActuatorSettings.Settings.EyesClosedCalibration_IntervalDuration); - Log.Debug("Sending eyes close parameters. Num repetitions: " + bciCalibrationEyesClosedParameters.NumRepetitions + " | Interval duration: " + bciCalibrationEyesClosedParameters.IntervalDuration); + _logger.LogDebug("Sending eyes close parameters. Num repetitions: " + bciCalibrationEyesClosedParameters.NumRepetitions + " | Interval duration: " + bciCalibrationEyesClosedParameters.IntervalDuration); SendIoctlResponse((int)OpCodes.CalibrationEyesClosedSendParameters, bciCalibrationEyesClosedParameters); - Log.Debug("IoctRequest " + OpCodes.CalibrationEyesClosedSendParameters + " sent. Message: " + bciCalibrationEyesClosedParameters.ToString()); + _logger.LogDebug("IoctRequest " + OpCodes.CalibrationEyesClosedSendParameters + " sent. Message: " + bciCalibrationEyesClosedParameters.ToString()); } /// @@ -1102,7 +1106,7 @@ private void OnCalibrationEyesClosedRequestParameters(object request) /// private void OnCalibrationEyesClosedSaveParameters(object request) { - Log.Debug("Calibration eyes closed save parameters called"); + _logger.LogDebug("Calibration eyes closed save parameters called"); // Receive parameters from ACAT var bciCalibrationEyesClosedParameters = request as BCICalibrationEyesClosedParameters; @@ -1112,7 +1116,7 @@ private void OnCalibrationEyesClosedSaveParameters(object request) BCIActuatorSettings.Settings.EyesClosedCalibration_NumRepetitions = bciCalibrationEyesClosedParameters.NumRepetitions; BCIActuatorSettings.Settings.Save(); - Log.Debug("Eyes closed parameters (Interval duration: " + BCIActuatorSettings.Settings.EyesClosedCalibration_IntervalDuration + " , num repetitions: " + BCIActuatorSettings.Settings.EyesClosedCalibration_NumRepetitions + ") received from ACAT and saved to BCISettings file"); + _logger.LogDebug("Eyes closed parameters (Interval duration: " + BCIActuatorSettings.Settings.EyesClosedCalibration_IntervalDuration + " , num repetitions: " + BCIActuatorSettings.Settings.EyesClosedCalibration_NumRepetitions + ") received from ACAT and saved to BCISettings file"); } /// @@ -1136,11 +1140,11 @@ private void OnCalibrationEyesClosedIterationEnd(object request) // var bciLogEntry = new BCILogEntryEyesClosed(BCIActuatorSettings.Settings.EyesClosed_EnableDetection, 0, eyesClosedDetected, alphaValues, betaValues, avgAlpha, avgBeta, bciEyesClosedIterationEnd.BciEyesClosedMode.ToString()); // var jsonString = JsonConvert.SerializeObject(bciLogEntry); // AuditLog.Audit(new AuditEvent("BCIEyesClosedCalibration", jsonString)); - // Log.Debug("Saved to audit file:" + jsonString); + // _logger.LogDebug("Saved to audit file:" + jsonString); // } // catch (Exception e) // { - // Log.Exception(e.Message); + // _logger.LogError(e, "Failed to process eyes closed calibration event"); // } //} } @@ -1152,7 +1156,7 @@ private void OnCalibrationEyesClosedIterationEnd(object request) private void OnCalibrationEyesClosedEnd(object request) { // TODO: We do not use Eyes closed detection - //Log.Debug("Calibration eyes closed ended"); + //_logger.LogDebug("Calibration eyes closed ended"); //if (useSensor) //{ @@ -1167,11 +1171,11 @@ private void OnCalibrationEyesClosedEnd(object request) // // End the esssion // DAQ_OpenBCI.EndSession(); - // Log.Debug("Session ended"); + // _logger.LogDebug("Session ended"); // } // catch (Exception e) // { - // Log.Exception(e.Message); + // _logger.LogError(e, "Failed to end eyes closed calibration session"); // } //} } @@ -1184,7 +1188,7 @@ private void OnCalibrationEyesClosedEnd(object request) /// private void OnCalibrationEnd(object request) { - Log.Debug("Calibartion End Received"); + _logger.LogDebug("Calibration End Received"); var bciCalibrationEnd = request as BCICalibrationEnd; @@ -1219,18 +1223,18 @@ private void OnCalibrationEnd(object request) if (auc * 100 >= DictCalibrationParameters[_currentCalibrationMode].MinimumScoreRequired) calibrationSuccessful = true; - Log.Debug("Session: " + sessionID + " Calibrated successfully: " + calibrationSuccessful + " - AUC: " + auc); + _logger.LogDebug("Session: " + sessionID + " Calibrated successfully: " + calibrationSuccessful + " - AUC: " + auc); if (auc == -1)// Error when training classifiers { - Log.Debug("Error when training classifiers"); + _logger.LogDebug("Error when training classifiers"); error = new BCIError(BCIErrorCodes.CalibrationError_OnAnalyzingData_TrainingClassifiersError, StringResources.CalibrationError_CalibrationFailed); } } catch (Exception e) { auc = -1; - Log.Exception(e.Message); + _logger.LogError(e, "Failed during calibration data analysis"); error = new BCIError(BCIErrorCodes.CalibrationError_OnAnalyzingData_UnknownException, StringResources.CalibrationError_CalibrationFailed); } } @@ -1240,7 +1244,7 @@ private void OnCalibrationEnd(object request) if (BCIActuatorSettings.Settings.Testing_ForceRecalibrateFromFile && BCIActuatorSettings.Settings.Testing_CalibrationFileId != null) { auc = RecalibrateFromFile(); - Log.Debug("Recalibrated from file. AUC: " + auc); + _logger.LogDebug("Recalibrated from file. AUC: " + auc); } calibrationSuccessful = true; } @@ -1249,9 +1253,9 @@ private void OnCalibrationEnd(object request) // Send auc to ACAT var bciCalibrationResult = new BCICalibrationResult(auc, calibrationSuccessful, error); - Log.Debug("Sending response. Calibration result: " + calibrationSuccessful + " | AUC: " + auc); + _logger.LogDebug("Sending response. Calibration result: " + calibrationSuccessful + " | AUC: " + auc); SendIoctlResponse((int)OpCodes.CalibrationResult, bciCalibrationResult); - Log.Debug("IoctRequest " + OpCodes.CalibrationResult + " sent. Message: " + bciCalibrationResult.ToString()); + _logger.LogDebug("IoctRequest " + OpCodes.CalibrationResult + " sent. Message: " + bciCalibrationResult.ToString()); } /// @@ -1261,7 +1265,7 @@ private void OnCalibrationEnd(object request) /// private void OnCalibrationEndRepetition(object request) { - Log.Debug("Calibration end repetition received"); + _logger.LogDebug("Calibration end repetition received"); BCIError sensorError = new(BCIErrorCodes.Status_Ok, BCIMessages.Status_Ok); SignalStatus statusSignal = SignalStatus.SIGNAL_KO; @@ -1302,7 +1306,7 @@ private void OnCalibrationEndRepetition(object request) numTriggerPulsesExpected = bciCalibrationInput.RowColumnIDs.Count; if (numTriggerPulsesDetected == 0) { - Log.Debug("Optical sensor error. No pulses were detected"); + _logger.LogDebug("Optical sensor error. No pulses were detected"); sensorError = new BCIError(BCIErrorCodes.OpticalSensorError_NoPulsesDetected, StringResources.OpticalSensorError); } // Note: Removed code since we can't guarantee the number of pulses received given bluetooth delays @@ -1327,7 +1331,7 @@ private void OnCalibrationEndRepetition(object request) }; var jsonString = bciLogEntry; AuditLog.Audit(new AuditEvent("BCIEyesClosed", jsonString)); - Log.Debug("Line added to audit file: " + jsonString); + _logger.LogDebug("Line added to audit file: " + jsonString); } else { @@ -1339,7 +1343,7 @@ private void OnCalibrationEndRepetition(object request) catch (Exception e) { sensorError = new BCIError(BCIErrorCodes.CalibrationError_UnknwonException, StringResources.CalibrationError_CalibrationFailed); - Log.Exception(e.Message); + _logger.LogError(e, "Failed to process calibration input"); } } } @@ -1347,14 +1351,14 @@ private void OnCalibrationEndRepetition(object request) if (sensorError.ErrorCode != BCIErrorCodes.Status_Ok) { String txt = "Error on calibration repetition end (Error: " + sensorError.ErrorCode + " Message: " + sensorError.ErrorMessage + ") Expected pulses: " + numTriggerPulsesExpected + " - Detected pulses: " + numTriggerPulsesDetected; - Log.Debug(txt); + _logger.LogDebug(txt); } // Send result var bciCalibrationResult = new BCISensorStatus() { Error = sensorError, StatusSignal = statusSignal }; - Log.Debug("Sending response. SensorError:" + (BCIErrorCodes)bciCalibrationResult.Error.ErrorCode); + _logger.LogDebug("Sending response. SensorError:" + (BCIErrorCodes)bciCalibrationResult.Error.ErrorCode); SendIoctlResponse((int)OpCodes.CalibrationEndRepetitionResult, bciCalibrationResult); - Log.Debug("IoctRequest " + OpCodes.CalibrationEndRepetitionResult + " sent. Message: " + bciCalibrationResult.ToString()); + _logger.LogDebug("IoctRequest " + OpCodes.CalibrationEndRepetitionResult + " sent. Message: " + bciCalibrationResult.ToString()); } /// @@ -1374,7 +1378,7 @@ private void OnHighlightOnOff(object request) /// private void OnLanguageModelProbabilities(object request) { - Log.Debug("Language model probabilities received"); + _logger.LogDebug("Language model probabilities received"); var bciLanguageModelProbabilities = request as BCILanguageModelProbabilities; bool enableLanguageModelprobabilities = false; @@ -1383,7 +1387,7 @@ private void OnLanguageModelProbabilities(object request) epochIdx++; // Restart classifiers (nextcharacterprobs = clear talk window, resume after pause, etc) - Log.Debug("Restarting all probabilities"); + _logger.LogDebug("Restarting all probabilities"); EEGProcessingGlobals.RestartAllDecisionMakerProbabilities(); // Add next character probabilities (flag will be turn on/off if they shouldn't be @@ -1414,11 +1418,11 @@ private void OnLanguageModelProbabilities(object request) { EEGProcessingGlobals.DecisionMakerDict[currentSection].AddNextCharacterProbabilities(bciLanguageModelProbabilities.LanguageModelProbabilities); EEGProcessingGlobals.DecisionMakerDict[currentSection].enableLanguageModelProbabilities = enableLanguageModelprobabilities; - Log.Debug("Probabilities for " + currentSection + " added to. Use LM for section: " + enableLanguageModelprobabilities); + _logger.LogDebug("Probabilities for " + currentSection + " added to. Use LM for section: " + enableLanguageModelprobabilities); } else { - Log.Debug("Probabilities not added"); + _logger.LogDebug("Probabilities not added"); } } @@ -1431,7 +1435,7 @@ private void OnLanguageModelProbabilities(object request) }; var jsonString = bciLogEntry; AuditLog.Audit(new AuditEvent("BCILanguageModelProbabilitiesReceived", jsonString)); - Log.Debug("Line added to audit file: " + jsonString); + _logger.LogDebug("Line added to audit file: " + jsonString); } /// @@ -1472,7 +1476,7 @@ private void OnRequestParameters(object request) BCIError error = new(BCIErrorCodes.Status_Ok, BCIMessages.Status_Ok); var bciUserInputParameters = request as BCIUserInputParameters; - Log.Debug("Request parameters for mode " + bciUserInputParameters.BciMode); + _logger.LogDebug("Request parameters for mode " + bciUserInputParameters.BciMode); switch (bciUserInputParameters.BciMode) { @@ -1483,7 +1487,7 @@ private void OnRequestParameters(object request) break; case BCIModes.CALIBRATION: - Log.Debug("Calibration mode: " + bciUserInputParameters.BciCalibrationMode + " Scan time: " + bciUserInputParameters.ScanTime + " | Number of targets: " + bciUserInputParameters.NumTargets + " | Number of iterations per target: " + bciUserInputParameters.NumIterationsPerTarget + " | Minimum score required: " + bciUserInputParameters.MinScoreRequired); + _logger.LogDebug("Calibration mode: " + bciUserInputParameters.BciCalibrationMode + " Scan time: " + bciUserInputParameters.ScanTime + " | Number of targets: " + bciUserInputParameters.NumTargets + " | Number of iterations per target: " + bciUserInputParameters.NumIterationsPerTarget + " | Minimum score required: " + bciUserInputParameters.MinScoreRequired); // Update settings for the corresponding section from parameters sent from ACAT switch (bciUserInputParameters.BciCalibrationMode) @@ -1494,7 +1498,7 @@ private void OnRequestParameters(object request) BoxCalibrationSettings.NumberOfIterationsPerTarget = bciUserInputParameters.NumIterationsPerTarget; BoxCalibrationSettings.MinimumScoreRequired = bciUserInputParameters.MinScoreRequired; BoxCalibrationSettings.Save(); - Log.Debug("Parameters saved for box calibration"); + _logger.LogDebug("Parameters saved for box calibration"); break; case BCIScanSections.Word: @@ -1503,7 +1507,7 @@ private void OnRequestParameters(object request) WordCalibrationSettings.NumberOfIterationsPerTarget = bciUserInputParameters.NumIterationsPerTarget; WordCalibrationSettings.MinimumScoreRequired = bciUserInputParameters.MinScoreRequired; WordCalibrationSettings.Save(); - Log.Debug("Parameters saved for calibration"); + _logger.LogDebug("Parameters saved for calibration"); break; case BCIScanSections.Sentence: @@ -1512,7 +1516,7 @@ private void OnRequestParameters(object request) SentenceCalibrationSettings.NumberOfIterationsPerTarget = bciUserInputParameters.NumIterationsPerTarget; SentenceCalibrationSettings.MinimumScoreRequired = bciUserInputParameters.MinScoreRequired; SentenceCalibrationSettings.Save(); - Log.Debug("Parameters saved for sentence calibration"); + _logger.LogDebug("Parameters saved for sentence calibration"); break; case BCIScanSections.KeyboardL: @@ -1521,7 +1525,7 @@ private void OnRequestParameters(object request) KeyboardLeftCalibrationSettings.NumberOfIterationsPerTarget = bciUserInputParameters.NumIterationsPerTarget; KeyboardLeftCalibrationSettings.MinimumScoreRequired = bciUserInputParameters.MinScoreRequired; KeyboardLeftCalibrationSettings.Save(); - Log.Debug("Parameters saved for keyboard Left calibration"); + _logger.LogDebug("Parameters saved for keyboard Left calibration"); break; case BCIScanSections.KeyboardR: @@ -1530,7 +1534,7 @@ private void OnRequestParameters(object request) KeyboardRightCalibrationSettings.NumberOfIterationsPerTarget = bciUserInputParameters.NumIterationsPerTarget; KeyboardRightCalibrationSettings.MinimumScoreRequired = bciUserInputParameters.MinScoreRequired; KeyboardRightCalibrationSettings.Save(); - Log.Debug("Paramters saved for keyboard right calibration"); + _logger.LogDebug("Parameters saved for keyboard right calibration"); break; } @@ -1539,15 +1543,15 @@ private void OnRequestParameters(object request) DictCalibrationParameters[bciUserInputParameters.BciCalibrationMode].TargetCount = bciUserInputParameters.NumTargets; DictCalibrationParameters[bciUserInputParameters.BciCalibrationMode].IterationsPerTarget = bciUserInputParameters.NumIterationsPerTarget; DictCalibrationParameters[bciUserInputParameters.BciCalibrationMode].MinimumScoreRequired = bciUserInputParameters.MinScoreRequired; - Log.Debug("Parameters updated in the " + bciUserInputParameters.BciCalibrationMode + " dictionary"); + _logger.LogDebug("Parameters updated in the " + bciUserInputParameters.BciCalibrationMode + " dictionary"); break; } // Send parameters to ACAT var bciParameters = new BCIParameters(DictCalibrationParameters, recalibrationRequired, lastCalibrationAUC, BCIActuatorSettings.Settings.Scanning_PauseTime, BCIActuatorSettings.Settings.Scanning_ShortPauseTime, BCIActuatorSettings.Settings.Scanning_ShowDecisionTime, BCIActuatorSettings.Settings.Scanning_DelayAfterDecision, BCIActuatorSettings.Settings.Scanning_DelayToGetReady, BCIActuatorSettings.Settings.Testing_MinimumProbabiltyToDisplayBarOnTyping, BCIActuatorSettings.Settings.Scanning_FocalCircleColor, BCIActuatorSettings.Settings.Scanning_IsFocalCircleFilled, error); - Log.Debug("Sending parameters. Error:" + (BCIErrorCodes)bciParameters.Error.ErrorCode + " RecalibrationRequired:" + bciParameters.CalibrationRequiredFlag + " | Pause time:" + bciParameters.Scanning_PauseTime + ", Short pause time:" + bciParameters.Scanning_ShortPauseTime + ", Show decision time: " + bciParameters.Scanning_ShowDecisionTime + ", Delay after decision:" + bciParameters.Scanning_DelayAfterDecision + ", Minimum probability to display bars on typing:" + bciParameters.MinProbablityToDisplayBarOnTyping); + _logger.LogDebug("Sending parameters. Error:" + (BCIErrorCodes)bciParameters.Error.ErrorCode + " RecalibrationRequired:" + bciParameters.CalibrationRequiredFlag + " | Pause time:" + bciParameters.Scanning_PauseTime + ", Short pause time:" + bciParameters.Scanning_ShortPauseTime + ", Show decision time: " + bciParameters.Scanning_ShowDecisionTime + ", Delay after decision:" + bciParameters.Scanning_DelayAfterDecision + ", Minimum probability to display bars on typing:" + bciParameters.MinProbablityToDisplayBarOnTyping); SendIoctlResponse((int)OpCodes.SendParameters, bciParameters); - Log.Debug("IoctRequest " + OpCodes.SendParameters); + _logger.LogDebug("IoctRequest " + OpCodes.SendParameters); } /// @@ -1567,7 +1571,7 @@ private void OnSessionStart(object request) if (bciModeObj != null) { - Log.Debug("Start session: " + bciModeObj.BciMode); + _logger.LogDebug("Start session: " + bciModeObj.BciMode); if (useSensor) { @@ -1597,9 +1601,9 @@ private void OnSessionStart(object request) // For Debugging / Testing: calibrate from old file when selected from settings if (BCIActuatorSettings.Settings.Testing_ForceRecalibrateFromFile && BCIActuatorSettings.Settings.Testing_CalibrationFileId != null) { - Log.Debug("Recalibrating from file"); + _logger.LogDebug("Recalibrating from file"); float auc = RecalibrateFromFile(); - Log.Debug("Recalibrated from file. AUC: " + auc); + _logger.LogDebug("Recalibrated from file. AUC: " + auc); } if (!LoadClassifiers()) @@ -1617,7 +1621,7 @@ private void OnSessionStart(object request) } // Start session - Log.Debug("Starting session: " + sessionID); + _logger.LogDebug("Starting session: " + sessionID); sensorReady = _daqInstance.StartSession(sessionID, true); sessionDirectory = _daqInstance.GetSessionDirectory(); _isSessionInProgress = false; // set to true on calibrationEndRepetition and TypingEndRepetition @@ -1628,11 +1632,11 @@ private void OnSessionStart(object request) { filePathCopyTo = Path.Combine(sessionDirectory, fileName); filePathCopyFrom = UserManager.GetFullPath(fileName); - Log.Debug("Copying files from: " + filePathCopyFrom + " to " + filePathCopyTo); + _logger.LogDebug("Copying files from: " + filePathCopyFrom + " to " + filePathCopyTo); if (!String.IsNullOrEmpty(filePathCopyTo) && !String.IsNullOrEmpty(filePathCopyFrom) && File.Exists(filePathCopyFrom) && Directory.Exists(sessionDirectory)) { File.Copy(filePathCopyFrom, filePathCopyTo); - Log.Debug("FIles copied from: " + filePathCopyFrom + " to " + filePathCopyTo); + _logger.LogDebug("Files copied from: " + filePathCopyFrom + " to " + filePathCopyTo); } } } @@ -1655,13 +1659,13 @@ private void OnSessionStart(object request) SessionId = sessionID, Error = error }; - Log.Debug("Sending response. Error: " + (BCIErrorCodes)error.ErrorCode + " Sensor ready: " + bciStartSessionResults.SensorReady + " | session ID: " + sessionID + " | directory: " + sessionDirectory); + _logger.LogDebug("Sending response. Error: " + (BCIErrorCodes)error.ErrorCode + " Sensor ready: " + bciStartSessionResults.SensorReady + " | session ID: " + sessionID + " | directory: " + sessionDirectory); SendIoctlResponse((int)OpCodes.StartSessionResult, bciStartSessionResults); - Log.Debug("IoctRequest " + OpCodes.StartSessionResult + " sent. Message: " + bciStartSessionResults.ToString()); + _logger.LogDebug("IoctRequest " + OpCodes.StartSessionResult + " sent. Message: " + bciStartSessionResults.ToString()); } catch (Exception e) { - Log.Exception(e.Message); + _logger.LogError(e, "Failed to start session"); } } @@ -1683,7 +1687,7 @@ private float RecalibrateFromFile() if (idxCalibrationType != -1) { string calibrationType = sessionID.Substring(idxCalibrationType + strToFind.Length); - Log.Debug("Recalibrating from file " + sessionID + " | Test ID: " + BCIActuatorSettings.Settings.Testing_TestID + " | Calibration type:" + calibrationType); + _logger.LogDebug("Recalibrating from file " + sessionID + " | Test ID: " + BCIActuatorSettings.Settings.Testing_TestID + " | Calibration type:" + calibrationType); FeatureExtractionObj = calibrationType.ToLower() switch { @@ -1708,14 +1712,14 @@ private float RecalibrateFromFile() }; } - Log.Debug(" Recalibrating file " + sessionID); + _logger.LogDebug(" Recalibrating file " + sessionID); // Train classifiers auc = FeatureExtractionObj.Learn(sessionID); // will return -1 if error when training classifiers - Log.Debug("Recalibrated with AUC: " + auc); + _logger.LogDebug("Recalibrated with AUC: " + auc); } catch (Exception e) { - Log.Exception(e.Message); + _logger.LogError(e, "Failed to recalibrate from file"); } return auc; } @@ -1741,7 +1745,7 @@ private void OnToggleCalibrationWindow() /*if (!IsSignalFormVisible()) {*/ SendIoctlResponse((int)OpCodes.CalibrationWindowPreShow, String.Empty); - Log.Debug("IoctRequest " + OpCodes.CalibrationWindowPreShow + " sent. Message: empty"); + _logger.LogDebug("IoctRequest " + OpCodes.CalibrationWindowPreShow + " sent. Message: empty"); //} } @@ -1772,7 +1776,7 @@ private void OnTypingRepetitionEnd(object request) var bciTypingRepetitionEnd = request as BCITypingRepetitionEnd; BCIScanSections currentScanSection = bciTypingRepetitionEnd.ScanningSection; - Log.Debug("On typing Repetition end called for section: " + bciTypingRepetitionEnd.ScanningSection); + _logger.LogDebug("On typing Repetition end called for section: " + bciTypingRepetitionEnd.ScanningSection); if (useSensor) { @@ -1850,7 +1854,7 @@ private void OnTypingRepetitionEnd(object request) if (BCIActuatorSettings.Settings.EyesClosed_EnableDetection) { - Log.Debug("Eyes closed detected"); + _logger.LogDebug("Eyes closed detected"); returnToBoxScanningFlag = eyesClosedDetected; if (eyesClosedDetected) { @@ -1866,7 +1870,7 @@ private void OnTypingRepetitionEnd(object request) // Reduce and compute posterior probabilities decidedButtonID = 0; decidedFlag = false; - Log.Debug("Calculating posterior probabilities"); + _logger.LogDebug("Calculating posterior probabilities"); EEGProcessingGlobals.DecisionMakerDict[currentScanSection].ComputePosteriorProbs(allSamples, bciTypingRepetitionEnd.RowColumnIDs, bciTypingRepetitionEnd.FlashingSequence, @@ -1895,15 +1899,15 @@ private void OnTypingRepetitionEnd(object request) if (posteriorProbs == null || posteriorProbs.Count == 0) { //error = new BCIError(BCIErrorCodes.TypingError_OnRepetitionEnd_NoProbabilitiesCalculated, BCIMessages.TypingError); // no probabilities returned. optical sensor dead? - Log.Debug("Probabilities not returned from DeicisionMaker"); + _logger.LogDebug("Probabilities not returned from DeicisionMaker"); } else if (posteriorProbs.Count != buttonIds.Count) { // error = new BCIError(BCIErrorCodes.TypingError_OnRepetitionEnd_ProabilitiesMarkersMissmatch, BCIMessages.TypingError); - Log.Debug("Number of probabilities different than number of highlights. Num buttons: " + buttonIds.Count + " Num Probabilities: " + posteriorProbs.Count); + _logger.LogDebug("Number of probabilities different than number of highlights. Num buttons: " + buttonIds.Count + " Num Probabilities: " + posteriorProbs.Count); } - Log.Debug("Posterior probabilities calculated. Repetition: " + repetition + " Decided:" + decidedFlag + " DecisionLabel:" + decidedButtonLabel + " DecisionID: " + decidedButtonID + " Probabilities" + eegProbs.ToString()); + _logger.LogDebug("Posterior probabilities calculated. Repetition: " + repetition + " Decided:" + decidedFlag + " DecisionLabel:" + decidedButtonLabel + " DecisionID: " + decidedButtonID + " Probabilities" + eegProbs.ToString()); } } else @@ -1919,12 +1923,12 @@ private void OnTypingRepetitionEnd(object request) catch (Exception e) { error = new BCIError(BCIErrorCodes.TypingError_OnRepetitionEnd_UnknownException, StringResources.TypingError);// Error when processing data - Log.Exception("Error: " + error.ErrorCode + " Message" + error.ErrorMessage + " Excepcion: " + e.Message); + _logger.LogError(e, "Error: " + error.ErrorCode + " Message" + error.ErrorMessage); } // Display error on logs if (error.ErrorCode != BCIErrorCodes.Status_Ok) - Log.Exception("Error: " + error.ErrorCode + " Message" + error.ErrorMessage); + _logger.LogError("Error: {ErrorCode} Message: {ErrorMessage}", error.ErrorCode, error.ErrorMessage); } else { @@ -2017,7 +2021,7 @@ private void OnTypingRepetitionEnd(object request) }; var jsonString = bciLogEntry; AuditLog.Audit(new AuditEvent("BCIRepetitionEnd", jsonString)); - Log.Debug("Results: " + jsonString); + _logger.LogDebug("Results: " + jsonString); // Send results to application var bciTypingRepetitionResult = new BCITypingRepetitionResult @@ -2032,9 +2036,9 @@ private void OnTypingRepetitionEnd(object request) if (posteriorProbs != null) bciTypingRepetitionResult.PosteriorProbs = posteriorProbs; - Log.Debug("Sending response. Error: " + (BCIErrorCodes)error.ErrorCode + " | Decided:" + decidedFlag + "DecidedID:" + decidedButtonID + " ReturnToBoxScanning:" + returnToBoxScanningFlag + " StatusSignal: " + statusSignal); + _logger.LogDebug("Sending response. Error: " + (BCIErrorCodes)error.ErrorCode + " | Decided:" + decidedFlag + "DecidedID:" + decidedButtonID + " ReturnToBoxScanning:" + returnToBoxScanningFlag + " StatusSignal: " + statusSignal); SendIoctlResponse((int)OpCodes.TypingEndRepetitionResult, bciTypingRepetitionResult); - Log.Debug("IoctRequest " + OpCodes.TypingEndRepetitionResult + " sent. Message: " + bciTypingRepetitionResult.ToString()); + _logger.LogDebug("IoctRequest " + OpCodes.TypingEndRepetitionResult + " sent. Message: " + bciTypingRepetitionResult.ToString()); } /// diff --git a/src/Extensions/BCI/Actuators/EEGDataAcquisition/BaseDAQ.cs b/src/Extensions/BCI/Actuators/EEGDataAcquisition/BaseDAQ.cs index 53f7fba3..86bf3dfb 100644 --- a/src/Extensions/BCI/Actuators/EEGDataAcquisition/BaseDAQ.cs +++ b/src/Extensions/BCI/Actuators/EEGDataAcquisition/BaseDAQ.cs @@ -19,6 +19,7 @@ using System; using System.Collections.Generic; using System.Linq; +using Microsoft.Extensions.Logging; namespace ACAT.Extensions.BCI.Actuators.EEG.EEGDataAcquisition { @@ -27,6 +28,8 @@ namespace ACAT.Extensions.BCI.Actuators.EEG.EEGDataAcquisition /// public abstract class BaseDAQ { + protected static ILogger _logger; + /// /// Settings file name /// @@ -313,7 +316,7 @@ public virtual bool StartSession(string sessionID, bool forceSavingData) if (saveDataToFile) { - Log.Debug("Creating files for session: " + sessionID); + _logger?.LogDebug("Creating files for session: {SessionID}", sessionID); // Creates new file if (sessionID == "") @@ -329,7 +332,7 @@ public virtual bool StartSession(string sessionID, bool forceSavingData) } catch (Exception e) { - Log.Exception("Exception " + e.Message); + _logger?.LogError(e, "Exception starting session"); } return result; } @@ -352,12 +355,12 @@ public virtual bool EndSession() { GetData(); // Empty buffer } - Log.Debug("Session closed"); + _logger?.LogDebug("Session closed"); result = true; } catch (Exception e) { - Log.Exception("Exception " + e.Message); + _logger?.LogError(e, "Exception ending session"); } return result; @@ -398,7 +401,7 @@ protected virtual bool AppendDataToBuffer(double[,] data, double[,] inBuffer, in } catch (Exception e) { - Log.Exception(e.Message); + _logger?.LogError(e, "Exception appending data to buffer"); } return result; } @@ -413,7 +416,7 @@ protected virtual void CreateFiles(string sessionID) { if (FileWriterObj == null) { - Log.Debug("Creating files for session: " + sessionID); + _logger?.LogDebug("Creating files for session: {SessionID}", sessionID); if (sessionID == "") FileWriterObj = new FileWriter(); @@ -433,12 +436,12 @@ public virtual void Config_Board(string cmd) { try { - Log.Debug("Config board. Command: " + cmd); + _logger?.LogDebug("Config board. Command: {Command}", cmd); DeviceObj.config_board(cmd); } catch (Exception ex) { - Log.Exception(ex); + _logger?.LogError(ex, "Exception configuring board"); } } } diff --git a/src/Extensions/BCI/Actuators/EEGDataAcquisition/DAQ_OpenBCI.cs b/src/Extensions/BCI/Actuators/EEGDataAcquisition/DAQ_OpenBCI.cs index 2726d2b3..a0a2d805 100644 --- a/src/Extensions/BCI/Actuators/EEGDataAcquisition/DAQ_OpenBCI.cs +++ b/src/Extensions/BCI/Actuators/EEGDataAcquisition/DAQ_OpenBCI.cs @@ -17,6 +17,7 @@ using ACAT.Extensions.BCI.Common.BCIControl; using Accord.Math; using brainflow; +using Microsoft.Extensions.Logging; using Microsoft.Win32; using System; using System.Collections.Generic; @@ -28,6 +29,8 @@ namespace ACAT.Extensions.BCI.Actuators.EEG.EEGDataAcquisition { public class DAQ_OpenBCI : BaseDAQ { + private readonly ILogger _logger; + // ********** Params set here (not read from settings) // private readonly string[] otherChannelsPinsNameList = { "x", "D11", "D12", "D13", "D17", "D18", "x" }; // private readonly int[] otherChannelsPinsIdxList = {12, 13, 14, 15, 16, 17, 18}; this is returnet when DeviceObj.get_other_channels(); @@ -105,13 +108,21 @@ public enum DaisyBoardStatus // ExitCodes enum is now inherited from BaseDAQ + /// + /// Initializes an instance of the class + /// + public DAQ_OpenBCI() + { + _logger = LoggingConfiguration.CreateLogger(); + } + /// /// Loads settings from the configuration file /// public override void LoadSettings() { SignalControl_WindowDurationForVrmsMeaseurment = BCIActuatorSettings.Settings.SignalControl_WindowDurationForVrmsMeaseurment; - Log.Debug("DAQ settings loaded. Window duration for uVrmsMeasurement: " + SignalControl_WindowDurationForVrmsMeaseurment); + _logger.LogDebug("DAQ settings loaded. Window duration for uVrmsMeasurement: " + SignalControl_WindowDurationForVrmsMeaseurment); switch (BCIActuatorSettings.Settings.DAQ_NumEEGChannels) { @@ -135,19 +146,19 @@ public override void LoadSettings() BCISettingsFixed.DataParser_IdxTriggerSignal_Hw = 16; BCISettingsFixed.DataParser_IdxTriggerSignal_Sw = 24; BCISettingsFixed.DimReduct_DownsampleRate = 2; - Log.Debug("Num Channels settings is incorrect. Sensor set to default: 8 channels"); + _logger.LogDebug("Num Channels settings is incorrect. Sensor set to default: 8 channels"); break; } BCIActuatorSettings.Save(); - Log.Debug("Sensor set to " + BCIActuatorSettings.Settings.DAQ_NumEEGChannels + " channels. SensorID: " + BCISettingsFixed.DAQ_SensorId + " , Downsample rate: " + BCISettingsFixed.DimReduct_DownsampleRate + + _logger.LogDebug("Sensor set to " + BCIActuatorSettings.Settings.DAQ_NumEEGChannels + " channels. SensorID: " + BCISettingsFixed.DAQ_SensorId + " , Downsample rate: " + BCISettingsFixed.DimReduct_DownsampleRate + " , Idx hw trigger signal: " + BCISettingsFixed.DataParser_IdxTriggerSignal_Hw + " , Idx sw trigger signal: " + BCISettingsFixed.DataParser_IdxTriggerSignal_Sw); boardID = BCISettingsFixed.DAQ_SensorId; saveDataToFile = BCIActuatorSettings.Settings.DAQ_SaveToFileFlag; frontendFilterIdx = BCIActuatorSettings.Settings.DAQ_FrontendFilterIdx; notchFilterIdx = BCIActuatorSettings.Settings.DAQ_NotchFilterIdx; - Log.Debug(" Frontend filter: " + frontendFilterIdx + " Notch filter: " + notchFilterIdx); + _logger.LogDebug(" Frontend filter: " + frontendFilterIdx + " Notch filter: " + notchFilterIdx); eyesClosedDetectionUseFixThreshold = BCIActuatorSettings.Settings.EyesClosed_UseFixThreshold; if (eyesClosedDetectionUseFixThreshold) @@ -155,7 +166,7 @@ public override void LoadSettings() else eyesClosedDetectionThreshold = BCIActuatorSettings.Settings.EyesClosed_AdaptiveThreshold; eyesClosed_WindowDuration = BCIActuatorSettings.Settings.EyesClosed_WindowDuration; - Log.Debug("Eyes closed detection. Use Fix Threshold" + eyesClosedDetectionUseFixThreshold + " Threshold: " + eyesClosedDetectionThreshold + " Window duration: " + eyesClosed_WindowDuration); + _logger.LogDebug("Eyes closed detection. Use Fix Threshold" + eyesClosedDetectionUseFixThreshold + " Threshold: " + eyesClosedDetectionThreshold + " Window duration: " + eyesClosed_WindowDuration); } #region Get/set @@ -221,13 +232,13 @@ public String DetectPort() foreach (String port in SerialPort.GetPortNames()) { - Log.Debug("Checking port " + port); + _logger.LogDebug("Checking port " + port); serialPort = port; AddWarning(ExitCodes.IDLE, " Time: " + DateTime.Now.ToString("h:mm:ss tt") + " TESTING PORT MESSAGE: Serial port " + serialPort); if (TestPort(port, out _)) { - Log.Debug("Detected cytonboard port " + port); + _logger.LogDebug("Detected cytonboard port " + port); return serialPort; } } @@ -298,13 +309,13 @@ public override bool InitDevice(string deviceIdentifier) { if (status == BoardStatus.BOARD_OPEN) { - Log.Debug("Board was open, closing device"); + _logger.LogDebug("Board was open, closing device"); CloseDevice(); } if (status == BoardStatus.BOARD_ACQUIRINGDATA) { - Log.Debug("Board already acquiring data, returning"); + _logger.LogDebug("Board already acquiring data, returning"); return true; } else @@ -314,13 +325,13 @@ public override bool InitDevice(string deviceIdentifier) // Enable /disable boardlogging if (boardLoggerEnabled) { - Log.Debug("BoardLoggerEnabled: " + boardLoggerEnabled + " Enabling brainflow logging"); + _logger.LogDebug("BoardLoggerEnabled: " + boardLoggerEnabled + " Enabling brainflow logging"); BoardShim.enable_dev_board_logger(); BoardShim.set_log_file(boardLogFileName); } else { - Log.Debug("BoardLoggerEnabled: " + boardLoggerEnabled + " Disabling brainflow logging"); + _logger.LogDebug("BoardLoggerEnabled: " + boardLoggerEnabled + " Disabling brainflow logging"); BoardShim.disable_board_logger(); } @@ -331,22 +342,22 @@ public override bool InitDevice(string deviceIdentifier) } // Test port - Log.Debug("Testing port: " + port); + _logger.LogDebug("Testing port: " + port); bool sensorConnected = TestPort(port, out _); if (!sensorConnected) { - Log.Debug("Sensor not connected to port " + port + ". Starting port detection"); + _logger.LogDebug("Sensor not connected to port " + port + ". Starting port detection"); port = DetectPort(); - Log.Debug("Port " + port + " detected. Testing port"); + _logger.LogDebug("Port " + port + " detected. Testing port"); sensorConnected = TestPort(port, out _); - Log.Debug("Port " + port + " tested. Result: " + sensorConnected); + _logger.LogDebug("Port " + port + " tested. Result: " + sensorConnected); } BrainFlowInputParams input_params = new(); if (sensorConnected) { - Log.Debug("Sensor connected to port " + port); + _logger.LogDebug("Sensor connected to port " + port); // Save port serialPort = port; @@ -354,7 +365,7 @@ public override bool InitDevice(string deviceIdentifier) // Save port to settings BCIActuatorSettings.Settings.DAQ_ComPort = serialPort; BCIActuatorSettings.Save(); - Log.Debug("Port: " + serialPort + " saved to settings"); + _logger.LogDebug("Port: " + serialPort + " saved to settings"); // Check if Cyton Daisy board attached // Makes separate COM connection (BrainFlow / BoardShim does not allow parsing of responses from lower level commands @@ -375,7 +386,7 @@ public override bool InitDevice(string deviceIdentifier) DeviceObj = new BoardShim(boardID, input_params); DeviceObj.prepare_session(); - Log.Debug("DAQ_OpenBCI - InitDevice | Board session prepared"); + _logger.LogDebug("DAQ_OpenBCI - InitDevice | Board session prepared"); indEegChannels = BoardShim.get_eeg_channels(boardID); sampleRate = BoardShim.get_sampling_rate(boardID); @@ -385,12 +396,12 @@ public override bool InitDevice(string deviceIdentifier) FrontendFilter = new Filter(frontendFilterIdx, Filter.FilterTypes.Frontend); NotchFilter = new Filter(notchFilterIdx, Filter.FilterTypes.Notch); - Log.Debug("Creating Frontend filter: " + frontendFilterIdx + " | Notch filter: " + notchFilterIdx); + _logger.LogDebug("Creating Frontend filter: " + frontendFilterIdx + " | Notch filter: " + notchFilterIdx); status = BoardStatus.BOARD_OPEN; deviceInitialized = true; AddWarning(ExitCodes.IDLE, " Time: " + DateTime.Now.ToString("h:mm:ss tt") + " STATUS MESSAGE: Device initialized at serial port: " + serialPort); - Log.Debug("Board initialized. Status: " + status.ToString()); + _logger.LogDebug("Board initialized. Status: " + status.ToString()); return true; } else @@ -399,7 +410,7 @@ public override bool InitDevice(string deviceIdentifier) } catch (Exception e) { - Log.Exception(e.Message); + _logger.LogError(e, e.Message); sensorStatus = getErrorCode(e.Message, ExitCodes.BOARD_NOT_READY_ERROR); AddWarning(sensorStatus, " Time: " + DateTime.Now.ToString("h:mm:ss tt") + " WARNING MESSAGE: Error Code: " + sensorStatus); return false; @@ -422,7 +433,7 @@ public override bool Start(string deviceIdentifier = "", bool saveData = false, { // Init device bool initPortSuccess; - Log.Debug("Initiating device"); + _logger.LogDebug("Initiating device"); if (status != BoardStatus.BOARD_OPEN) { if (!String.IsNullOrWhiteSpace(deviceIdentifier)) @@ -433,15 +444,15 @@ public override bool Start(string deviceIdentifier = "", bool saveData = false, else initPortSuccess = true; - Log.Debug("Starting stream"); + _logger.LogDebug("Starting stream"); DeviceObj.start_stream(); - Log.Debug("Stream started"); + _logger.LogDebug("Stream started"); status = BoardStatus.BOARD_ACQUIRINGDATA; if (saveDataToFile) { - Log.Debug("Creating files for session " + sessionID); + _logger.LogDebug("Creating files for session " + sessionID); CreateFiles(sessionID); } @@ -455,10 +466,10 @@ public override bool Start(string deviceIdentifier = "", bool saveData = false, { sensorStatus = getErrorCode(e.Message, ExitCodes.BOARD_NOT_CREATED_ERROR); AddWarning(sensorStatus, " Time: " + DateTime.Now.ToString("h:mm:ss tt") + " WARNING MESSAGE: Error Code: " + sensorStatus); - Log.Exception("Exception:" + e.Message + " Error code:" + sensorStatus); + _logger.LogError("Exception:" + e.Message + " Error code:" + sensorStatus); success = false; } - Log.Debug("Device started: " + success); + _logger.LogDebug("Device started: " + success); return success; } @@ -472,19 +483,19 @@ public override bool Stop() { if (status == BoardStatus.BOARD_ACQUIRINGDATA) { - Log.Debug("Board acquiring data. Stopping device"); + _logger.LogDebug("Board acquiring data. Stopping device"); GetData(); DeviceObj.stop_stream(); DeviceObj.release_session(); - Log.Debug("Device stopped"); + _logger.LogDebug("Device stopped"); } if (saveDataToFile && FileWriterObj != null && FileWriterObj.isFileOpened) { - Log.Debug("Closing files"); + _logger.LogDebug("Closing files"); FileWriterObj.CloseFiles(); FileWriterObj = null; - Log.Debug("Files closed"); + _logger.LogDebug("Files closed"); } status = BoardStatus.BOARD_STANDBY; @@ -494,7 +505,7 @@ public override bool Stop() { sensorStatus = getErrorCode(e.Message, ExitCodes.SYNC_TIMEOUT_ERROR); AddWarning(sensorStatus, " Time: " + DateTime.Now.ToString("h:mm:ss tt") + " WARNING MESSAGE: Error Code: " + sensorStatus); - Log.Exception("Exception:" + e.Message + " Error code: " + sensorStatus); + _logger.LogError("Exception:" + e.Message + " Error code: " + sensorStatus); return false; } } @@ -509,7 +520,7 @@ public override bool CloseDevice() { if (status == BoardStatus.BOARD_CLOSED) { - Log.Debug("Board already closed"); + _logger.LogDebug("Board already closed"); return true; } @@ -518,14 +529,14 @@ public override bool CloseDevice() DeviceObj.release_session(); status = BoardStatus.BOARD_CLOSED; - Log.Debug("Device closed"); + _logger.LogDebug("Device closed"); return true; } catch (Exception e) { sensorStatus = getErrorCode(e.Message, ExitCodes.UNABLE_TO_CLOSE); AddWarning(sensorStatus, " Time: " + DateTime.Now.ToString("h:mm:ss tt") + " WARNING MESSAGE: Error Code: " + sensorStatus); - Log.Exception("Exception:" + e.Message + " Error code: " + sensorStatus); + _logger.LogError("Exception:" + e.Message + " Error code: " + sensorStatus); return false; } } @@ -570,7 +581,7 @@ public override bool CloseDevice() } catch (Exception e) { - Log.Exception("Exception: " + e.Message); + _logger.LogError(e, e.Message); } if (returnFilteredData) @@ -715,7 +726,7 @@ public override SignalStatus GetStatus(out SignalStatus[] statusSignals) } catch (Exception e) { - Log.Exception("Exception: " + e.Message); + _logger.LogError(e, e.Message); } } return statusAllSignals; @@ -765,7 +776,7 @@ private bool AppendDataToBuffer(double[,] data, double[,] inBuffer, int numSampl } catch (Exception e) { - Log.Exception(e.Message); + _logger.LogError(e, e.Message); } return result; } @@ -831,7 +842,7 @@ public bool DetectEyesClosed(out double[] alphaValues, out double avgAlpha, out } catch (Exception e) { - Log.Exception(e.Message); + _logger.LogError(e, e.Message); } } avgAlpha /= indEegChannels.Length; @@ -860,7 +871,7 @@ private bool TestPort(String port, out bool portAlreadyOpen) portAlreadyOpen = false; try { - Log.Debug("Testing port " + port); + _logger.LogDebug("Testing port " + port); BrainFlowInputParams input_params = new() { serial_port = port @@ -869,7 +880,7 @@ private bool TestPort(String port, out bool portAlreadyOpen) DeviceObj = new BoardShim(boardID, input_params); DeviceObj.prepare_session(); DeviceObj.release_session(); - Log.Debug("Sensor detected to port" + port); + _logger.LogDebug("Sensor detected to port" + port); return true; } catch (Exception e) @@ -878,7 +889,7 @@ private bool TestPort(String port, out bool portAlreadyOpen) if (sensorStatus == ExitCodes.ANOTHER_BOARD_IS_CREATED_ERROR) portAlreadyOpen = true; AddWarning(sensorStatus, " Time: " + DateTime.Now.ToString("h:mm:ss tt") + " WARNING MESSAGE: Error Code: " + sensorStatus); - Log.Exception("Exception: " + e.Message); + _logger.LogError(e, e.Message); return false; } } @@ -927,7 +938,7 @@ private UInt32 ReadLatencyTimerValue(String comPort) } catch (Exception e) { - Log.Exception("Exception: " + e.Message); + _logger.LogError(e, e.Message); } return 0; @@ -959,7 +970,7 @@ private void CreateFiles(String sessionID) { if (FileWriterObj == null) { - Log.Debug("Creating files for session: " + sessionID); + _logger.LogDebug("Creating files for session: " + sessionID); if (sessionID == "") FileWriterObj = new FileWriter(); @@ -993,7 +1004,7 @@ public override bool StartSession(string sessionID, bool forceSavingData) if (saveDataToFile) { - Log.Debug("Creating files for session: " + sessionID); + _logger.LogDebug("Creating files for session: " + sessionID); // Creates new file if (sessionID == "") @@ -1010,7 +1021,7 @@ public override bool StartSession(string sessionID, bool forceSavingData) } catch (Exception e) { - Log.Exception("Exception " + e.Message); + _logger.LogError(e.Message); } return result; } @@ -1033,12 +1044,12 @@ public override bool EndSession() { GetData(); // Empty buffer } - Log.Debug("Session closed"); + _logger.LogDebug("Session closed"); result = true; } catch (Exception e) { - Log.Exception("Exception " + e.Message); + _logger.LogError(e.Message); } return result; @@ -1082,7 +1093,7 @@ public Dictionary getWarning() } catch (Exception e) { - Log.Exception(e.Message); + _logger.LogError(e, e.Message); return info; } return info; @@ -1096,12 +1107,12 @@ public void Config_Board(string cmd) { try { - Log.Debug("Config board. Command" + cmd); + _logger.LogDebug("Config board. Command" + cmd); DeviceObj.config_board(cmd); } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, ex.Message); } } @@ -1160,14 +1171,14 @@ private bool cytonIsDaisyAttached(String comPort) NewLine = "$$$" }; - Log.Debug(String.Format("cytonIsDaisyAttached | Opening serial port with port name: {0}, baud rate: {1}", serialPort.PortName, serialPort.BaudRate)); + _logger.LogDebug(String.Format("cytonIsDaisyAttached | Opening serial port with port name: {0}, baud rate: {1}", serialPort.PortName, serialPort.BaudRate)); serialPort.Open(); Thread.Sleep(100); // If the port is open, do something if (serialPort.IsOpen) { - Log.Debug("cytonIsDaisyAttached | serialPort is open"); + _logger.LogDebug("cytonIsDaisyAttached | serialPort is open"); int max_tries = 3; while (!receivedResponse && max_tries > 0) { @@ -1176,7 +1187,7 @@ private bool cytonIsDaisyAttached(String comPort) Thread.Sleep(1000); String response = serialPort.ReadLine().Trim(); - Log.Debug(String.Format("cytonIsDaisyAttached | response: {0}", response)); + _logger.LogDebug(String.Format("cytonIsDaisyAttached | response: {0}", response)); if (response == "8" || response == "16") { @@ -1203,7 +1214,7 @@ private bool cytonIsDaisyAttached(String comPort) Thread.Sleep(500); } - Log.Debug("cytonIsDaisyAttached | End read line / check loop. Sending reset board command"); + _logger.LogDebug("cytonIsDaisyAttached | End read line / check loop. Sending reset board command"); serialPort.WriteLine("d"); Thread.Sleep(3500); } @@ -1221,35 +1232,35 @@ private bool cytonIsDaisyAttached(String comPort) BCIActuatorSettings.Settings.DAQ_NumEEGChannels = 8; _daisyBoardStatus = DaisyBoardStatus.NOT_CONNECTED; } - Log.Debug("cytonIsDaisyAttached | Received a valid response from cyton board | DAQ_NumEEGChannels: " + + _logger.LogDebug("cytonIsDaisyAttached | Received a valid response from cyton board | DAQ_NumEEGChannels: " + BCIActuatorSettings.Settings.DAQ_NumEEGChannels.ToString()); BCIActuatorSettings.Save(); } else { - Log.Debug("cytonIsDaisyAttached | Did not receive a valid response from cyton board. Setting DAQ_NumEEGChannels to 8"); + _logger.LogDebug("cytonIsDaisyAttached | Did not receive a valid response from cyton board. Setting DAQ_NumEEGChannels to 8"); BCIActuatorSettings.Settings.DAQ_NumEEGChannels = 16; } } catch (Exception e) { - Log.Exception(e.Message); + _logger.LogError(e, e.Message); } finally { - Log.Debug("cytonIsDaisyAttached | closing serialPort from finally"); + _logger.LogDebug("cytonIsDaisyAttached | closing serialPort from finally"); serialPort.Close(); - Log.Debug("cytonIsDaisyAttached | serialPort closed from finally"); + _logger.LogDebug("cytonIsDaisyAttached | serialPort closed from finally"); } if (serialPort != null && serialPort.IsOpen) { - Log.Debug("cytonIsDaisyAttached | serialPort not yet closed. calling close() again"); + _logger.LogDebug("cytonIsDaisyAttached | serialPort not yet closed. calling close() again"); serialPort.Close(); } - Log.Debug(String.Format("cytonDaisyAttached() done | " + + _logger.LogDebug(String.Format("cytonDaisyAttached() done | " + "receivedResponse: {0}, " + "daisyBoardAttached: {1}, " + "BCIActuatorSettings.Settings.DAQ_NumEEGChannels: {2}", diff --git a/src/Extensions/BCI/Actuators/EEGDataAcquisition/DAQ_gTecBCI.cs b/src/Extensions/BCI/Actuators/EEGDataAcquisition/DAQ_gTecBCI.cs index 9f48cc7b..0cf63a89 100644 --- a/src/Extensions/BCI/Actuators/EEGDataAcquisition/DAQ_gTecBCI.cs +++ b/src/Extensions/BCI/Actuators/EEGDataAcquisition/DAQ_gTecBCI.cs @@ -19,6 +19,7 @@ using Gtec.Unicorn; #endif +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; @@ -31,6 +32,8 @@ namespace ACAT.Extensions.BCI.Actuators.EEG.EEGDataAcquisition /// public class DAQ_gTecBCI : BaseDAQ { + private static readonly ILogger _logger = LogManager.CreateLogger(); + /// /// MInimum duty cycle required to pass trigger test. Set to 0 for no duty cycle requirement /// @@ -55,7 +58,7 @@ public override void LoadSettings() { SignalControl_WindowDurationForVrmsMeaseurment = BCIActuatorSettings.Settings.SignalControl_WindowDurationForVrmsMeaseurment; SignalControl_MinDutyCycleToPassTriggerTest = BCIActuatorSettings.Settings.TriggerTest_MinDutyCycleToPassTriggerTest; - Log.Debug("DAQ settings loaded. Min duty cycle to pass trigger test" + SignalControl_MinDutyCycleToPassTriggerTest + " Window duration for uVrmsMeasurement: " + SignalControl_WindowDurationForVrmsMeaseurment); + _logger.LogDebug("DAQ settings loaded. Min duty cycle to pass trigger test" + SignalControl_MinDutyCycleToPassTriggerTest + " Window duration for uVrmsMeasurement: " + SignalControl_WindowDurationForVrmsMeaseurment); // Gtec Does not have hardware trigger so we will keep both same for ML that support openbci BCIActuatorSettings.Settings.DAQ_NumEEGChannels = 8; @@ -80,14 +83,14 @@ public override void LoadSettings() BCIActuatorSettings.Save(); - Log.Debug("Sensor set to " + BCIActuatorSettings.Settings.DAQ_NumEEGChannels + " channels. SensorID: " + BCISettingsFixed.DAQ_SensorId + " , Downsample rate: " + BCISettingsFixed.DimReduct_DownsampleRate + + _logger.LogDebug("Sensor set to " + BCIActuatorSettings.Settings.DAQ_NumEEGChannels + " channels. SensorID: " + BCISettingsFixed.DAQ_SensorId + " , Downsample rate: " + BCISettingsFixed.DimReduct_DownsampleRate + " , Idx hw trigger signal: " + BCISettingsFixed.DataParser_IdxTriggerSignal_Hw + " , Idx sw trigger signal: " + BCISettingsFixed.DataParser_IdxTriggerSignal_Sw); saveDataToFile = BCIActuatorSettings.Settings.DAQ_SaveToFileFlag; frontendFilterIdx = BCIActuatorSettings.Settings.DAQ_FrontendFilterIdx; notchFilterIdx = BCIActuatorSettings.Settings.DAQ_NotchFilterIdx; - Log.Debug(" Frontend filter: " + frontendFilterIdx + " Notch filter: " + notchFilterIdx); + _logger.LogDebug(" Frontend filter: " + frontendFilterIdx + " Notch filter: " + notchFilterIdx); } public static bool IsDeviceAvailable() @@ -110,7 +113,7 @@ public static bool IsDeviceAvailable() } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, ex.Message); } return success; @@ -139,13 +142,13 @@ public override bool InitDevice(string serial_number = "") if (status == BoardStatus.BOARD_OPEN) { - Log.Debug("Board was open, closing device"); + _logger.LogDebug("Board was open, closing device"); CloseDevice(); } if (status == BoardStatus.BOARD_ACQUIRINGDATA) { - Log.Debug("Board already acquiring data, returning"); + _logger.LogDebug("Board already acquiring data, returning"); return true; } else @@ -155,30 +158,30 @@ public override bool InitDevice(string serial_number = "") // Enable /disable boardlogging if (boardLoggerEnabled) { - Log.Debug("BoardLoggerEnabled: " + boardLoggerEnabled + " Enabling brainflow logging"); + _logger.LogDebug("BoardLoggerEnabled: " + boardLoggerEnabled + " Enabling brainflow logging"); BoardShim.enable_dev_board_logger(); BoardShim.set_log_file(boardLogFileName); } else { - Log.Debug("BoardLoggerEnabled: " + boardLoggerEnabled + " Disabling brainflow logging"); + _logger.LogDebug("BoardLoggerEnabled: " + boardLoggerEnabled + " Disabling brainflow logging"); BoardShim.disable_board_logger(); } // Test port - Log.Debug("Testing port: " + serial_number); + _logger.LogDebug("Testing port: " + serial_number); bool sensorConnected = TestPort(serial_number, out _); BrainFlowInputParams input_params = new(); if (sensorConnected) { - Log.Debug("Sensor connected to port " + serial_number); + _logger.LogDebug("Sensor connected to port " + serial_number); // Save port to settings BCIActuatorSettings.Settings.GTecDeviceName = serial_number; BCIActuatorSettings.Save(); - Log.Debug("Port: " + serial_number + " saved to settings"); + _logger.LogDebug("Port: " + serial_number + " saved to settings"); // DAQ_NumEEGChannels may have changed - run LoadSettings() at this point LoadSettings(); @@ -202,14 +205,14 @@ public override bool InitDevice(string serial_number = "") FrontendFilter = new Filter(frontendFilterIdx, Filter.FilterTypes.Frontend); NotchFilter = new Filter(notchFilterIdx, Filter.FilterTypes.Notch); - Log.Debug("Creating Frontend filter: " + frontendFilterIdx + " | Notch filter: " + notchFilterIdx); + _logger.LogDebug("Creating Frontend filter: " + frontendFilterIdx + " | Notch filter: " + notchFilterIdx); status = BoardStatus.BOARD_OPEN; deviceInitialized = true; AddWarning(ExitCodes.IDLE, " Time: " + DateTime.Now.ToString("h:mm:ss tt") + " STATUS MESSAGE: Device initialized at serial port: " + serial_number); - Log.Debug("Board initialized. Status: " + status.ToString()); + _logger.LogDebug("Board initialized. Status: " + status.ToString()); return true; } @@ -219,7 +222,7 @@ public override bool InitDevice(string serial_number = "") } catch (Exception e) { - Log.Exception(e.Message); + _logger.LogError(e.Message); sensorStatus = getErrorCode(e.Message, ExitCodes.BOARD_NOT_READY_ERROR); AddWarning(sensorStatus, " Time: " + DateTime.Now.ToString("h:mm:ss tt") + " WARNING MESSAGE: Error Code: " + sensorStatus); return false; @@ -242,22 +245,22 @@ public override bool Start(string serial_number = "", bool saveData = false, str { // Init device bool initPortSuccess; - Log.Debug("Initiating device"); + _logger.LogDebug("Initiating device"); if (status != BoardStatus.BOARD_OPEN) initPortSuccess = InitDevice(serial_number); else initPortSuccess = true; - Log.Debug("Starting stream"); + _logger.LogDebug("Starting stream"); Start_Streaming(); - Log.Debug("Stream started"); + _logger.LogDebug("Stream started"); status = BoardStatus.BOARD_ACQUIRINGDATA; //triggerTestInProgressFlag = false; if (saveDataToFile) { - Log.Debug("Creating files for session " + sessionID); + _logger.LogDebug("Creating files for session " + sessionID); CreateFiles(sessionID); } @@ -271,10 +274,10 @@ public override bool Start(string serial_number = "", bool saveData = false, str { sensorStatus = getErrorCode(e.Message, ExitCodes.BOARD_NOT_CREATED_ERROR); AddWarning(sensorStatus, " Time: " + DateTime.Now.ToString("h:mm:ss tt") + " WARNING MESSAGE: Error Code: " + sensorStatus); - Log.Exception("Exception:" + e.Message + " Error code:" + sensorStatus); + _logger.LogError("Exception:" + e.Message + " Error code:" + sensorStatus); success = false; } - Log.Debug("Device started: " + success); + _logger.LogDebug("Device started: " + success); return success; } @@ -288,18 +291,18 @@ public override bool Stop() { if (status == BoardStatus.BOARD_ACQUIRINGDATA) { - Log.Debug("Board acquiring data. Stopping device"); + _logger.LogDebug("Board acquiring data. Stopping device"); GetData(); Stop_Streaming(); - Log.Debug("Device stopped"); + _logger.LogDebug("Device stopped"); } if (saveDataToFile && FileWriterObj != null && FileWriterObj.isFileOpened) { - Log.Debug("Closing files"); + _logger.LogDebug("Closing files"); FileWriterObj.CloseFiles(); FileWriterObj = null; - Log.Debug("Files closed"); + _logger.LogDebug("Files closed"); } status = BoardStatus.BOARD_STANDBY; @@ -309,7 +312,7 @@ public override bool Stop() { sensorStatus = getErrorCode(e.Message, ExitCodes.SYNC_TIMEOUT_ERROR); AddWarning(sensorStatus, " Time: " + DateTime.Now.ToString("h:mm:ss tt") + " WARNING MESSAGE: Error Code: " + sensorStatus); - Log.Exception("Exception:" + e.Message + " Error code: " + sensorStatus); + _logger.LogError("Exception:" + e.Message + " Error code: " + sensorStatus); return false; } } @@ -324,7 +327,7 @@ public override bool CloseDevice() { if (status == BoardStatus.BOARD_CLOSED) { - Log.Debug("Board already closed"); + _logger.LogDebug("Board already closed"); return true; } @@ -334,14 +337,14 @@ public override bool CloseDevice() } status = BoardStatus.BOARD_CLOSED; - Log.Debug("Device closed"); + _logger.LogDebug("Device closed"); return true; } catch (Exception e) { sensorStatus = getErrorCode(e.Message, ExitCodes.UNABLE_TO_CLOSE); AddWarning(sensorStatus, " Time: " + DateTime.Now.ToString("h:mm:ss tt") + " WARNING MESSAGE: Error Code: " + sensorStatus); - Log.Exception("Exception:" + e.Message + " Error code: " + sensorStatus); + _logger.LogError("Exception:" + e.Message + " Error code: " + sensorStatus); return false; } } @@ -383,7 +386,7 @@ public override bool CloseDevice() } catch (Exception e) { - Log.Exception("Exception: " + e.Message); + _logger.LogError("Exception: " + e.Message); } if (returnFilteredData) @@ -414,14 +417,14 @@ private bool TestPort(String serial_number, out bool portAlreadyOpen) portAlreadyOpen = false; try { - Log.Debug("Testing port " + serial_number); + _logger.LogDebug("Testing port " + serial_number); BrainFlowInputParams input_params = new(); //input_params.serial_number = serial_number; DeviceObj = new BoardShim(boardID, input_params); DeviceObj.prepare_session(); DeviceObj.release_session(); - Log.Debug("Sensor detected to port" + serial_number); + _logger.LogDebug("Sensor detected to port" + serial_number); return true; } catch (Exception e) @@ -430,7 +433,7 @@ private bool TestPort(String serial_number, out bool portAlreadyOpen) if (sensorStatus == ExitCodes.ANOTHER_BOARD_IS_CREATED_ERROR) portAlreadyOpen = true; AddWarning(sensorStatus, " Time: " + DateTime.Now.ToString("h:mm:ss tt") + " WARNING MESSAGE: Error Code: " + sensorStatus); - Log.Exception("Exception: " + e.Message); + _logger.LogError("Exception: " + e.Message); return false; } } @@ -488,7 +491,7 @@ public Dictionary getWarning() } catch (Exception e) { - Log.Exception(e.Message); + _logger.LogError(e.Message); return info; } return info; @@ -544,7 +547,7 @@ public async Task> ScanDevicesAsync(bool paired = true) } catch (Gtec.Unicorn.DeviceException ex) { - Log.Exception($"Error: {ex.Message}"); + _logger.LogError(ex, ex.Message); } return devices; }); @@ -576,9 +579,9 @@ public async Task connectionTestAsync() { #if !SIMULATIONBOARD - Log.Debug($"Selected device: {BCIActuatorSettings.Settings.GTecDeviceName}, trying to connect..."); + _logger.LogDebug($"Selected device: {BCIActuatorSettings.Settings.GTecDeviceName}, trying to connect..."); using Unicorn device = new Unicorn(BCIActuatorSettings.Settings.GTecDeviceName); - Log.Debug($"Device: {device} is connected..."); + _logger.LogDebug($"Device: {device} is connected..."); device.Dispose(); #endif EvtBluetoothResult(BluetoothEvent.SUCCESSFUL_CONNECTION, null); @@ -586,7 +589,7 @@ public async Task connectionTestAsync() } catch (Gtec.Unicorn.DeviceException ex) { - Log.Exception($"Error: {ex.Message}"); + _logger.LogError(ex, ex.Message); Dictionary eventParams = new() { ["error"] = ex.Message @@ -596,7 +599,7 @@ public async Task connectionTestAsync() } catch (Exception ex) { - Log.Exception($"Unexpected error: {ex.Message}"); + _logger.LogError(ex, ex.Message); Dictionary eventParams = new() { ["error"] = ex.Message @@ -615,7 +618,7 @@ public async Task connectionTestAsync() /// Any extra params sent with bluetooth event request public void bluetoothRequestHandler(BluetoothEvent bluetoothEvent, Dictionary eventParams) { - Log.Debug("DAQ_gTecBCI | bluetoothRequestHandler | bluetoothEvent: " + bluetoothEvent.ToString()); + _logger.LogDebug("DAQ_gTecBCI | bluetoothRequestHandler | bluetoothEvent: " + bluetoothEvent.ToString()); switch (bluetoothEvent) { @@ -657,7 +660,7 @@ public override SignalStatus GetStatus(out SignalStatus[] statusSignals) } catch (Exception e) { - Log.Exception("Exception: " + e.Message); + _logger.LogError("Exception: " + e.Message); } } return statusAllSignals; diff --git a/src/Extensions/BCI/Actuators/EEGDataAcquisition/FileManagement/FileWriter.cs b/src/Extensions/BCI/Actuators/EEGDataAcquisition/FileManagement/FileWriter.cs index e075462a..a29fef9d 100644 --- a/src/Extensions/BCI/Actuators/EEGDataAcquisition/FileManagement/FileWriter.cs +++ b/src/Extensions/BCI/Actuators/EEGDataAcquisition/FileManagement/FileWriter.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; @@ -24,6 +25,7 @@ namespace ACAT.Extensions.BCI.Actuators.EEG.EEGDataAcquisition.FileManagement { public class FileWriter { + private static readonly ILogger _logger = LogManager.GetLogger(); /// /// Directory for session /// @@ -172,8 +174,7 @@ private void WriteDataToFile(StreamWriter sw, double[,] data) } catch (Exception ex) { - Log.Exception(data[channelIdx, sampleIdx].ToString()); - Log.Exception(ex.ToString()); + _logger.LogError(ex, "Error writing data at channel {ChannelIdx}, sample {SampleIdx}, value: {Value}", channelIdx, sampleIdx, data[channelIdx, sampleIdx]); } if (channelIdx < numChannels - 1) stringBuilder.Append(", "); @@ -188,7 +189,7 @@ private void WriteDataToFile(StreamWriter sw, double[,] data) } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex, "Error writing data to file"); } finally { diff --git a/src/Extensions/BCI/Actuators/EEGProcessing/DataLoader/DataParser.cs b/src/Extensions/BCI/Actuators/EEGProcessing/DataLoader/DataParser.cs index a70f5321..9b76827f 100644 --- a/src/Extensions/BCI/Actuators/EEGProcessing/DataLoader/DataParser.cs +++ b/src/Extensions/BCI/Actuators/EEGProcessing/DataLoader/DataParser.cs @@ -12,6 +12,7 @@ using ACAT.Core.Utility; using ACAT.Extensions.BCI.Actuators.EEG.EEGSettings; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; @@ -21,6 +22,8 @@ namespace ACAT.Extensions.BCI.Actuators.EEG.EEGProcessing.DataLoader [Serializable] public class DataParser { + private static readonly ILogger _logger = LoggerFactory.Create(builder => builder.AddConsole()).CreateLogger(); + /// /// Offset added to targets /// (this parameter is typically set in settings) @@ -264,8 +267,7 @@ public void ParseData(double[,] inputData, int[] triggerData, List markerVa } catch (Exception e) { - //Log.Exception(e.getClass().getName()); e) - Log.Debug(e.Message); + _logger.LogDebug("{Message}", e.Message); } } @@ -288,7 +290,7 @@ public void ParseData(double[,] inputData, int[] triggerData, List markerVa remainingData = new double[numColumns, numRemainingSamples]; string txtLog = "Get " + numRemainingSamples + " remaining data. Input data with Num Columns: " + numColumns + " Num Samples: " + numSamples; - Log.Debug(txtLog); + _logger.LogDebug("{Message}", txtLog); try { for (int columnIdx = 0; columnIdx < numColumns; columnIdx++) @@ -296,11 +298,11 @@ public void ParseData(double[,] inputData, int[] triggerData, List markerVa remainingData[columnIdx, i] = allData[columnIdx, startingSampleIdx + i]; txtLog = "Remaining dat. Num Columns: " + remainingData.GetLength(0) + " Num samples: " + remainingData.GetLength(1); - Log.Debug(txtLog); + _logger.LogDebug("{Message}", txtLog); } catch (Exception e) { - Log.Exception(e.Message); + _logger.LogError(e, "{Message}", e.Message); } } diff --git a/src/Extensions/BCI/Actuators/EEGProcessing/DecisionMaker.cs b/src/Extensions/BCI/Actuators/EEGProcessing/DecisionMaker.cs index 950995f3..d126b42b 100644 --- a/src/Extensions/BCI/Actuators/EEGProcessing/DecisionMaker.cs +++ b/src/Extensions/BCI/Actuators/EEGProcessing/DecisionMaker.cs @@ -16,6 +16,8 @@ using ACAT.Core.Utility; using ACAT.Extensions.BCI.Actuators.EEG.EEGProcessing.Utilities; using ACAT.Extensions.BCI.Actuators.EEG.EEGSettings; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; using System; using System.Collections.Generic; using System.IO; @@ -24,6 +26,9 @@ namespace ACAT.Extensions.BCI.Actuators.EEG.EEGProcessing { public class DecisionMaker { + private static readonly ILogger _nullLogger = NullLogger.Instance; + private readonly ILogger _logger; + // ************ Params and objects loaded at init /// @@ -91,8 +96,9 @@ public class DecisionMaker /// /// Constructor (Params read from settings) /// - public DecisionMaker(string TrainedClassifiersFilePath) + public DecisionMaker(string TrainedClassifiersFilePath, ILogger logger = null) { + _logger = logger ?? _nullLogger; enableLanguageModelProbabilities = false; // by default (actuator will set flag for different type of LM probabilities) maxNumberOfSequences = BCIActuatorSettings.Settings.Classifier_MaxDecisionSequences; confidenceThreshold = BCIActuatorSettings.Settings.Classifier_ConfidenceThreshold; @@ -110,23 +116,24 @@ public DecisionMaker(string TrainedClassifiersFilePath) { TrainedClassifiersObj = BinaryUtils.ReadFromBinaryFile(TrainedClassifiersFilePath); - string logTxt = "Decision maker created with calibration file " + TrainedClassifiersObj.trainedClassifiersSessionID + ". AUC: " + TrainedClassifiersObj.meanAUC + " Max number of sequences: " + maxNumberOfSequences + ". Confidence threshold: " + confidenceThreshold; - Log.Debug(logTxt); + _logger.LogDebug("Decision maker created with calibration file {SessionID}. AUC: {MeanAUC} Max number of sequences: {MaxSequences}. Confidence threshold: {ConfidenceThreshold}", + TrainedClassifiersObj.trainedClassifiersSessionID, TrainedClassifiersObj.meanAUC, maxNumberOfSequences, confidenceThreshold); } else - Log.Debug("Calibration file does not exist"); + _logger.LogDebug("Calibration file does not exist"); } catch (Exception e) { - Log.Exception(e.Message); + _logger.LogError(e, "Exception in DecisionMaker constructor"); } } /// /// Constructor (Params as input) /// - public DecisionMaker(int maxNumberOfSeqs, float confThreshold) + public DecisionMaker(int maxNumberOfSeqs, float confThreshold, ILogger logger = null) { + _logger = logger ?? _nullLogger; maxNumberOfSequences = maxNumberOfSeqs; confidenceThreshold = confThreshold; @@ -135,7 +142,7 @@ public DecisionMaker(int maxNumberOfSeqs, float confThreshold) if (File.Exists(filePath)) TrainedClassifiersObj = BinaryUtils.ReadFromBinaryFile(filePath); else - Log.Debug("Calibration file does not exist"); + _logger.LogDebug("Calibration file does not exist"); _likelihoodsTarget = new Dictionary>(); _likelihoodsNontarget = new Dictionary>(); @@ -193,7 +200,7 @@ public void ComputePosteriorProbs(double[,] data2parse, List markerValues, TrainedClassifiersObj.UpdateChannelSubset(availableChannels); List markerValuesString = markerValues.ConvertAll(x => x.ToString()); - Log.Debug("Reduce data w/ " + data2parse.Length + " samples and " + String.Join(", ", markerValuesString) + " markers"); + _logger.LogDebug("Reduce data w/ {SampleCount} samples and {Markers} markers", data2parse.Length, String.Join(", ", markerValuesString)); // Append incomplete data and markers double[,] allDataToParse; @@ -203,7 +210,7 @@ public void ComputePosteriorProbs(double[,] data2parse, List markerValues, // Concatenate markers allMarkersToParse = incompleteMarkers; allMarkersToParse.AddRange(markerValues); - Log.Debug("Markers concatenated. Total markers: " + allMarkersToParse.Count); + _logger.LogDebug("Markers concatenated. Total markers: {TotalMarkers}", allMarkersToParse.Count); // Concatenate data int numColumns = data2parse.GetLength(0); @@ -217,7 +224,8 @@ public void ComputePosteriorProbs(double[,] data2parse, List markerValues, for (int sampleIdx = 0; sampleIdx < data2parse.GetLength(1); sampleIdx++) allDataToParse[columnIdx, sampleIdx + incompleteData.GetLength(1)] = data2parse[columnIdx, sampleIdx]; } - Log.Debug("Data concatenated. Total data: " + allDataToParse.GetLength(1) + " containing " + incompleteData.GetLength(1) + " from previous iterations and " + data2parse.GetLength(1) + " from current iteration"); + _logger.LogDebug("Data concatenated. Total data: {TotalData} containing {PreviousData} from previous iterations and {CurrentData} from current iteration", + allDataToParse.GetLength(1), incompleteData.GetLength(1), data2parse.GetLength(1)); } else { @@ -229,14 +237,14 @@ public void ComputePosteriorProbs(double[,] data2parse, List markerValues, List trialScores = TrainedClassifiersObj.Reduce(allDataToParse, allMarkersToParse, flashingSequence, out incompleteData, out incompleteMarkers); if (trialScores != null) - Log.Debug("Data reduced " + trialScores.Count + " trial scores found"); + _logger.LogDebug("Data reduced {TrialScoreCount} trial scores found", trialScores.Count); else - Log.Debug("Data not reduced. Scores returned null. Will reduce in new iteration"); + _logger.LogDebug("Data not reduced. Scores returned null. Will reduce in new iteration"); List appendedTrialScores = new(); if (incompleteTrialScores != null) { - Log.Debug("Creating appended list with " + incompleteTrialScores.Count + " scores"); + _logger.LogDebug("Creating appended list with {IncompleteScoreCount} scores", incompleteTrialScores.Count); appendedTrialScores = new List(incompleteTrialScores); } if (trialScores != null && trialScores.Count > 0) @@ -244,18 +252,20 @@ public void ComputePosteriorProbs(double[,] data2parse, List markerValues, // Append trial scores if (appendedTrialScores != null && appendedTrialScores.Count > 0) { - Log.Debug("Adding current " + trialScores.Count + " scores to appended trialscores"); + _logger.LogDebug("Adding current {CurrentScoreCount} scores to appended trialscores", trialScores.Count); appendedTrialScores.AddRange(trialScores); if (incompleteTrialScores != null) - Log.Debug("Appended trialScores. Total scores: " + appendedTrialScores.Count + " with " + incompleteTrialScores.Count + " from previous iteration and " + trialScores.Count + " from current iteration"); + _logger.LogDebug("Appended trialScores. Total scores: {TotalScores} with {PreviousScores} from previous iteration and {CurrentScores} from current iteration", + appendedTrialScores.Count, incompleteTrialScores.Count, trialScores.Count); else - Log.Debug("Appended trialScores. Total scores: " + appendedTrialScores.Count + " with 0 from previous iteration and " + trialScores.Count + " from current iteration"); + _logger.LogDebug("Appended trialScores. Total scores: {TotalScores} with 0 from previous iteration and {CurrentScores} from current iteration", + appendedTrialScores.Count, trialScores.Count); } else { appendedTrialScores = trialScores; - Log.Debug("No trial scores from previous iterations. Current " + trialScores.Count + " will be used"); + _logger.LogDebug("No trial scores from previous iterations. Current {CurrentScoreCount} will be used", trialScores.Count); } } @@ -268,22 +278,22 @@ public void ComputePosteriorProbs(double[,] data2parse, List markerValues, // List completeTrialScores = new List(appendedTrialScores); List completeTrialScores = new(appendedTrialScores.GetRange(0, flashingSequence.Count)); - Log.Debug("Calculating probabilities for " + completeTrialScores.Count + " scores corresponding to " + flashingSequence.Count + " trials"); + _logger.LogDebug("Calculating probabilities for {CompleteScoreCount} scores corresponding to {TrialCount} trials", completeTrialScores.Count, flashingSequence.Count); ComputePosteriorProbs(completeTrialScores.ToArray(), flashingSequence, out decided, out decidedButtonID, out repetition, out posteriorProbs, out eegProbs, out nextCharacterProbs); - Log.Debug("Posterior probabilities calculated. Repetition: " + repetition + " , Decided: " + decided + " , Decided button ID: " + decidedButtonID); + _logger.LogDebug("Posterior probabilities calculated. Repetition: {Repetition} , Decided: {Decided} , Decided button ID: {DecidedButtonID}", repetition, decided, decidedButtonID); if (appendedTrialScores.Count > flashingSequence.Count) { incompleteTrialScores = new List(appendedTrialScores.GetRange(flashingSequence.Count, appendedTrialScores.Count - flashingSequence.Count)); - Log.Debug("Incomplete Trial scores " + incompleteTrialScores.Count + " saved for next iteration"); + _logger.LogDebug("Incomplete Trial scores {IncompleteScoreCount} saved for next iteration", incompleteTrialScores.Count); } } else { if (trialScores != null) - Log.Debug("Incomplete trial scores. Expected: " + flashingSequence.Count + " Calculated: " + trialScores.Count + " Waiting for new repetition"); + _logger.LogDebug("Incomplete trial scores. Expected: {ExpectedCount} Calculated: {CalculatedCount} Waiting for new repetition", flashingSequence.Count, trialScores.Count); else - Log.Debug("Incomplete trial scores. Expected: " + flashingSequence.Count + " Calculated: 0 Waiting for new repetition"); + _logger.LogDebug("Incomplete trial scores. Expected: {ExpectedCount} Calculated: 0 Waiting for new repetition", flashingSequence.Count); if (incompleteTrialScores == null) incompleteTrialScores = appendedTrialScores; @@ -294,7 +304,7 @@ public void ComputePosteriorProbs(double[,] data2parse, List markerValues, } catch (Exception e) { - Log.Exception(e.Message); + _logger.LogError(e, "Exception in ComputePosteriorProbs"); } } @@ -371,7 +381,7 @@ public void ComputePosteriorProbs(double[] trialScores, Dictionary t // Add next character probabilities if (enableLanguageModelProbabilities && _languageModelProbabilities != null) { - Log.Debug("Adding language model probabilities"); + _logger.LogDebug("Adding language model probabilities"); if (_languageModelProbabilities.ContainsKey(buttonID)) { buttonLogPosterior += Math.Log(Math.Sqrt(_languageModelProbabilities[buttonID])); @@ -427,8 +437,7 @@ public void ComputePosteriorProbs(double[] trialScores, Dictionary t decided = false; if (maxProb > confidenceThreshold || _sequenceCount == maxNumberOfSequences) { - string txtLog = "Decision made. Repetition: " + _sequenceCount + " Probability: " + maxProb; - Log.Debug(txtLog); + _logger.LogDebug("Decision made. Repetition: {SequenceCount} Probability: {MaxProb}", _sequenceCount, maxProb); decided = true; _sequenceCount = 0; _likelihoodsTarget = new Dictionary>(); @@ -440,14 +449,14 @@ public void ComputePosteriorProbs(double[] trialScores, Dictionary t } if (posteriorProbs == null || posteriorProbs.Count == 0) - Log.Debug("Zero posteriorProbs"); + _logger.LogDebug("Zero posteriorProbs"); } else - Log.Debug("Error when computing probabilities, trialScore is null or 0, returning null and restarting algorithm"); + _logger.LogDebug("Error when computing probabilities, trialScore is null or 0, returning null and restarting algorithm"); } catch (Exception e) { - Log.Exception(e.Message); + _logger.LogError(e, "Exception in ComputePosteriorProbs"); } } @@ -456,7 +465,7 @@ public void ComputePosteriorProbs(double[] trialScores, Dictionary t /// public void RestartProbabilities() { - Log.Debug("Restarting probabilities"); + _logger.LogDebug("Restarting probabilities"); _sequenceCount = 0; _likelihoodsTarget = new Dictionary>(); _likelihoodsNontarget = new Dictionary>(); diff --git a/src/Extensions/BCI/Actuators/EEGProcessing/DimReduction/DimReductChanSel.cs b/src/Extensions/BCI/Actuators/EEGProcessing/DimReduction/DimReductChanSel.cs index 4811b03d..143e692a 100644 --- a/src/Extensions/BCI/Actuators/EEGProcessing/DimReduction/DimReductChanSel.cs +++ b/src/Extensions/BCI/Actuators/EEGProcessing/DimReduction/DimReductChanSel.cs @@ -12,6 +12,7 @@ using ACAT.Core.Utility; using Accord.Math; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; @@ -21,11 +22,14 @@ namespace ACAT.Extensions.BCI.Actuators.EEG.EEGProcessing.DimReduction [Serializable] public class DimReductChanSel { + [NonSerialized] + private readonly ILogger _logger; // Subset of channels public int[] channelSubset; public DimReductChanSel(int[] pChannelSubset) { + _logger = LoggingConfiguration.CreateLogger(); channelSubset = pChannelSubset; } @@ -85,7 +89,7 @@ public bool Reduce(List inputData, out List outputData) } catch (Exception e) { - Log.Exception(e.Message); + _logger?.LogError(e, "Error during dimension reduction processing"); } return true; } diff --git a/src/Extensions/BCI/Actuators/EEGProcessing/FeatureExtraction.cs b/src/Extensions/BCI/Actuators/EEGProcessing/FeatureExtraction.cs index 3a0b89c9..2daf1ddd 100644 --- a/src/Extensions/BCI/Actuators/EEGProcessing/FeatureExtraction.cs +++ b/src/Extensions/BCI/Actuators/EEGProcessing/FeatureExtraction.cs @@ -23,6 +23,7 @@ using ACAT.Extensions.BCI.Actuators.EEG.EEGSettings; using ACAT.Extensions.BCI.Common.BCIControl; using Accord.Math; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.IO; @@ -33,6 +34,8 @@ namespace ACAT.Extensions.BCI.Actuators.EEG.EEGProcessing [Serializable] public class FeatureExtraction { + private readonly ILogger _logger; + /// /// Path of the trained classifiers /// @@ -161,8 +164,9 @@ public class FeatureExtraction /// /// /// - public FeatureExtraction(Dictionary pSymbolsInGroups, CalibrationParametersForSection pCalibrationParameters, int numRows = 6, int numCols = 6, bool isRowCol = true) + public FeatureExtraction(Dictionary pSymbolsInGroups, CalibrationParametersForSection pCalibrationParameters, int numRows = 6, int numCols = 6, bool isRowCol = true, ILogger logger = null) { + _logger = logger; // Get parameters from settings offsetTarget = BCIActuatorSettings.Settings.Calibration_OffsetTarget; windowDuration = BCIActuatorSettings.Settings.FeatureExtraction_WindowDurationInMs / 1000f; @@ -357,8 +361,7 @@ public float Learn(String sessionID) // Train classifiers trainedClassifiersSessionID = sessionID; - string txtLog = "Read data " + sessionID; - Log.Debug(txtLog); + _logger?.LogDebug("Read data {SessionID}", sessionID); FileReader fileReaderObj = new(); fileReaderObj.ReadDataAndMarkersFromFiles(sessionID, out rawData, out triggerSignal, out markerValues, out sessionDirectory); //fileReaderObj.ReadDataAndMarkersFromTestFiles(out rawData, out triggerSignal, out markerValues, out sessionDirectory, @@ -366,20 +369,19 @@ public float Learn(String sessionID) int numSamples = rawData.GetLength(1); int numColumns = rawData.GetLength(0); - txtLog = "Raw data read " + sessionID + " Num samples: " + numSamples + " Num channels: " + numColumns; - Log.Debug(txtLog); + _logger?.LogDebug("Raw data read {SessionID} Num samples: {NumSamples} Num channels: {NumColumns}", sessionID, numSamples, numColumns); //Plots.plotTriggerSignal(triggerSignal); // 1.2 Filter - Log.Debug("Filtering data"); + _logger?.LogDebug("Filtering data"); _BandPassFilter.FilterData(rawData, triggerSignal, out double[,] filteredData, out int[] delayedTriggerSignal); - Log.Debug("Data filtered"); + _logger?.LogDebug("Data filtered"); //Plots.plotSignal(filteredData, 1); // 1.2 Parse file - Log.Debug("Parsing data"); + _logger?.LogDebug("Parsing data"); _DataParserObj.ParseData(filteredData, delayedTriggerSignal, markerValues, _symbolsInGroups, out inputData, out trialTargetness, out trialLabels, out List trialGroups, out List targetLabels, out _, out _, true); // ===================== 2. Preprocessing ========================== @@ -387,8 +389,7 @@ public float Learn(String sessionID) { int[] trialTargetnessArray = trialTargetness.ToArray(); - txtLog = "Data parsed. Num trials: " + inputData.Count; - Log.Debug(txtLog); + _logger?.LogDebug("Data parsed. Num trials: {Count}", inputData.Count); // 2.1 Select subset of channels (if applicable) _DimReductChannelSelectionObj.Reduce(inputData, out inputData); @@ -400,21 +401,18 @@ public float Learn(String sessionID) // ===================== 3. Feature selection ========================== // 3.1 PCA (reduce dimensions) - Log.Debug("Applying PCA"); + _logger?.LogDebug("Applying PCA"); _DimReductPCAObj.Learn(inputData); _DimReductPCAObj.Reduce(inputData, out trialData); // 3.2 RDA (transform to scores using crossValidation) - txtLog = "Crossvalidation with " + trialData.Count + " trials"; - Log.Debug(txtLog); + _logger?.LogDebug("Crossvalidation with {Count} trials", trialData.Count); scores = _CrossValidationObj.CrossValidate(_DimReductRDAObj, trialData, trialTargetness); // Calculate performance - txtLog = "Calculating AUC for " + scores.Count + " trials"; - Log.Debug(txtLog); + _logger?.LogDebug("Calculating AUC for {Count} trials", scores.Count); meanAUC = ClassifierUtils.CalculateAUC(scores, trialTargetnessArray, out double[] TPrate, out double[] FPrate); - txtLog = "AUC " + meanAUC; - Log.Debug(txtLog); + _logger?.LogDebug("AUC {MeanAUC}", meanAUC); // 3.3 Train RDA with all data (scores for target/nontarget class distributions are calculated with crossV) _DimReductRDAObj.Learn(trialData, trialTargetness.ToList()); @@ -452,7 +450,7 @@ public float Learn(String sessionID) } catch (Exception e) { - Log.Exception(e.Message); + _logger?.LogError(e, e.Message); meanAUC = -1; // Save Error in file @@ -475,26 +473,26 @@ public List Reduce(List inputData) { // ===================== 2. Preprocessing ========================== // 2.1 Select subset of channels (if applicable) - Log.Debug("Reducing number of channels for " + inputData.Count + " trials"); + _logger?.LogDebug("Reducing number of channels for {Count} trials", inputData.Count); _DimReductChannelSelectionObj.Reduce(inputData, out inputData); - Log.Debug("Number of channels reduced to " + _DimReductChannelSelectionObj.channelSubset.Length); + _logger?.LogDebug("Number of channels reduced to {Length}", _DimReductChannelSelectionObj.channelSubset.Length); // 2.2 Downsample - Log.Debug("Downsampling"); + _logger?.LogDebug("Downsampling"); _DimReductDownSampleObj.Reduce(inputData, out inputData); - Log.Debug("Data downsampled by " + _DimReductDownSampleObj.downsampleRate + " for " + inputData.Count + " trials"); + _logger?.LogDebug("Data downsampled by {Rate} for {Count} trials", _DimReductDownSampleObj.downsampleRate, inputData.Count); // ===================== 3. Feature selection ========================== // PCA (reduce dimensions)" - Log.Debug("Starting PCA.reduce for " + inputData.Count + " trials"); + _logger?.LogDebug("Starting PCA.reduce for {Count} trials", inputData.Count); _DimReductPCAObj.Reduce(inputData, out List trialData); - Log.Debug("PCA reduced for " + trialData.Count); + _logger?.LogDebug("PCA reduced for {Count}", trialData.Count); // RDA (obtain 1-dimensional scores) - Log.Debug("Starting RDA.reduce for " + trialData.Count + " trials"); + _logger?.LogDebug("Starting RDA.reduce for {Count} trials", trialData.Count); _DimReductRDAObj.Reduce(trialData, out List scores); - Log.Debug("RDA reduced " + scores.Count + " scores"); + _logger?.LogDebug("RDA reduced {Count} scores", scores.Count); return scores; } @@ -514,18 +512,18 @@ public List Reduce(double[,] allData, List markerValues, Dictionary int numSamples = allData.GetLength(1); int numColumns = allData.GetLength(0); incompleteData = null; - Log.Debug("Parsing data from brainflow " + numSamples + " samples and " + numColumns + " columns"); + _logger?.LogDebug("Parsing data from brainflow {NumSamples} samples and {NumColumns} columns", numSamples, numColumns); _DataParserObj.ParseDataFromBrainflow(allData, out double[,] rawData, out int[] triggerSignal, out _); numSamples = rawData.GetLength(1); - Log.Debug("Data parsed " + numSamples + " samples."); + _logger?.LogDebug("Data parsed {NumSamples} samples.", numSamples); _BandPassFilter.FilterData(rawData, triggerSignal, out double[,] filteredData, out int[] delayedTriggerSignal); // 1.2 Parse file - Log.Debug("Parsing data"); + _logger?.LogDebug("Parsing data"); _DataParserObj.ParseData(filteredData, delayedTriggerSignal, markerValues, symbolsInGroups, out List trialData, out _, out _, out List trialMarkers, out _, out int incompleteSampleIdx, out incompleteMarkerValues); - Log.Debug("Data parsed for " + trialMarkers.Count + " markers and" + trialData.Count + " trials"); + _logger?.LogDebug("Data parsed for {MarkersCount} markers and {TrialsCount} trials", trialMarkers.Count, trialData.Count); // trialLabels: if singleBox paradigm: trialLabels[trial1][boxID] // if RC paradigm: trialLabels[trial1][box1 box2 box3] containing all highlighted boxes @@ -534,13 +532,13 @@ public List Reduce(double[,] allData, List markerValues, Dictionary { int startSampleIdx = incompleteSampleIdx - _BandPassFilter.GetGroupDelay(); incompleteData = _DataParserObj.GetRemaining(allData, startSampleIdx); - Log.Debug("Incomplete data remaining with " + incompleteData.GetLength(1) + " columns and " + incompleteData.GetLength(0) + " samples for " + trialMarkers.Count + " markers"); + _logger?.LogDebug("Incomplete data remaining with {Columns} columns and {Samples} samples for {MarkersCount} markers", incompleteData.GetLength(1), incompleteData.GetLength(0), trialMarkers.Count); } if (trialData.Count > 0 && trialData.Count == trialMarkers.Count) { trialScores = Reduce(trialData); - Log.Debug("Reduced " + trialScores.Count + " trials found"); + _logger?.LogDebug("Reduced {Count} trials found", trialScores.Count); } return trialScores; // will return null if can't be computed } diff --git a/src/Extensions/BCI/Actuators/gTec_SensorUI/SensorForm.cs b/src/Extensions/BCI/Actuators/gTec_SensorUI/SensorForm.cs index 0b3449ea..6e637512 100644 --- a/src/Extensions/BCI/Actuators/gTec_SensorUI/SensorForm.cs +++ b/src/Extensions/BCI/Actuators/gTec_SensorUI/SensorForm.cs @@ -362,8 +362,8 @@ public void TaskStartStopDataProcessing(OnboardingUserState state) /// private void startStopProcessDataTimer(bool startProcessDataTimer, OnboardingUserState state) { - Log.Debug("startStopProcessDataTimer | startProcessDataTimer: " + startProcessDataTimer.ToString() + - " | state: " + state.ToString()); + _logger.LogDebug("startStopProcessDataTimer | startProcessDataTimer: {StartProcessDataTimer} | state: {State}", + startProcessDataTimer, state); if (startProcessDataTimer) { diff --git a/src/Extensions/BCI/Actuators/gTec_SensorUI/UserControlBCISignalCheck.cs b/src/Extensions/BCI/Actuators/gTec_SensorUI/UserControlBCISignalCheck.cs index 6a82ceb6..f47aadc4 100644 --- a/src/Extensions/BCI/Actuators/gTec_SensorUI/UserControlBCISignalCheck.cs +++ b/src/Extensions/BCI/Actuators/gTec_SensorUI/UserControlBCISignalCheck.cs @@ -318,9 +318,9 @@ public void updateSignalStatus(double[,] latestUnfilteredData, double[,] latestF public void initializeBCISignalCheck(DAQ_gTecBCI gtecbci, bool maxTimeHasElapsed, double maxTimeMins, double minElapsedPrevSignalQualityCheck, bool userPassedLastSignalQualityCheck) { gTecBCI = gtecbci; - Log.Debug(String.Format("initializeBCISignalCheck | maxTimeHasElapsed: {0}, " + - "minElapsedPrevSignalQualityCheck: {1}, userPassedLastSignalQualityCheck: {2}", - maxTimeHasElapsed.ToString(), minElapsedPrevSignalQualityCheck.ToString(), userPassedLastSignalQualityCheck.ToString())); + _logger?.LogDebug("initializeBCISignalCheck | maxTimeHasElapsed: {MaxTimeHasElapsed}, " + + "minElapsedPrevSignalQualityCheck: {MinElapsedPrevSignalQualityCheck}, userPassedLastSignalQualityCheck: {UserPassedLastSignalQualityCheck}", + maxTimeHasElapsed, minElapsedPrevSignalQualityCheck, userPassedLastSignalQualityCheck); // Get / inititalize variables related to board config used in data processing _indEegChannels = gTecBCI.indEegChannels; @@ -338,10 +338,10 @@ public void initializeBCISignalCheck(DAQ_gTecBCI gtecbci, bool maxTimeHasElapsed for (int i = 0; i < _indEegChannels.Length; i++) _indEegChannels_str += (_indEegChannels[i].ToString() + ", "); - Log.Debug(String.Format("initializeBCISignalCheck | _numChannels: {0}, " + "_samplingRate: {1}, " + - "_scaleIdx: {2}, _bufSize: {3}\n" + - "_indEegChannels_str: {4}", - _numChannels.ToString(), _samplingRate.ToString(), _scaleIdx.ToString(), _bufSize.ToString(), _indEegChannels_str)); + _logger?.LogDebug("initializeBCISignalCheck | _numChannels: {NumChannels}, " + "_samplingRate: {SamplingRate}, " + + "_scaleIdx: {ScaleIdx}, _bufSize: {BufSize}\n" + + "_indEegChannels_str: {IndEegChannelsStr}", + _numChannels, _samplingRate, _scaleIdx, _bufSize, _indEegChannels_str); // Set some text fields to smaller font size for 125 scaling (100 scaling is default) var tuple = DualMonitor.GetDisplayWidthAndScaling(); @@ -643,7 +643,7 @@ private void tabControlElectrodeQuality_SelectedIndexChanged(object sender, Even highlightSelectedTab(0); } - Log.Debug("tabControlElectrodeQuality_SelectedIndexChanged" + " | _currentBCISignalCheckMode: " + _currentBCISignalCheckMode.ToString()); + _logger?.LogDebug("tabControlElectrodeQuality_SelectedIndexChanged | _currentBCISignalCheckMode: {CurrentBCISignalCheckMode}", _currentBCISignalCheckMode); } /// @@ -696,7 +696,7 @@ private void GetGraphYLims(int scaleIdx, out int yLimMin, out int yLimMax) } catch (Exception e) { - Log.Exception(e.Message); + _logger?.LogError(e, "Exception in GetGraphYLims"); } yLimMax = scale; diff --git a/src/Extensions/BCI/Actuators/gTec_SensorUI/UserControlErrorBluetoothDisconnected.cs b/src/Extensions/BCI/Actuators/gTec_SensorUI/UserControlErrorBluetoothDisconnected.cs index ab0f015a..95a5282c 100644 --- a/src/Extensions/BCI/Actuators/gTec_SensorUI/UserControlErrorBluetoothDisconnected.cs +++ b/src/Extensions/BCI/Actuators/gTec_SensorUI/UserControlErrorBluetoothDisconnected.cs @@ -190,7 +190,7 @@ public void bluetoothResultHandler(DAQ_gTecBCI.BluetoothEvent bluetoothEvent, Di } catch (Exception ex) { - Log.Exception("UserControlErrorBluetoothDisconnected | bluetoothResultHandler | Exception: " + ex.Message); + _logger.LogError(ex, "UserControlErrorBluetoothDisconnected | bluetoothResultHandler | Exception"); } })); diff --git a/src/Extensions/BCI/Actuators/gTec_SensorUI/gTecDeviceTester.cs b/src/Extensions/BCI/Actuators/gTec_SensorUI/gTecDeviceTester.cs index 75d56ebd..dac76fd7 100644 --- a/src/Extensions/BCI/Actuators/gTec_SensorUI/gTecDeviceTester.cs +++ b/src/Extensions/BCI/Actuators/gTec_SensorUI/gTecDeviceTester.cs @@ -459,7 +459,7 @@ private void buttonNextHandler(String buttonNextName) if (!userPassedLastSignalQualityCheck) { // Exit anyways regardless of signal quality result - Log.Debug("User did not pass signal quality check but set testing parameter to ignore result. Exiting as if user did pass the check"); + _logger.LogDebug("User did not pass signal quality check but set testing parameter to ignore result. Exiting as if user did pass the check"); } } @@ -494,7 +494,7 @@ private void buttonNextHandler(String buttonNextName) else { // Display message to user prompting them to improve signal quality before moving on - Log.Debug("Not exiting | Did not pass signal quality criteria"); + _logger.LogDebug("Not exiting | Did not pass signal quality criteria"); bool confirmed = ConfirmBoxOneOption.ShowDialog(StringResources.SignalQualityChecksFailed + "\n" + StringResources.Youneedtocompleteboth + "\n“ +Impedance” tests and get good signals to" + "\n" + "proceed" + "\n" + StringResources.Pleaserefertotheuserguideforhelp, "", StringResources.OK, _mainForm, false); @@ -512,7 +512,7 @@ private void buttonNextHandler(String buttonNextName) /// private void runSignalCheckIfRequired() { - Log.Debug("gTecDeviceTester | runSignalCheckIfRequired"); + _logger.LogDebug("gTecDeviceTester | runSignalCheckIfRequired"); // Always check time last impedance test was run (all electrodes tested) and update UI accordingly long timestampPrevImpedanceTest = BCIActuatorSettings.Settings.SignalQuality_TimeOfLastImpedanceCheck; @@ -523,8 +523,8 @@ private void runSignalCheckIfRequired() bool maxTimeHasElapsed = false; if (minElapsedPrevSignalQualityCheck >= maxTimeMins) maxTimeHasElapsed = true; - Log.Debug(String.Format("runSignalCheckIfRequired | timestampPrevImpedanceTest: {0}, timestampNow: {1}, secDiff: {2}", timestampPrevImpedanceTest.ToString(), timestampNow.ToString(), secDiff.ToString())); - Log.Debug(String.Format("minElapsedPrevSignalQualityCheck: {0}, maxTimeMins: {1}, maxTimeHasElapsed: {2}", minElapsedPrevSignalQualityCheck.ToString(), maxTimeMins.ToString(), maxTimeHasElapsed.ToString())); + _logger.LogDebug("runSignalCheckIfRequired | timestampPrevImpedanceTest: {TimestampPrevImpedanceTest}, timestampNow: {TimestampNow}, secDiff: {SecDiff}", timestampPrevImpedanceTest, timestampNow, secDiff); + _logger.LogDebug("minElapsedPrevSignalQualityCheck: {MinElapsedPrevSignalQualityCheck}, maxTimeMins: {MaxTimeMins}, maxTimeHasElapsed: {MaxTimeHasElapsed}", minElapsedPrevSignalQualityCheck, maxTimeMins, maxTimeHasElapsed); // Always check if user passed the last overall signal quality check that was executed // If max time has not passed, but user did not pass their most recent overall signal quality check, diff --git a/src/Extensions/BCI/Actuators/openBCI_SensorUI/OpenBCIDeviceTester.cs b/src/Extensions/BCI/Actuators/openBCI_SensorUI/OpenBCIDeviceTester.cs index 539e8e63..0b3eae00 100644 --- a/src/Extensions/BCI/Actuators/openBCI_SensorUI/OpenBCIDeviceTester.cs +++ b/src/Extensions/BCI/Actuators/openBCI_SensorUI/OpenBCIDeviceTester.cs @@ -191,6 +191,7 @@ public enum DeviceTestingState /// public OpenBCIDeviceTester() { + _logger = ACATExtension.GetLogger(); // Do not call init function here // Call init function after creating object of this class and linking any necessary event handler (ex: EvtBCIDeviceTestingCompleted) @@ -202,12 +203,12 @@ public OpenBCIDeviceTester() /// public void initialize() { - Log.Debug("OpenBCIDeviceTester | initialize"); + _logger.LogDebug("Initializing OpenBCIDeviceTester"); // Close main form if for some reason it's opened at this point if (_mainForm != null && _mainForm.IsDisposed == false) { - Log.Debug("OpenBCIDeviceTester | _mainForm != null && _mainForm.IsDisposed == false"); + _logger.LogDebug("Main form is open and not disposed, closing it"); _mainForm.Close(); _mainForm.Dispose(); } @@ -219,7 +220,7 @@ public void initialize() } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, "Exception during initialization"); } if (ExitOnboardingEarly) @@ -317,7 +318,7 @@ public void Exit(bool lostConnection) /// private void _mainForm_EvtFormClosed(object sender, FormClosedEventArgs e) { - Log.Debug("OpenBCIDeviceTester | _mainForm_EvtFormClosed | _deviceTestingState: " + _deviceTestingState.ToString()); + _logger.LogDebug("Main form closed with DeviceTestingState: {DeviceTestingState}", _deviceTestingState); if (_deviceTestingState == DeviceTestingState.ReceivedBCIError_LostDataConnection) { @@ -375,9 +376,10 @@ private void startSignalQualityTestingState(DeviceTestingState newDeviceTestingS bool maxTimeHasElapsed = false; if (minElapsedPrevSignalQualityCheck >= maxTimeMins) maxTimeHasElapsed = true; - Log.Debug(String.Format("startSignalQualityTestingState | newDeviceTestingState == DeviceTestingState.BCISignalCheckStartRequired" + - "\ntimestampPrevImpedanceTest: {0}, timestampNow: {1}, secDiff: {2}", timestampPrevImpedanceTest.ToString(), timestampNow.ToString(), secDiff.ToString())); - Log.Debug(String.Format("minElapsedPrevSignalQualityCheck: {0}, maxTimeMins: {1}, maxTimeHasElapsed: {2}", minElapsedPrevSignalQualityCheck.ToString(), maxTimeMins.ToString(), maxTimeHasElapsed.ToString())); + _logger.LogDebug("Signal quality test timing - PrevTest: {PrevTestTimestamp}, Now: {NowTimestamp}, SecDiff: {SecDiff}", + timestampPrevImpedanceTest, timestampNow, secDiff); + _logger.LogDebug("Signal quality elapsed check - MinElapsed: {MinElapsed}min, MaxTime: {MaxTime}min, HasElapsed: {HasElapsed}", + minElapsedPrevSignalQualityCheck, maxTimeMins, maxTimeHasElapsed); // Always check if user passed the last overall signal quality check that was executed // If max time has not passed, but user did not pass their most recent overall signal quality check, @@ -457,7 +459,7 @@ private void startSignalQualityTestingState(DeviceTestingState newDeviceTestingS /// private void finishSignalQualityTestingState(DeviceTestingState currentDeviceTestingState) { - Log.Debug("OpenBCIDeviceTester | finishSignalQualityTestingState | currentDeviceTestingState: " + currentDeviceTestingState.ToString()); + _logger.LogDebug("Finishing signal quality testing with state: {DeviceTestingState}", currentDeviceTestingState); // Next button selected from BCI signal check start required screen if (currentDeviceTestingState == DeviceTestingState.BCISignalCheckStartRequired) @@ -533,20 +535,20 @@ private void finishSignalQualityTestingState(DeviceTestingState currentDeviceTes 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("BCIActuatorSettings.Testing_IgnoreSignalTestResultDuringOnboarding = true"); + _logger.LogDebug("Ignoring signal test result during onboarding (Testing_IgnoreSignalTestResultDuringOnboarding enabled)"); exitBCIOnboarding = true; if (!userPassedLastSignalQualityCheck) { // Exit anyways regardless of signal quality result - Log.Debug("User did not pass signal quality check but set testing parameter to ignore result. Exiting as if user did pass the check"); + _logger.LogDebug("User did not pass signal quality check but testing parameter is set to ignore - exiting anyway"); } } @@ -584,7 +586,7 @@ private void finishSignalQualityTestingState(DeviceTestingState currentDeviceTes else { // Display message to user prompting them to improve signal quality before moving on - Log.Debug("Not exiting | Did not pass signal quality criteria"); + _logger.LogDebug("Not exiting - user did not pass signal quality criteria"); _ = ConfirmBoxOneOption.ShowDialog("Signal Quality Checks Failed or Incomplete" + "\nYou need to complete both “Railing” and\n“Impedance” tests and get good signals to\nproceed" + "\nPlease refer to the user guide for help", "", StringResources.OK, _mainForm, false); @@ -617,7 +619,7 @@ private void _mainForm_EvtButtonRetestClicked(object sender) /// private void retestBCIConnections() { - Log.Debug("retestBCIConnections(). deviceTestingState: " + _deviceTestingState); + _logger.LogDebug("Retesting BCI connections with state: {DeviceTestingState}", _deviceTestingState); // If already on Optical sensor error screen -> retest button does not check all BCI connections from the beginning, tests optical sensor right away // _requestTestTriggerBox goes to correct user control when test completed @@ -666,7 +668,7 @@ private void _mainForm_EvtButtonExitClicked_DEBUG(object sender) try { _Testing_useSensor_TestIndex += 1; - Log.Debug("OpenBCIDeviceTester | _mainForm_EvtButtonExitClicked_DEBUG | _Testing_useSensor_TestIndex: " + _Testing_useSensor_TestIndex.ToString()); + _logger.LogDebug("DEBUG Exit button clicked, test index: {TestIndex}", _Testing_useSensor_TestIndex); if (_Testing_useSensor_TestIndex < _DebugStates.Length) { DeviceTestingState newState = _DebugStates[_Testing_useSensor_TestIndex]; @@ -698,7 +700,7 @@ private void _mainForm_EvtButtonExitClicked_DEBUG(object sender) } catch (Exception e) { - Log.Exception("_mainForm_EvtButtonExitClicked_DEBUG exception: " + e.ToString()); + _logger.LogError(e, "Exception in DEBUG exit button handler"); } } @@ -745,7 +747,7 @@ public async Task startBCIDeviceTesting(int initialDelaySec = 0) } } - Log.Debug("startBCIDeviceTesting | Calling InitDAQ()"); + _logger.LogDebug("Starting BCI device testing - calling InitDAQ()"); // Call async function which connects to BCI sensor + starts task that controls TriggerBox flashing and tests optical sensor by request if (_Testing_useSensor == true) @@ -790,7 +792,7 @@ private void changeTriggerBoxColor(Color color) } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, "Exception in changeTriggerBoxColor"); } } @@ -809,7 +811,7 @@ private void changeDeviceTestingState(DeviceTestingState state) } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, "Exception in changeDeviceTestingState"); } } @@ -820,7 +822,7 @@ private void changeDeviceTestingState(DeviceTestingState state) /// public async Task InitDAQ() // Original function { - Log.Debug("InitDAQ()"); + _logger.LogDebug("Initializing DAQ"); _initDAQTaskStopped = false; while (!_endTasks) @@ -834,31 +836,31 @@ public async Task InitDAQ() // Original function BaseDAQ.ExitCodes exitCode = ((DAQ_OpenBCI)_daqInstance).getUsbDongleConnected(); if (exitCode == BaseDAQ.ExitCodes.UNABLE_TO_OPEN_PORT_ERROR) { - Log.Debug("OpenBCIDeviceTester | _deviceTestingState = DeviceTestingState.ReceivedBCIError_UsbDongle"); + _logger.LogDebug("USB dongle connection error detected, state: ReceivedBCIError_UsbDongle"); _deviceTestingState = DeviceTestingState.ReceivedBCIError_UsbDongle; changeDeviceTestingState(DeviceTestingState.ReceivedBCIError_UsbDongle); } else { - Log.Debug("InitDAQ | exitCode: " + exitCode.ToString()); + _logger.LogDebug("InitDAQ exit code: {ExitCode}", exitCode); bool success = _daqInstance.Start(""); if (success) { - Log.Debug("DAQ_OpenBCI.Start() | true"); + _logger.LogDebug("DAQ_OpenBCI started successfully"); // Check latency setting of port is set correctly bool latencyPortOk = ((DAQ_OpenBCI)_daqInstance).CheckLatencyPort(); if (latencyPortOk) { - Log.Debug("DAQ_OpenBCI.CheckLatencyPort() | true"); + _logger.LogDebug("DAQ_OpenBCI latency port check passed"); if (_daqInstance.deviceInitialized) { - Log.Debug("DAQ_OpenBCI.deviceInitialized | true"); + _logger.LogDebug("DAQ_OpenBCI device initialized successfully"); // BCI impedence / railing integration - debugging option, go straight to signal check screens without checking optical sensor - Log.Debug("_Testing_BCIOnboardingIgnoreOpticalSensorChecks == true"); + _logger.LogDebug("Testing mode enabled - ignoring optical sensor checks during onboarding"); // Go to first stage of signal quality checking process startSignalQualityTestingState(DeviceTestingState.BCISignalCheckStartRequired); @@ -866,12 +868,12 @@ public async Task InitDAQ() // Original function } else { - Log.Debug("DAQ_OpenBCI.deviceInitialized | false"); + _logger.LogDebug("DAQ_OpenBCI device initialization failed"); } } else { - Log.Debug("DAQ_OpenBCI.CheckLatencyPort() | false | _deviceTestingState = DeviceTestingState.ReceivedBCIError_PortConfig"); + _logger.LogDebug("DAQ_OpenBCI latency port check failed, state: ReceivedBCIError_PortConfig"); _daqInstance.Stop(); _deviceTestingState = DeviceTestingState.ReceivedBCIError_PortConfig; changeDeviceTestingState(DeviceTestingState.ReceivedBCIError_PortConfig); @@ -879,7 +881,7 @@ public async Task InitDAQ() // Original function } else { - Log.Debug("OpenBCIDeviceTester | _deviceTestingState = DeviceTestingState.ReceivedBCIError_CytonBoard"); + _logger.LogDebug("Cyton board connection error detected, state: ReceivedBCIError_CytonBoard"); _deviceTestingState = DeviceTestingState.ReceivedBCIError_CytonBoard; changeDeviceTestingState(DeviceTestingState.ReceivedBCIError_CytonBoard); } @@ -890,7 +892,7 @@ public async Task InitDAQ() // Original function } _initDAQTaskStopped = true; - Log.Debug("InitDAQ | hole | _initDAQ_TaskStopped = true"); + _logger.LogDebug("InitDAQ task stopped"); // return; } diff --git a/src/Extensions/BCI/Actuators/openBCI_SensorUI/SensorForm.cs b/src/Extensions/BCI/Actuators/openBCI_SensorUI/SensorForm.cs index a67084fe..fc602448 100644 --- a/src/Extensions/BCI/Actuators/openBCI_SensorUI/SensorForm.cs +++ b/src/Extensions/BCI/Actuators/openBCI_SensorUI/SensorForm.cs @@ -20,6 +20,7 @@ using System.Windows.Forms; using static ACAT.Extensions.BCI.Actuators.openBCISensorUI.OpenBCIDeviceTester; using static ACAT.Extensions.BCI.Actuators.openBCISensorUI.UserControlBCISignalCheck; +using Microsoft.Extensions.Logging; namespace ACAT.Extensions.BCI.Actuators.openBCISensorUI { @@ -28,6 +29,8 @@ namespace ACAT.Extensions.BCI.Actuators.openBCISensorUI /// public partial class SensorForm : Form { + private static ILogger _logger; + /// /// User control displayed while trying to connect to sensor /// @@ -210,7 +213,7 @@ public SensorForm(DeviceTestingState initialState) /// public void changeDeviceTestingState(DeviceTestingState state) { - Log.Debug("SensorForm | changeDeviceTestingState | state: " + state.ToString()); + _logger?.LogDebug("SensorForm | changeDeviceTestingState | state: {State}", state); DeviceTestingState prevDeviceTestingState = _mainFormDeviceTestingState; UserControl newUserControl = null; @@ -339,8 +342,8 @@ public void changeDeviceTestingState(DeviceTestingState state) /// private void startStopProcessDataTimer(bool startProcessDataTimer, DeviceTestingState state) { - Log.Debug("startStopProcessDataTimer | startProcessDataTimer: " + startProcessDataTimer.ToString() + - " | state: " + state.ToString()); + _logger?.LogDebug("startStopProcessDataTimer | startProcessDataTimer: {StartTimer} | state: {State}", + startProcessDataTimer, state); if (startProcessDataTimer) { @@ -367,11 +370,11 @@ private void startStopProcessDataTimer(bool startProcessDataTimer, DeviceTesting } 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"); } } else @@ -388,7 +391,7 @@ private void startStopProcessDataTimer(bool startProcessDataTimer, DeviceTesting } catch (Exception e) { - Log.Exception("startStopProcessDataTimer | Exception: " + e.ToString()); + _logger?.LogError(e, "startStopProcessDataTimer | Exception"); } } } @@ -430,7 +433,7 @@ private void ProcessDataSignalCheck_Tick(object sender, EventArgs e) // Check flag to stop this particular timer if (_stopTimers || OpenBCIDeviceTester._endSignalCheckTimer) { - Log.Debug("ProcessDataSignalCheck_Tick | _stopTimers | OpenBCIDeviceTester._endSignalCheckTimer"); + _logger?.LogDebug("ProcessDataSignalCheck_Tick | _stopTimers | OpenBCIDeviceTester._endSignalCheckTimer"); startStopProcessDataTimer(false, DeviceTestingState.ExitBCITesting); return; } @@ -465,7 +468,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; } @@ -543,7 +546,7 @@ private void buttonRetest_Click(object sender, EventArgs e) /// private void modifyUserControlsForDebugMode() { - Log.Debug("SensorForm | modifyUserControlsForDebugMode"); + _logger?.LogDebug("SensorForm | modifyUserControlsForDebugMode"); _userControlTestBCIConnections.buttonExit.AutoSize = true; _userControlTestBCIConnections.buttonExit.Font = new Font("Montserrat Medium", 13F); diff --git a/src/Extensions/BCI/Actuators/openBCI_SensorUI/UserControlBCISignalCheck.cs b/src/Extensions/BCI/Actuators/openBCI_SensorUI/UserControlBCISignalCheck.cs index 3bf3f971..04e430a1 100644 --- a/src/Extensions/BCI/Actuators/openBCI_SensorUI/UserControlBCISignalCheck.cs +++ b/src/Extensions/BCI/Actuators/openBCI_SensorUI/UserControlBCISignalCheck.cs @@ -23,6 +23,7 @@ using ACAT.Extensions.BCI.Common.BCIControl; using Accord.Math; using brainflow; +using Microsoft.Extensions.Logging; //using SharpDX.Direct2D1; using System; using System.Collections.Generic; @@ -39,6 +40,11 @@ namespace ACAT.Extensions.BCI.Actuators.openBCISensorUI /// public partial class UserControlBCISignalCheck : UserControl { + /// + /// Logger instance for this class + /// + private readonly ILogger _logger; + /// /// The DAQ instance for OpenBCI /// @@ -278,6 +284,9 @@ public UserControlBCISignalCheck(String stepId) { InitializeComponent(); + // Initialize logger + _logger = ACATLogManager.CreateLogger(); + // Initialize the DAQ instance _daqInstance = DAQFactory.CreateDAQ(DAQDeviceType.OpenBCI); @@ -614,7 +623,7 @@ public void changeSignalCheckMode(BCISignalCheckMode mode) } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, ex.Message); } } @@ -627,7 +636,7 @@ public void changeSignalCheckMode(BCISignalCheckMode mode) public void initializeBCISignalCheck(bool maxTimeHasElapsed, double maxTimeMins, double minElapsedPrevSignalQualityCheck, bool userPassedLastSignalQualityCheck) { - Log.Debug(String.Format("initializeBCISignalCheck | maxTimeHasElapsed: {0}, " + + _logger.LogDebug(String.Format("initializeBCISignalCheck | maxTimeHasElapsed: {0}, " + "minElapsedPrevSignalQualityCheck: {1}, userPassedLastSignalQualityCheck: {2}", maxTimeHasElapsed.ToString(), minElapsedPrevSignalQualityCheck.ToString(), userPassedLastSignalQualityCheck.ToString())); @@ -669,7 +678,7 @@ public void initializeBCISignalCheck(bool maxTimeHasElapsed, double maxTimeMins, for (int i = 0; i < _indEegChannels.Length; i++) _indEegChannels_str += (_indEegChannels[i].ToString() + ", "); - Log.Debug(String.Format("initializeBCISignalCheck | _numChannels: {0}, " + "_samplingRate: {1}, " + + _logger.LogDebug(String.Format("initializeBCISignalCheck | _numChannels: {0}, " + "_samplingRate: {1}, " + "_scaleIdx: {2}, _bufSize: {3}\n" + "_indEegChannels_str: {4}", _numChannels.ToString(), _samplingRate.ToString(), _scaleIdx.ToString(), _bufSize.ToString(), _indEegChannels_str)); @@ -845,7 +854,7 @@ public void initializeBCISignalCheck(bool maxTimeHasElapsed, double maxTimeMins, //private async Task StartImpedanceTesting() private void StartImpedanceTesting() { - Log.Debug("StartImpedanceTesting"); + _logger.LogDebug("StartImpedanceTesting"); if (!_runImpedanceTestingCycle && _daqInstance.deviceInitialized) { @@ -855,7 +864,7 @@ private void StartImpedanceTesting() ////// Before running impedance tests /////// //// Stop streaming on board, does not consistently register commands while streaming - Log.Debug("Stop streaming"); + _logger.LogDebug("Stop streaming"); ((DAQ_OpenBCI)_daqInstance).Stop_Streaming(); Thread.Sleep(50); @@ -866,7 +875,7 @@ private void StartImpedanceTesting() EEGChannel currentEegChannel = _eegChannels[_currentImpedanceTestElectrodeIndex]; String electrodeName = currentEegChannel._electrodeName; - Log.Debug("StartImpedanceTesting loop | _currentImpedanceTestElectrodeIndex: " + _currentImpedanceTestElectrodeIndex.ToString() + + _logger.LogDebug("StartImpedanceTesting loop | _currentImpedanceTestElectrodeIndex: " + _currentImpedanceTestElectrodeIndex.ToString() + " | electrodeName: " + electrodeName.ToString()); String cmdStartElectrodeImpedanceTest = currentEegChannel.ImpedanceTestingEnableCmd; @@ -884,7 +893,7 @@ private void StartImpedanceTesting() _daqInstance.GetData(); // Clear buffer //// Send enable electrode Impedance testing commands - Log.Debug(String.Format("Sending enable electrode {0} Impedance testing command: {1}", electrodeName, cmdStartElectrodeImpedanceTest)); + _logger.LogDebug(String.Format("Sending enable electrode {0} Impedance testing command: {1}", electrodeName, cmdStartElectrodeImpedanceTest)); ((DAQ_OpenBCI)_daqInstance).Config_Board(cmdStartElectrodeImpedanceTest); Thread.Sleep(750); @@ -892,7 +901,7 @@ private void StartImpedanceTesting() _daqInstance.deviceInitialized = true; //// Send start streaming - Log.Debug("Start streaming"); + _logger.LogDebug("Start streaming"); ((DAQ_OpenBCI)_daqInstance).Start_Streaming(); Thread.Sleep(50); @@ -910,15 +919,15 @@ private void StartImpedanceTesting() _daqInstance.deviceInitialized = false; //// Stop streaming - Log.Debug("Stop streaming"); + _logger.LogDebug("Stop streaming"); ((DAQ_OpenBCI)_daqInstance).Stop_Streaming(); Thread.Sleep(50); // Send command to disable impedance testing for specific electrode - Log.Debug(String.Format("Sending disable electrode {0} impedance testing command: {1}", electrodeName, cmdEndElectrodeImpedanceTest)); + _logger.LogDebug(String.Format("Sending disable electrode {0} impedance testing command: {1}", electrodeName, cmdEndElectrodeImpedanceTest)); ((DAQ_OpenBCI)_daqInstance).Config_Board(cmdEndElectrodeImpedanceTest); Thread.Sleep(750); - Log.Debug("Completed impedance testing electrode: " + _currentImpedanceTestElectrodeIndex.ToString()); + _logger.LogDebug("Completed impedance testing electrode: " + _currentImpedanceTestElectrodeIndex.ToString()); // Reset back color of impedance result button in Impedance testing page to transparent Invoke(new Action(() => @@ -933,7 +942,7 @@ private void StartImpedanceTesting() _currentImpedanceTestElectrodeIndex = 0; if (BCIActuatorSettings.Settings.SignalQuality_StopImpedanceTestAfterOneCycle) { - Log.Debug("SignalQuality_StopImpedanceTestAfterOneCycle = true | Stopping impedance testing"); + _logger.LogDebug("SignalQuality_StopImpedanceTestAfterOneCycle = true | Stopping impedance testing"); try { Invoke(new Action(() => @@ -948,7 +957,7 @@ private void StartImpedanceTesting() } catch (Exception ex) { - Log.Exception(ex.Message); + _logger.LogError(ex, ex.Message); } } } @@ -958,18 +967,18 @@ private void StartImpedanceTesting() //// Do opposite of what was done at the beginning on this function to bring board back to default state // Reset board to default parameters - Log.Debug("Send command to reset board"); + _logger.LogDebug("Send command to reset board"); ((DAQ_OpenBCI)_daqInstance).Reset_Board(); // Run multiple times? Thread.Sleep(750); // Tested 750 - is ok - Log.Debug("Send command to reset board"); + _logger.LogDebug("Send command to reset board"); ((DAQ_OpenBCI)_daqInstance).Reset_Board(); Thread.Sleep(4500); - Log.Debug("Calling Stop()"); + _logger.LogDebug("Calling Stop()"); _daqInstance.Stop(); Thread.Sleep(250); // Tested 250 - is ok - Log.Debug("Calling Start()"); + _logger.LogDebug("Calling Start()"); _daqInstance.Start(); // Also starts streaming // Stopped Impedance testing cycle, update UI accordingly @@ -990,7 +999,7 @@ private void StartImpedanceTesting() // save this time as time of last signal quality check completed if (_AllElectrodesOverallSignalQualityResult.allElectrodesUpdatedWithinSession == true) { - Log.Debug("Saving current time as SignalQuality_TimeOfLastImpedanceCheck"); + _logger.LogDebug("Saving current time as SignalQuality_TimeOfLastImpedanceCheck"); BCIActuatorSettings.Settings.SignalQuality_TimeOfLastImpedanceCheck = DateTimeOffset.Now.ToUnixTimeSeconds(); BCIActuatorSettings.Save(); // Save settings } @@ -1029,7 +1038,7 @@ public void ProcessDataSignalCheck(double[,] data, double[,] filteredData) } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, ex.Message); } // Removed automatic optical sensor checks below for now - it's likely the optical sensor is still @@ -1100,7 +1109,7 @@ private void updateRailingTestResult(int chIdx, int railingResultPercentage, boo } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, ex.Message); } } @@ -1161,7 +1170,7 @@ private void updateImpedanceResult(int chIdx, int impedanceResult, bool update_u } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, ex.Message); } } @@ -1213,7 +1222,7 @@ public bool updateSignalQualityResult(int chIdx) } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, ex.Message); } return ret; @@ -1260,7 +1269,7 @@ private void updateSignalChart(int channelIndex, double[] samples, bool scale_pl } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, ex.Message); } } @@ -1296,7 +1305,7 @@ private static bool AppendDataToBuffer2(double[,] data, double[,] inBuffer, int } catch (Exception e) { - Log.Exception(e.Message); + _logger.LogError(e, e.Message); } return result; } @@ -1339,7 +1348,7 @@ private void tabControlElectrodeQuality_SelectedIndexChanged(object sender, Even } } - Log.Debug("tabControlElectrodeQuality_SelectedIndexChanged" + + _logger.LogDebug("tabControlElectrodeQuality_SelectedIndexChanged" + " | _impedanceTestingRunning: " + _impedanceTestingRunning.ToString() + " | _currentBCISignalCheckMode: " + _currentBCISignalCheckMode.ToString()); } @@ -1375,7 +1384,7 @@ private void highlightSelectedTab(int tabControlIndex) } catch (Exception e) { - Log.Exception(e.Message); + _logger.LogError(e, e.Message); } } @@ -1420,7 +1429,7 @@ private void GetGraphYLimits(int scaleIdx, out int yLimMin, out int yLimMax) } catch (Exception e) { - Log.Exception(e.Message); + _logger.LogError(e, e.Message); } yLimMax = scale; @@ -1434,13 +1443,13 @@ private void GetGraphYLimits(int scaleIdx, out int yLimMin, out int yLimMax) /// private void buttonTestImpedance_Click(object sender, EventArgs e) { - Log.Debug("buttonTestImpedance_Click | _currentImpedanceTestElectrodeIndex: " + _currentImpedanceTestElectrodeIndex.ToString()); + _logger.LogDebug("buttonTestImpedance_Click | _currentImpedanceTestElectrodeIndex: " + _currentImpedanceTestElectrodeIndex.ToString()); if (_runImpedanceTestingCycle) { try { - Log.Debug("Impedance cyclical testing running. Stopping process..."); + _logger.LogDebug("Impedance cyclical testing running. Stopping process..."); buttonTestImpedance.Enabled = false; buttonTestImpedance.BackColor = Color.Gray; updateImpedanceTestingStateLabels(ImpedanceTestingState.STOP_IN_PROGRESS); @@ -1450,7 +1459,7 @@ private void buttonTestImpedance_Click(object sender, EventArgs e) } catch (Exception ex) { - Log.Exception(ex.Message); + _logger.LogError(ex, ex.Message); } } else if (!_runImpedanceTestingCycle) @@ -1458,7 +1467,7 @@ private void buttonTestImpedance_Click(object sender, EventArgs e) // Start impedance testing try { - Log.Debug("Impedances testing not running. Starting process..."); + _logger.LogDebug("Impedances testing not running. Starting process..."); buttonTestImpedance.Text = "Stop"; buttonNext.Enabled = false; buttonNext.BackColor = Color.Gray; @@ -1468,7 +1477,7 @@ private void buttonTestImpedance_Click(object sender, EventArgs e) } catch (Exception ex) { - Log.Exception(ex.Message); + _logger.LogError(ex, ex.Message); } // Start thread doing impedance testing @@ -1566,7 +1575,7 @@ private void updateImpedanceTestingStateLabels(ImpedanceTestingState impedanceTe } catch (Exception ex) { - Log.Exception(ex.Message); + _logger.LogError(ex, ex.Message); } } @@ -1641,7 +1650,7 @@ public void handle125Scaling() } catch (Exception ex) { - Log.Exception(ex.Message); + _logger.LogError(ex, ex.Message); } } } diff --git a/src/Extensions/Default/Actuators/CameraActuator/AutoCalibrateForm.cs b/src/Extensions/Default/Actuators/CameraActuator/AutoCalibrateForm.cs index 01be5ae6..ce65bcb8 100644 --- a/src/Extensions/Default/Actuators/CameraActuator/AutoCalibrateForm.cs +++ b/src/Extensions/Default/Actuators/CameraActuator/AutoCalibrateForm.cs @@ -13,6 +13,7 @@ using ACAT.Core.PanelManagement.Utils; using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Windows.Forms; @@ -20,6 +21,7 @@ namespace ACAT.Extensions.Actuators.CameraActuator { internal partial class AutoCalibrateForm : Form { + private static readonly ILogger _logger = LoggingConfiguration.CreateLogger(); private VideoWindowFinder _videoWindowFinder; private readonly CameraActuator _visionActuator; @@ -92,11 +94,11 @@ private void EndCalibration() _videoWindowFinder.Dispose(); } - Log.Debug("Hiding video window"); + _logger.LogDebug("Hiding video window"); CameraSensor.hideVideoWindow(); - Log.Debug("Closing calibform"); + _logger.LogDebug("Closing calibform"); Windows.CloseForm(this); } diff --git a/src/Extensions/Default/Actuators/CameraActuator/CameraActuator.cs b/src/Extensions/Default/Actuators/CameraActuator/CameraActuator.cs index 2146f3c3..42a34d90 100644 --- a/src/Extensions/Default/Actuators/CameraActuator/CameraActuator.cs +++ b/src/Extensions/Default/Actuators/CameraActuator/CameraActuator.cs @@ -227,6 +227,11 @@ public override bool Init() return true; } + public CameraActuator() + { + _logger = LoggingConfiguration.CreateLogger(); + } + /// /// Pause the actuator /// @@ -297,7 +302,7 @@ public override void StartCalibration(RequestCalibrationReason reason) { try { - Log.Debug("Calling UpdateCalibrationstatus"); + _logger.LogDebug("Calling UpdateCalibrationstatus"); if (_autoCalibrateForm != null) { @@ -305,16 +310,16 @@ public override void StartCalibration(RequestCalibrationReason reason) _autoCalibrateForm = null; } - Log.Debug("Calling NotifyStartCalibration"); + _logger.LogDebug("Calling NotifyStartCalibration"); Context.AppActuatorManager.NotifyStartCalibration(new CalibrationNotifyEventArgs(true, false)); if (reason == RequestCalibrationReason.SensorInitiated) { - Log.Debug("Calling new Calibform"); + _logger.LogDebug("Calling new Calibform"); _autoCalibrateForm = new AutoCalibrateForm(this); - Log.Debug("Calling new Calibform show dialog"); + _logger.LogDebug("Calling new Calibform show dialog"); var form = Context.AppPanelManager.GetCurrentForm() as Form; if (form != null) @@ -328,7 +333,7 @@ public override void StartCalibration(RequestCalibrationReason reason) { _autoCalibrateForm.ShowDialog(); } - Log.Debug("Returned from Calibform show dialog"); + _logger.LogDebug("Returned from Calibform show dialog"); _autoCalibrateForm = null; } @@ -342,10 +347,10 @@ public override void StartCalibration(RequestCalibrationReason reason) } } - Log.Debug("Calling NotifyEndCalibration"); + _logger.LogDebug("Calling NotifyEndCalibration"); Context.AppActuatorManager.NotifyEndCalibration(); - Log.Debug("Calling OnEndCalibration"); + _logger.LogDebug("Calling OnEndCalibration"); OnEndCalibration(); if (_cameraActuatorInitInProgress) @@ -357,7 +362,7 @@ public override void StartCalibration(RequestCalibrationReason reason) } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex, ex.Message); } } @@ -453,21 +458,21 @@ internal void setHeadMovementSensitivity(int value) internal void setVisionSettings() { - Log.Debug("Setting vision parameters..."); + _logger.LogDebug("Setting vision parameters..."); - Log.Debug("HeadMovementSensitivity: " + CameraActuatorSettings.HeadMovementSensitivity); + _logger.LogDebug("HeadMovementSensitivity: {HeadMovementSensitivity}", CameraActuatorSettings.HeadMovementSensitivity); setHeadMovementSensitivity(CameraActuatorSettings.HeadMovementSensitivity); - Log.Debug("CheekTwitchSensitivity: " + CameraActuatorSettings.CheekTwitchSensitivity); + _logger.LogDebug("CheekTwitchSensitivity: {CheekTwitchSensitivity}", CameraActuatorSettings.CheekTwitchSensitivity); setCheekTwitchSensitivity(CameraActuatorSettings.CheekTwitchSensitivity); - Log.Debug("EyebrowRaiseSensitivity: " + CameraActuatorSettings.EyebrowRaiseSensitivity); + _logger.LogDebug("EyebrowRaiseSensitivity: {EyebrowRaiseSensitivity}", CameraActuatorSettings.EyebrowRaiseSensitivity); setEyebrowRaiseSensitivity(CameraActuatorSettings.EyebrowRaiseSensitivity); - Log.Debug("CheekTwitchHoldTime: " + CameraActuatorSettings.CheekTwitchHoldTime); + _logger.LogDebug("CheekTwitchHoldTime: {CheekTwitchHoldTime}", CameraActuatorSettings.CheekTwitchHoldTime); setCheekTwitchHoldTime(CameraActuatorSettings.CheekTwitchHoldTime); - Log.Debug("EyebrowRaiseHoldTime: " + CameraActuatorSettings.EyebrowRaiseHoldTime); + _logger.LogDebug("EyebrowRaiseHoldTime: {EyebrowRaiseHoldTime}", CameraActuatorSettings.EyebrowRaiseHoldTime); setEyebrowRaiseHoldTime(CameraActuatorSettings.EyebrowRaiseHoldTime); } @@ -481,7 +486,7 @@ protected override void Dispose(bool disposing) { try { - Log.Verbose(); + _logger.LogTrace("Dispose"); if (disposing) { @@ -562,7 +567,7 @@ private void callbackFromVision(string text) { var gesture = String.Empty; - Log.Debug("Received msg: " + text); + _logger.LogDebug("Received msg: {Message}", text); IActuatorSwitch actuatorSwitch = parseActuatorMsgAndGetSwitch(text, ref gesture); @@ -593,27 +598,27 @@ private void callbackFromVision(string text) { IsCalibrating = true; - Log.Debug("Received CALIB_START"); + _logger.LogDebug("Received CALIB_START"); EvtCalibrationStart?.Invoke(this, new EventArgs()); if (!_cameraActuatorInitInProgress && !_calibrateAndTestInProgress) { - Log.Debug("Calling RequestCalibration"); + _logger.LogDebug("Calling RequestCalibration"); RequestCalibration(_calibrateAndTestInProgress ? RequestCalibrationReason.AppRequested : RequestCalibrationReason.SensorInitiated); - Log.Debug("Returned from RequestCalibration"); + _logger.LogDebug("Returned from RequestCalibration"); } } catch (Exception ex) { - Log.Exception("Exception " + ex); + _logger.LogError(ex, ex.Message); } } else if (gesture == "CALIB_END") // end camera calibration { - Log.Debug("CALIB_END"); + _logger.LogDebug("CALIB_END"); IsCalibrating = false; @@ -785,21 +790,18 @@ private void visionThread() } catch (SEHException seh) { - Log.Exception("acatVision threw a SEHException: " + seh.ToString()); - Log.Exception(seh); + _logger.LogError(seh, "acatVision threw a SEHException"); } catch (AccessViolationException ave) { - Log.Exception("acatVision threw an AccessViolationException: " + ave.ToString()); - Log.Exception(ave); + _logger.LogError(ave, "acatVision threw an AccessViolationException"); } catch (Exception ex) { - Log.Exception("acatVision threw an exception: " + ex.ToString()); - Log.Exception(ex); + _logger.LogError(ex, "acatVision threw an exception"); } - Log.Debug("ACATvision quit"); + _logger.LogDebug("ACATvision quit"); } public bool CalibrationDoneAtleastOnce diff --git a/src/Extensions/Default/Actuators/CameraActuator/ConfigureActuatorForm.cs b/src/Extensions/Default/Actuators/CameraActuator/ConfigureActuatorForm.cs index baf65862..d8f09e9c 100644 --- a/src/Extensions/Default/Actuators/CameraActuator/ConfigureActuatorForm.cs +++ b/src/Extensions/Default/Actuators/CameraActuator/ConfigureActuatorForm.cs @@ -312,7 +312,7 @@ private void CameraActuator_EvtChangeCameraStart(String camera) form.Invoke(new MethodInvoker(delegate { labelPrompt.Text = String.Empty; - Log.Debug("Calling startTimer()"); + _logger.LogDebug("Calling startTimer()"); startTimer(_switchingCamera); })); } diff --git a/src/Extensions/Default/FunctionalAgents/SwitchWindowsAgent/SwitchWindowsScanner.cs b/src/Extensions/Default/FunctionalAgents/SwitchWindowsAgent/SwitchWindowsScanner.cs index b5d82058..2f0fb65b 100644 --- a/src/Extensions/Default/FunctionalAgents/SwitchWindowsAgent/SwitchWindowsScanner.cs +++ b/src/Extensions/Default/FunctionalAgents/SwitchWindowsAgent/SwitchWindowsScanner.cs @@ -49,7 +49,8 @@ namespace ACAT.Extensions.FunctionalAgents.SwitchWindowsAgent "SwitchWindowsScanner", "Switch Windows Scanner")] public partial class SwitchWindowsScanner : GenericScannerForm - { private readonly ILogger _logger; + { + private readonly ILogger _logger; /// /// Enables invoking methods and properties in this form /// @@ -121,6 +122,7 @@ public partial class SwitchWindowsScanner : GenericScannerForm /// public SwitchWindowsScanner() : base() { + _logger = LoggingConfiguration.CreateLogger(); InitializeComponent(); } diff --git a/src/Libraries/ACATCore/AbbreviationsManagement/Abbreviations.cs b/src/Libraries/ACATCore/AbbreviationsManagement/Abbreviations.cs index d2e5e13e..39edfe96 100644 --- a/src/Libraries/ACATCore/AbbreviationsManagement/Abbreviations.cs +++ b/src/Libraries/ACATCore/AbbreviationsManagement/Abbreviations.cs @@ -174,7 +174,7 @@ public bool Load(String abbreviationsFile = null) } else { - Log.Debug("Abbreviation file " + abbreviationsFile + " does not exist"); + _logger?.LogDebug("Abbreviation file {AbbreviationsFile} does not exist", abbreviationsFile); } } catch (Exception ex) @@ -199,7 +199,7 @@ public Abbreviation Lookup(String mnemonic) // do we detect something? if (_abbreviationList.ContainsKey(lookupString)) { - Log.Debug("Yes. Abbreviation list contains : " + lookupString); + _logger?.LogDebug("Yes. Abbreviation list contains : {LookupString}", lookupString); return _abbreviationList[lookupString]; } @@ -258,7 +258,7 @@ public bool Save(String abbreviationsFile) } catch (IOException ex) { - Log.Exception(ex); + _logger?.LogError(ex, ex.Message); retVal = false; } @@ -300,7 +300,7 @@ protected virtual void Dispose(bool disposing) // Check to see if Dispose has already been called. if (!_disposed) { - Log.Verbose(); + _logger?.LogTrace(""); if (disposing) { @@ -332,7 +332,7 @@ private void closeAbbreviationFile(XmlWriter xmlTextWriter) } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger?.LogError(ex, ex.Message); } } @@ -355,7 +355,7 @@ private XmlTextWriter createAbbreviationsFile(String fileName) } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger?.LogError(ex, ex.Message); xmlTextWriter = null; } diff --git a/src/Libraries/ACATCore/ActuatorManagement/ActuatorBase.cs b/src/Libraries/ACATCore/ActuatorManagement/ActuatorBase.cs index 011834fc..28fda26d 100644 --- a/src/Libraries/ACATCore/ActuatorManagement/ActuatorBase.cs +++ b/src/Libraries/ACATCore/ActuatorManagement/ActuatorBase.cs @@ -278,25 +278,25 @@ public bool Load(IEnumerable switchSettings) // enumerate the switches in this actuator and create // each switch object using the switch ClassFactory - Log.Debug("Loading switches"); + _logger?.LogDebug("Loading switches"); foreach (var switchSetting in switchSettings) { var actuatorSwitch = CreateSwitch(); if (actuatorSwitch != null) { - Log.Debug("name=" + switchSetting.Name); + _logger?.LogDebug("Loading switch: {SwitchName}", switchSetting.Name); if (!_switches.ContainsKey(switchSetting.Name)) { if (actuatorSwitch.Load(switchSetting) && actuatorSwitch.Init()) { - Log.Debug("Adding switch " + actuatorSwitch.Name); + _logger?.LogDebug("Adding switch {SwitchName}", actuatorSwitch.Name); actuatorSwitch.Actuator = this; _switches.Add(actuatorSwitch.Name, actuatorSwitch); } } else { - Log.Warn("Warning. Switch " + actuatorSwitch.Name + " defined more than once"); + _logger?.LogWarning("Warning. Switch {SwitchName} defined more than once", actuatorSwitch.Name); } } } @@ -426,7 +426,7 @@ protected virtual void Dispose(bool disposing) // Check to see if Dispose has already been called. if (!_disposed) { - Log.Verbose(); + _logger?.LogTrace("Disposing ActuatorBase"); if (disposing) { @@ -454,8 +454,7 @@ protected SwitchAction getSwitchAction(String action) } catch (Exception e) { - Log.Warn("VisionAcutator switch, invalid action specified " + action); - Log.Exception(e); + _logger?.LogWarning(e, "VisionActuator switch, invalid action specified {Action}", action); } return retVal; @@ -477,7 +476,7 @@ protected 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 CreateSwitch(switchObj); } } @@ -577,7 +576,7 @@ protected IActuatorSwitch parseActuatorMsgAndGetSwitch(String strData, ref Strin bool actuate = true; parsedGesture = String.Empty; - Log.Debug(strData); + _logger?.LogDebug("Parsing actuator message: {Data}", strData); var tokens = strData.Split(';'); foreach (var token in tokens) @@ -696,7 +695,7 @@ protected bool ShowDefaultTryoutDialog() /// should the configure button b e enabled protected void UpdateCalibrationStatus(String caption, String prompt, int timeout = 0, bool enableConfigure = true, string buttonText = "") { - Log.Debug("Calling ActuatorManager.Instance.UpdateCalibrationStatus"); + _logger?.LogDebug("Calling ActuatorManager.Instance.UpdateCalibrationStatus"); ActuatorManager.Instance.UpdateCalibrationStatus(this, caption, prompt, timeout, enableConfigure, buttonText); } @@ -714,7 +713,7 @@ private long parseLong(String val) } catch (Exception e) { - Log.Exception(e); + _logger?.LogError(e, "Exception parsing long value"); } return retVal; diff --git a/src/Libraries/ACATCore/ActuatorManagement/ActuatorEx.cs b/src/Libraries/ACATCore/ActuatorManagement/ActuatorEx.cs index 91ceda9c..aca1893b 100644 --- a/src/Libraries/ACATCore/ActuatorManagement/ActuatorEx.cs +++ b/src/Libraries/ACATCore/ActuatorManagement/ActuatorEx.cs @@ -113,11 +113,11 @@ public void Init() { SourceActuator.Init(); - Log.Debug("Before Wait"); + _logger?.LogDebug("Waiting for initialization to complete"); WaitForInit(); - Log.Debug("After Wait"); + _logger?.LogDebug("Initialization wait completed"); } /// @@ -129,7 +129,7 @@ public void Init() /// should the config button be enabled public void OnEndCalibration(String errorMessage = "", bool enableConfigure = true) { - Log.Verbose(); + _logger?.LogTrace("Ending calibration"); if (!String.IsNullOrEmpty((errorMessage))) { @@ -138,7 +138,7 @@ public void OnEndCalibration(String errorMessage = "", bool enableConfigure = tr OnError(errorMessage, enableConfigure); } - Log.Debug("Calling closeCalibrationForm()"); + _logger?.LogDebug("Closing calibration form"); closeCalibrationForm(); _calibrationDoneEvent.Set(); @@ -189,11 +189,11 @@ public void PostInit() PostInitError = true; } - Log.Debug("Before Wait"); + _logger?.LogDebug("Waiting for post-initialization to complete"); WaitForPostInit(); - Log.Debug("After Wait"); + _logger?.LogDebug("Post-initialization wait completed"); } /// @@ -239,17 +239,17 @@ public void UpdateCalibrationStatus(Windows.WindowPosition position, String capt /// public void WaitForCalibration() { - Log.Debug("Waiting for calibration"); + _logger?.LogDebug("Waiting for calibration to complete"); _calibrationDoneEvent.WaitOne(); - Log.Debug("Calibration event is done"); + _logger?.LogDebug("Calibration event completed"); - Log.Debug("Waiting for calibration configure dialog"); + _logger?.LogDebug("Waiting for calibration configure dialog"); _bgTaskDoneEvent.WaitOne(); - Log.Debug("Calibration configure dialog event is done"); + _logger?.LogDebug("Calibration configure dialog completed"); } /// @@ -257,16 +257,16 @@ public void WaitForCalibration() /// public void WaitForInit() { - Log.Debug("Waiting for initdone"); + _logger?.LogDebug("Waiting for initialization done event"); initDoneEvent.WaitOne(); - Log.Debug("initdone is done"); + _logger?.LogDebug("Initialization done event signaled"); } public void WaitForPostInit() { - Log.Debug("Waiting for postinitdone"); + _logger?.LogDebug("Waiting for post-initialization done event"); postInitDoneEvent.WaitOne(); - Log.Debug("postinitdone is done"); + _logger?.LogDebug("Post-initialization done event signaled"); } /// @@ -293,9 +293,9 @@ private void bgWorker_DoWork(object sender, DoWorkEventArgs e) _formCreatedEvent.Set(); if (calibrationForm != null) { - Log.Debug("Calling calibrationform.ShowDialog"); + _logger?.LogDebug("Showing calibration form dialog"); DialogResult result = calibrationForm.ShowDialog(); - Log.Debug("Result: " + result); + _logger?.LogDebug("Calibration form closed with result: {Result}", result); // user closed the calibration form if (result == DialogResult.Cancel) @@ -306,7 +306,7 @@ private void bgWorker_DoWork(object sender, DoWorkEventArgs e) } else { - Log.Debug("calibration form IS NULL!!!"); + _logger?.LogWarning("Calibration form is null"); } if (calibrationForm != null) @@ -323,7 +323,7 @@ private void bgWorker_DoWork(object sender, DoWorkEventArgs e) /// event args private void bgWorker_RunCompleted(object sender, RunWorkerCompletedEventArgs e) { - Log.Verbose(); + _logger?.LogTrace("Background worker run completed"); _bgTaskDoneEvent.Set(); } @@ -336,7 +336,7 @@ private void closeCalibrationForm() { if (calibrationForm != null) { - Log.Debug("Closing calibration form, calling Dismiss()"); + _logger?.LogDebug("Closing calibration form"); calibrationForm.Dismiss(); calibrationForm = null; } diff --git a/src/Libraries/ACATCore/ActuatorManagement/ActuatorManager.cs b/src/Libraries/ACATCore/ActuatorManagement/ActuatorManager.cs index a3a223df..a33dc51e 100644 --- a/src/Libraries/ACATCore/ActuatorManagement/ActuatorManager.cs +++ b/src/Libraries/ACATCore/ActuatorManagement/ActuatorManager.cs @@ -123,11 +123,11 @@ public class ActuatorManager : IDisposable /// private ActuatorManager(ILogger logger = null) { - _logger = logger; + _logger = logger ?? LoggerFactory.Create(builder => builder.AddConsole()).CreateLogger(); _activeSwitches = new Dictionary(); - // _nonActuateSwitches = new Dictionary(); - // _syncObjectSwitches = new object(); - //} + _nonActuateSwitches = new Dictionary(); + _syncObjectSwitches = new object(); + } /// /// Deleagate for notification of start of calibration by an actuator @@ -358,7 +358,7 @@ public void OnCalibrationCanceled(IActuator source) { source.OnCalibrationCanceled(); - Log.Debug("Entered ActuatorManger.OnCalibrationCanceled"); + _logger.LogDebug("Entered ActuatorManger.OnCalibrationCanceled"); if (isCalibratingActuator(source)) { source.OnCalibrationCanceled(); @@ -387,14 +387,14 @@ public void OnCalibrationPeriodExpired(IActuator source) /// should the "configure" be enabled public void OnEndCalibration(IActuator source, String errorMessage = "", bool enableConfigure = true) { - Log.Verbose(); - Log.Debug("Calling isCalibratingActuator"); + _logger.LogTrace(string.Empty); + _logger.LogDebug("Calling isCalibratingActuator"); if (isCalibratingActuator(source)) { _calibratingActuatorEx.OnEndCalibration(errorMessage, enableConfigure); - Log.Debug("Setting calibratingActuatorEx to null"); + _logger.LogDebug("Setting calibratingActuatorEx to null"); _calibratingActuatorEx = null; } } @@ -481,17 +481,17 @@ public IActuator GetCalibrationSupportedActuator() /// the requesting actuator public void RequestCalibration(IActuator source, RequestCalibrationReason reason) { - Log.Debug("Entered RequestCalibration for " + source.Name); + _logger.LogDebug("Entered RequestCalibration for " + source.Name); if (!source.SupportsCalibration()) { - Log.Debug(source.Name + ": Does not support calibration. returning"); + _logger.LogDebug(source.Name + ": Does not support calibration. returning"); return; } if (calibrationQueue.Contains(source) || isCalibratingActuator(source)) { - Log.Debug("Already queued up or currently processing. Will not enqueue for " + source.Name); + _logger.LogDebug("Already queued up or currently processing. Will not enqueue for " + source.Name); return; } @@ -500,7 +500,7 @@ public void RequestCalibration(IActuator source, RequestCalibrationReason reason if (aex != null) { aex.RequestCalibration(reason); - Log.Debug("Enqueing calibration request for " + source.Name); + _logger.LogDebug("Enqueing calibration request for " + source.Name); calibrationQueue.Enqueue(aex); } @@ -616,15 +616,15 @@ public bool UnregisterSwitch(IActuator actuator, String switchName) /// text of the calibration button public void UpdateCalibrationStatus(IActuator source, String caption, String prompt, int timeout = 0, bool enableConfigure = true, String buttonText = "") { - Log.Debug("Checking if isCalibrationg for " + source.Name); + _logger.LogDebug("Checking if isCalibrationg for " + source.Name); if (isCalibratingActuator(source)) { - Log.Debug("UpdateCalibStatus: Yes it is!!. Calling calibratingActuatorEx.UpdateCalibrationStatus for " + source.Name); + _logger.LogDebug("UpdateCalibStatus: Yes it is!!. Calling calibratingActuatorEx.UpdateCalibrationStatus for " + source.Name); _calibratingActuatorEx.UpdateCalibrationStatus(getCalibrationFormPosition(), caption, prompt, timeout, enableConfigure, buttonText); } else { - Log.Debug("isCalibrating returned False. Actuator is NOT calibrating for " + source.Name); + _logger.LogDebug("isCalibrating returned False. Actuator is NOT calibrating for " + source.Name); } } @@ -762,7 +762,7 @@ protected virtual void Dispose(bool disposing) // Check to see if Dispose has already been called. if (!_disposed) { - Log.Verbose(); + _logger.LogTrace(string.Empty); if (disposing) { @@ -776,11 +776,11 @@ protected virtual void Dispose(bool disposing) if (_thread != null) { - Log.Debug("Calling thread.join"); + _logger.LogDebug("Calling thread.join"); _thread.Join(2000); } - Log.Debug("Exited thread"); + _logger.LogDebug("Exited thread"); if (_actuators != null) { @@ -845,7 +845,7 @@ private void act(IActuatorSwitch switchObj) if (!handled) { - Log.Debug("ACT on Switch " + switchObj.Name); + _logger.LogDebug("ACT on Switch " + switchObj.Name); notifySwitchActivated(switchObj); } } @@ -858,7 +858,7 @@ private void act(IActuatorSwitch switchObj) /// event args private void actuator_EvtSwitchActivated(object sender, ActuatorSwitchEventArgs e) { - Log.Debug("Switch " + e.SwitchObj.Name + " activated"); + _logger.LogDebug("Switch " + e.SwitchObj.Name + " activated"); disambiguateAndAct(e.SwitchObj.Actuate ? _activeSwitches : _nonActuateSwitches, e.SwitchObj); } @@ -870,7 +870,7 @@ private void actuator_EvtSwitchActivated(object sender, ActuatorSwitchEventArgs /// event args private void actuator_EvtSwitchDeactivated(object sender, ActuatorSwitchEventArgs e) { - Log.Debug("Switch " + e.SwitchObj.Name + " deactivated"); + _logger.LogDebug("Switch " + e.SwitchObj.Name + " deactivated"); //disambiguateAndAct(e.SwitchObj); disambiguateAndAct(e.SwitchObj.Actuate ? _activeSwitches : _nonActuateSwitches, e.SwitchObj); } @@ -882,7 +882,7 @@ private void actuator_EvtSwitchDeactivated(object sender, ActuatorSwitchEventArg /// event args private void actuator_EvtSwitchTriggered(object sender, ActuatorSwitchEventArgs e) { - Log.Debug("Switch " + e.SwitchObj.Name + " triggered"); + _logger.LogDebug("Switch " + e.SwitchObj.Name + " triggered"); //disambiguateAndAct(e.SwitchObj); disambiguateAndAct(e.SwitchObj.Actuate ? _activeSwitches : _nonActuateSwitches, e.SwitchObj); } @@ -905,9 +905,9 @@ private void calibrationHandlerThread() { while (!_exitThread) { - Log.Debug("Waiting for item"); + _logger.LogDebug("Waiting for item"); var obj = calibrationQueue.Dequeue(); - Log.Debug("Got item"); + _logger.LogDebug("Got item"); if (obj is String) { @@ -917,12 +917,12 @@ private void calibrationHandlerThread() if (obj is ActuatorEx) { _calibratingActuatorEx = obj as ActuatorEx; - Log.Debug("Before start calib"); + _logger.LogDebug("Before start calib"); var actuator = _calibratingActuatorEx; actuator.StartCalibration(); - Log.Debug("after start calib"); + _logger.LogDebug("after start calib"); - Log.Debug("Waiting for calib for " + actuator.SourceActuator.Name); + _logger.LogDebug("Waiting for calib for " + actuator.SourceActuator.Name); actuator.WaitForCalibration(); } @@ -946,7 +946,7 @@ private void disambiguateAndAct(Dictionary switches, IA if (!switchObj.Enabled) { - Log.Debug("Switch " + switchObj.Name + " is not enabled. Will be ignored"); + _logger.LogDebug("Switch " + switchObj.Name + " is not enabled. Will be ignored"); return; } @@ -957,7 +957,7 @@ private void disambiguateAndAct(Dictionary switches, IA { if (!switches.ContainsKey(switchObj.Name)) { - Log.Debug("SWITCH DOWN switches does not contain " + switchObj.Name + ". adding it"); + _logger.LogDebug("SWITCH DOWN switches does not contain " + switchObj.Name + ". adding it"); // add it to the current list of active switches switches.Add(switchObj.Name, switchObj); @@ -968,7 +968,7 @@ private void disambiguateAndAct(Dictionary switches, IA } else { - Log.Debug("SWITCH DOWN switches already contains " + switchObj.Name); + _logger.LogDebug("SWITCH DOWN switches already contains " + switchObj.Name); } } @@ -981,7 +981,7 @@ private void disambiguateAndAct(Dictionary switches, IA switchObj.RegisterSwitchUp(); if (switches.ContainsKey(switchObj.Name)) { - Log.Debug("SWITCH UP switches contains " + switchObj.Name); + _logger.LogDebug("SWITCH UP switches contains " + switchObj.Name); var activeSwitch = switches[switchObj.Name]; elapsedTime = (activeSwitch != null && activeSwitch.AcceptTimer.IsRunning) ? @@ -989,13 +989,13 @@ private void disambiguateAndAct(Dictionary switches, IA bool accepted = false; - Log.Debug("SWITCH UP Acauate: " + switchObj.Actuate); - Log.Debug("SWITCH UP Acticeswitch != null is " + (activeSwitch != null)); + _logger.LogDebug("SWITCH UP Acauate: " + switchObj.Actuate); + _logger.LogDebug("SWITCH UP Acticeswitch != null is " + (activeSwitch != null)); if (activeSwitch != null) { - Log.Debug("SWITCH UP Accepttimer is running " + activeSwitch.AcceptTimer.IsRunning); - Log.Debug("SWITCH UP Elapsed milli: " + activeSwitch.AcceptTimer.ElapsedMilliseconds); + _logger.LogDebug("SWITCH UP Accepttimer is running " + activeSwitch.AcceptTimer.IsRunning); + _logger.LogDebug("SWITCH UP Elapsed milli: " + activeSwitch.AcceptTimer.ElapsedMilliseconds); } if (switchObj.Actuate && @@ -1003,13 +1003,13 @@ private void disambiguateAndAct(Dictionary switches, IA activeSwitch.AcceptTimer.IsRunning && activeSwitch.AcceptTimer.ElapsedMilliseconds >= CoreGlobals.AppPreferences.MinActuationHoldTime) { - Log.Debug("SWITCH UP Switch accepted! ElapsedMilliseconds: " + activeSwitch.AcceptTimer.ElapsedMilliseconds); + _logger.LogDebug("SWITCH UP Switch accepted! ElapsedMilliseconds: " + activeSwitch.AcceptTimer.ElapsedMilliseconds); accepted = true; switchActivated = switchObj; } else { - Log.Debug("SWITCH UP Switch not found or actuate is false or timer not running or elapsedTime < accept time"); + _logger.LogDebug("SWITCH UP Switch not found or actuate is false or timer not running or elapsedTime < accept time"); } switches.Remove(switchObj.Name); @@ -1027,7 +1027,7 @@ private void disambiguateAndAct(Dictionary switches, IA } else { - Log.Debug("SWITCH UP switches does not contain " + switchObj.Name); + _logger.LogDebug("SWITCH UP switches does not contain " + switchObj.Name); } } @@ -1150,15 +1150,15 @@ private bool init() /// private bool isCalibratingActuator(IActuator actuator) { - Log.Debug("isCalibrating: " + actuator.Name + " calibratingActuatorEx is null:" + (_calibratingActuatorEx == null)); + _logger.LogDebug("isCalibrating: " + actuator.Name + " calibratingActuatorEx is null:" + (_calibratingActuatorEx == null)); if (_calibratingActuatorEx != null) { - Log.Debug("calibratingActuatorEx.SourceActuator: " + _calibratingActuatorEx.SourceActuator.Name); + _logger.LogDebug("calibratingActuatorEx.SourceActuator: " + _calibratingActuatorEx.SourceActuator.Name); } bool retVal = _calibratingActuatorEx != null && _calibratingActuatorEx.SourceActuator == actuator; - Log.Debug("isCalibrating: returning " + retVal); + _logger.LogDebug("isCalibrating: returning " + retVal); return retVal; } @@ -1183,7 +1183,7 @@ private void notifySwitchActivated(IActuatorSwitch switchObj) if (EvtSwitchActivated == null) { - Log.Debug("No subscribers. Returning"); + _logger.LogDebug("No subscribers. Returning"); return; } @@ -1191,7 +1191,7 @@ private void notifySwitchActivated(IActuatorSwitch switchObj) foreach (var del in delegates) { var switchActivated = (ActuatorSwitchEvent)del; - Log.Debug("Calling begininvoke for " + switchObj.Name); + _logger.LogDebug("Calling begininvoke for " + switchObj.Name); switchActivated.BeginInvoke(this, new ActuatorSwitchEventArgs(switchObj), null, null); } } @@ -1223,7 +1223,7 @@ private void notifySwitchHooks(IActuatorSwitch switchObj, ref bool handled) return; } - Log.Verbose(); + _logger.LogTrace(string.Empty); var delegates = EvtSwitchHook.GetInvocationList(); foreach (var del in delegates) diff --git a/src/Libraries/ACATCore/ActuatorManagement/Actuators.cs b/src/Libraries/ACATCore/ActuatorManagement/Actuators.cs index 77b92f5a..aac216b5 100644 --- a/src/Libraries/ACATCore/ActuatorManagement/Actuators.cs +++ b/src/Libraries/ACATCore/ActuatorManagement/Actuators.cs @@ -148,7 +148,7 @@ public IActuator Find(String name) } } - Log.Warn("Could not find actuator by name " + name); + _logger?.LogWarning("Could not find actuator by name {Name}", name); return null; } @@ -163,12 +163,12 @@ public IActuator Find(Type actuatorType) { if (actuatorType.FullName == actuatorEx.SourceActuator.GetType().FullName) { - Log.Debug("Found actuator of type " + actuatorType.Name); + _logger?.LogDebug("Found actuator of type {TypeName}", actuatorType.Name); return actuatorEx.SourceActuator; } } - Log.Warn("Could not find actuator of type " + actuatorType.Name); + _logger?.LogWarning("Could not find actuator of type {TypeName}", actuatorType.Name); return null; } @@ -244,7 +244,7 @@ public bool Load(IEnumerable extensionDirs, String configFile, bool load } catch (Exception ex) { - Log.Exception(ex); + _logger?.LogError(ex, "Exception loading actuator"); } } @@ -281,7 +281,7 @@ public bool Load(IEnumerable extensionDirs, String configFile, bool load } catch (Exception ex) { - Log.Exception(ex); + _logger?.LogError(ex, "Exception adding actuator"); } } } @@ -374,7 +374,7 @@ protected virtual void Dispose(bool disposing) // Check to see if Dispose has already been called. if (!_disposed) { - Log.Verbose(); + _logger?.LogTrace("Disposing actuators"); if (disposing) { @@ -409,7 +409,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/ACATCore/ActuatorManagement/BaseActuators/KeyboardActuator.cs b/src/Libraries/ACATCore/ActuatorManagement/BaseActuators/KeyboardActuator.cs index d402cab6..7eeb8308 100644 --- a/src/Libraries/ACATCore/ActuatorManagement/BaseActuators/KeyboardActuator.cs +++ b/src/Libraries/ACATCore/ActuatorManagement/BaseActuators/KeyboardActuator.cs @@ -14,6 +14,7 @@ using ACAT.Core.ActuatorManagement.Interfaces; using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Windows.Forms; @@ -25,6 +26,8 @@ namespace ACAT.Core.ActuatorManagement.BaseActuators "Handles Keyboard and Mouse input")] public class KeyboardActuator : ActuatorBase { + private static readonly ILogger _logger = LoggerFactory.Create(builder => builder.AddConsole()).CreateLogger(); + /// /// Indicated whetherthis object been disposed /// @@ -193,7 +196,7 @@ protected override void Dispose(bool disposing) { try { - Log.Verbose(); + _logger.LogTrace(""); if (disposing) { @@ -237,7 +240,7 @@ private IActuatorSwitch findActuatorSwitch(string hotKey) } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex, ex.Message); } return null; @@ -257,7 +260,7 @@ private void KeyboardHook_KeyDown(object sender, KeyEventArgs e) return; } - Log.Debug("Keydown: " + e.KeyCode.ToString()); + _logger.LogDebug("Keydown: {KeyCode}", e.KeyCode); // check if this is one of the keys we recognize. If so, trigger // a switch-activated event @@ -286,7 +289,7 @@ private void KeyboardHook_KeyDown(object sender, KeyEventArgs e) hotKey += "+" + e.KeyCode; } - Log.Debug("KeyStateTracker.KeyString: " + hotKey); + _logger.LogDebug("KeyStateTracker.KeyString: {HotKey}", hotKey); // check which switch handles this hotkey and trigger it actuatorSwitch = findActuatorSwitch(hotKey); @@ -316,7 +319,7 @@ private void KeyboardHook_KeyPress(object sender, KeyPressEventArgs e) } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex, ex.Message); } } @@ -333,7 +336,7 @@ private void KeyboardHook_KeyUp(object sender, KeyEventArgs e) } var s = string.Format("Keyup{0}. Alt: {1} Ctrl: {2}", e.KeyCode, e.Alt, e.Control); - Log.Debug(s); + _logger.LogDebug("{Message}", s); KeyStateTracker.KeyUp(e.KeyCode); diff --git a/src/Libraries/ACATCore/ActuatorManagement/WinsockActuators/WinsockServerActuator/SocketServer.cs b/src/Libraries/ACATCore/ActuatorManagement/WinsockActuators/WinsockServerActuator/SocketServer.cs index da256580..5751192c 100644 --- a/src/Libraries/ACATCore/ActuatorManagement/WinsockActuators/WinsockServerActuator/SocketServer.cs +++ b/src/Libraries/ACATCore/ActuatorManagement/WinsockActuators/WinsockServerActuator/SocketServer.cs @@ -13,6 +13,7 @@ //////////////////////////////////////////////////////////////////////////// using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Collections.Specialized; using System.Net; @@ -28,6 +29,8 @@ namespace ACAT.Core.ActuatorManagement.WinsockActuators.WinsockServerActuator /// public class SocketServer { + private readonly ILogger _logger; + /// /// List of clients connected to this socket server /// @@ -75,8 +78,9 @@ public SocketServer(int listenPort) /// /// Default constructor. /// - public SocketServer(string listenAddress, int listenPort) + public SocketServer(string listenAddress, int listenPort, ILogger logger = null) { + _logger = logger; ipToBind = listenAddress; portToBind = listenPort; parentThread = Thread.CurrentThread; @@ -192,7 +196,7 @@ public Thread Start() } catch (Exception exc) { - Log.Error("Couldn't start the SocketServer main working thread." + exc.StackTrace); + _logger?.LogError(exc, "Couldn't start the SocketServer main working thread"); workerThread = null; } @@ -204,18 +208,18 @@ public Thread Start() /// public void Stop() { - Log.Debug("SERVER: Stopping listeners until service is started again"); + _logger?.LogDebug("SERVER: Stopping listeners until service is started again"); try { tcpListener.Stop(); } catch (SocketException se) { - Log.Exception(se.ToString()); + _logger?.LogError(se, "Socket exception while stopping TCP listener"); } catch (Exception e) { - Log.Exception(e.ToString()); + _logger?.LogError(e, "Exception while stopping TCP listener"); } if (listenThread != null) { @@ -265,18 +269,14 @@ private void connHandler_OnPacketReceived(byte[] packet) /// private void ListenForClients() { - Log.Debug("SocketServer: Listener Thread"); + _logger?.LogDebug("SocketServer: Listener Thread started"); try { tcpListener.Start(); } catch (SocketException se) { - //Log.Error(se.IncludeStackTrace); - Log.Error(se.StackTrace); - // se.ErrorCode == 10048, this condition means that more than one process is attempting to bind to same port, disallowed. - // Log.Write(String.Format("SocketException: NativeError:{0} ErrorCode:{1}, Msg:{2}", se.NativeErrorCode, se.ErrorCode, se.Message)); - // Log.Debug("Socket Exception Listening for clients", se); + _logger?.LogError(se, "Socket exception while starting TCP listener (ErrorCode: {ErrorCode})", se.ErrorCode); listenThread.Abort(); return; } @@ -292,7 +292,7 @@ private void ListenForClients() IPAddress addr = IPAddress.Parse(ipe.Address.ToString()); string strAddr = addr.ToString(); - Log.Debug("Client " + strAddr + " has connected"); + _logger?.LogDebug("Client {ClientAddress} has connected", strAddr); // Create a thread to handle communication with a connected client. // The ClientConnHandler is an object that allows a way to pass data to a thread. The TcpClient is passed to the @@ -308,7 +308,7 @@ private void ListenForClients() } catch (SocketException se) { - Log.Error(se.StackTrace); + _logger?.LogError(se, "Socket exception while accepting client connection"); } } } @@ -328,7 +328,7 @@ private void serverThreadMethod() } catch (SocketException se) { - Log.Error("SERVER: Couldn't start TCP Listener, exiting the app. " + se.StackTrace); + _logger?.LogError(se, "SERVER: Couldn't start TCP Listener, exiting the app"); return; } catch (Exception ex) @@ -339,7 +339,7 @@ private void serverThreadMethod() string startMessage = string.Format("SERVER: Listener Started on {0}:{1}", ((IPEndPoint)tcpListener.LocalEndpoint).Address, ((IPEndPoint)tcpListener.LocalEndpoint).Port); - Log.Debug(startMessage); + _logger?.LogDebug("{StartMessage}", startMessage); parentThread.Join(); // A way to get current thread to wait until a thread is complete before continuing. } diff --git a/src/Libraries/ACATCore/ActuatorManagement/WinsockActuators/WinsockServerActuator/WinsockServerActuatorBase.cs b/src/Libraries/ACATCore/ActuatorManagement/WinsockActuators/WinsockServerActuator/WinsockServerActuatorBase.cs index f652a410..0dff73bc 100644 --- a/src/Libraries/ACATCore/ActuatorManagement/WinsockActuators/WinsockServerActuator/WinsockServerActuatorBase.cs +++ b/src/Libraries/ACATCore/ActuatorManagement/WinsockActuators/WinsockServerActuator/WinsockServerActuatorBase.cs @@ -15,6 +15,7 @@ using ACAT.Core.ActuatorManagement.Interfaces; using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System.Text; namespace ACAT.Core.ActuatorManagement.WinsockActuators.WinsockServerActuator @@ -27,6 +28,8 @@ namespace ACAT.Core.ActuatorManagement.WinsockActuators.WinsockServerActuator /// public class WinsockServerActuatorBase : ActuatorBase { + private static ILogger _logger; + /// /// Has this object been disposed? /// @@ -109,7 +112,7 @@ protected override void Dispose(bool disposing) { try { - Log.Verbose(); + _logger?.LogTrace("Disposing WinsockServerActuatorBase"); if (disposing) { @@ -152,7 +155,7 @@ protected virtual void onClientDisconnected(WinsockClientConnectEventArgs e) protected virtual void onDataReceived(byte[] packet) { string strData = Encoding.ASCII.GetString(packet, 0, packet.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); @@ -191,7 +194,7 @@ protected void triggerEvent(IActuatorSwitch switchObj) /// event arg private void _socketServer_OnClientConnected(object sender, WinsockClientConnectEventArgs e) { - Log.Debug("ImageActuator: Client disconnected " + e.IPAddress); + _logger?.LogDebug("ImageActuator: Client disconnected {IPAddress}", e.IPAddress); onClientConnected(e); } @@ -202,7 +205,7 @@ private void _socketServer_OnClientConnected(object sender, WinsockClientConnect /// event argument private void _socketServer_OnClientDisconnected(object sender, WinsockClientConnectEventArgs e) { - Log.Debug("ImageActuator: Client connected " + e.IPAddress); + _logger?.LogDebug("ImageActuator: Client connected {IPAddress}", e.IPAddress); onClientDisconnected(e); } @@ -232,7 +235,7 @@ private void initSocketInterface() } else { - Log.Debug("Listen error. Listen port not set"); + _logger?.LogDebug("Listen error. Listen port not set"); } } diff --git a/src/Libraries/ACATCore/AgentManagement/AgentManager.cs b/src/Libraries/ACATCore/AgentManagement/AgentManager.cs index e3c10443..85409b99 100644 --- a/src/Libraries/ACATCore/AgentManagement/AgentManager.cs +++ b/src/Libraries/ACATCore/AgentManagement/AgentManager.cs @@ -14,6 +14,7 @@ using ACAT.Core.PanelManagement.CommandDispatcher; using ACAT.Core.PanelManagement.Common; using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Diagnostics; @@ -141,6 +142,11 @@ public class AgentManager : IDisposable /// private static readonly AgentManager _instance = new(); + /// + /// Logger instance + /// + private static ILogger _logger; + /// /// Name of the executing assembly /// @@ -289,6 +295,15 @@ public static AgentManager Instance get { return _instance; } } + /// + /// Sets the logger for the AgentManager + /// + /// Logger instance + public static void SetLogger(ILogger logger) + { + _logger = logger; + } + /// /// Gets the currently active agent /// @@ -416,12 +431,12 @@ public async Task ActivateAgent(IApplicationAgent caller, IFunctionalAgent agent setAgent(agent); } - Log.Debug("Calling activateAgent: " + agent.Name); + _logger?.LogDebug("Calling activateAgent: " + agent.Name); await activateAgent(agent); CompletionCode exitCode = agent.ExitCode; - Log.Debug("Returned from activateAgent: " + agent.Name); + _logger?.LogDebug("Returned from activateAgent: " + agent.Name); setAgent(null); if (agent.ExitCommand != null) @@ -454,7 +469,7 @@ public async Task ActivateAgent(IFunctionalAgent agent) { if (_currentAgent is IFunctionalAgent) { - Log.Debug("Cannot activate functional agent " + agent.Name + ", functional agent " + _currentAgent.Name + " is currently active"); + _logger?.LogDebug("Cannot activate functional agent " + agent.Name + ", functional agent " + _currentAgent.Name + " is currently active"); return; } @@ -484,7 +499,7 @@ public AgentContext ActiveContext() /// agent to add public void AddAgent(IntPtr handle, IApplicationAgent agent) { - Log.Debug("hwnd: " + handle + ", " + agent.Name); + _logger?.LogDebug("hwnd: " + handle + ", " + agent.Name); agent.EvtPanelRequest += agent_EvtPanelRequest; _agentsCache.AddAgent(handle, agent); @@ -523,7 +538,7 @@ public void CheckCommandEnabled(CommandEnabledArg arg) if (_currentAgent is IFunctionalAgent && ((FunctionalAgentBase)_currentAgent).IsClosing) { - Log.Debug("Functional agent is closing. returning"); + _logger?.LogDebug("Functional agent is closing. returning"); return; } @@ -672,9 +687,9 @@ public bool LoadExtensions(IEnumerable extensionDirs) [EnvironmentPermission(SecurityAction.LinkDemand, Unrestricted = true)] public void OnPanelClosed(String panelClass) { - Log.Verbose(); - Log.Debug("panelClass : " + panelClass); - Log.Debug(" currentAgent: " + _currentAgent); + _logger?.LogTrace("OnPanelClosed"); + _logger?.LogDebug("panelClass : " + panelClass); + _logger?.LogDebug(" currentAgent: " + _currentAgent); if (_currentAgent != null) { var currentWindow = WindowActivityMonitor.CurrentWindowInfo(); @@ -768,7 +783,7 @@ public void RunCommand(String command, ref bool handled) { if (_currentAgent != null) { - Log.Debug("Calling runcommand agent : " + _currentAgent.Name + ", command: " + command); + _logger?.LogDebug("Calling runcommand agent : " + _currentAgent.Name + ", command: " + command); var cmd = (command[0] == '@') ? command.Substring(1) : command; _currentAgent.OnRunCommand(cmd, null, ref handled); @@ -786,7 +801,7 @@ public void RunCommand(String command, object arg, ref bool handled) { if (_currentAgent != null) { - Log.Debug("Calling runcommand agent : " + _currentAgent.Name + ", command: " + command); + _logger?.LogDebug("Calling runcommand agent : " + _currentAgent.Name + ", command: " + command); String cmd = (command[0] == '@') ? command.Substring(1) : command; _currentAgent.OnRunCommand(cmd, arg, ref handled); } @@ -943,30 +958,30 @@ private async Task activateAgent(IFunctionalAgent agent) var funcAgent = (FunctionalAgentBase)agent; Task task = Task.Factory.StartNew(() => { - Log.Debug("Calling funcAgent.activate: " + agent.Name); + _logger?.LogDebug("Calling funcAgent.activate: " + agent.Name); //funcAgent.IsClosing = false; funcAgent.ExitCommand = null; form.Invoke(new MethodInvoker(delegate { Context.AppPanelManager.NewStack(); - Log.Debug("Before activate " + funcAgent.Name); + _logger?.LogDebug("Before activate " + funcAgent.Name); funcAgent.Activate(); - Log.Debug("Returned from activate " + funcAgent.Name + ", calling closestack"); + _logger?.LogDebug("Returned from activate " + funcAgent.Name + ", calling closestack"); Context.AppPanelManager.CloseStack(); })); // This event is triggered by the functional agent when it exits - Log.Debug("Waiting on CloseEvent...: " + agent.Name); + _logger?.LogDebug("Waiting on CloseEvent...: " + agent.Name); funcAgent.CloseEvent.WaitOne(); - Log.Debug("Returned from CloseEvent: " + agent.Name); + _logger?.LogDebug("Returned from CloseEvent: " + agent.Name); funcAgent.PostClose(); }); - Log.Debug("Before await task"); + _logger?.LogDebug("Before await task"); await task; - Log.Debug("After await task"); + _logger?.LogDebug("After await task"); Windows.CloseForm(form); } @@ -985,27 +1000,27 @@ private void activateAppAgent(WindowActivityMonitorInfo monitorInfo) { if (inActivateAppAgent) { - Log.Warn("Already inside. returning"); + _logger?.LogWarning("Already inside. returning"); return; } - Log.Verbose("Before syncsetagent"); + _logger?.LogTrace("Before syncsetagent"); lock (_syncActivateAgent) { inActivateAppAgent = true; - Log.Verbose("After syncsetagent"); + _logger?.LogTrace("After syncsetagent"); try { bool handled = false; - //Log.Debug(monitorInfo.ToString()); + //_logger?.LogDebug(monitorInfo.ToString()); // did a request for displaying the contextual // menu come in? If so handle it. bool getContextMenu = _getContextMenu; - Log.Verbose("getContextMenu: " + getContextMenu); + _logger?.LogTrace("getContextMenu: " + getContextMenu); _getContextMenu = false; @@ -1013,12 +1028,12 @@ private void activateAppAgent(WindowActivityMonitorInfo monitorInfo) // first check if there is an ad-hoc agent, if so, // activate it - Log.Verbose("Looking for adhoc agent for " + monitorInfo.FgHwnd); + _logger?.LogTrace("Looking for adhoc agent for " + monitorInfo.FgHwnd); IApplicationAgent agent = _agentsCache.GetAgent(monitorInfo.FgHwnd); if (agent == null) { // check if a dialog or menu is active - Log.Verbose("Adhoc agent not present for " + monitorInfo.FgHwnd); + _logger?.LogTrace("Adhoc agent not present for " + monitorInfo.FgHwnd); IntPtr parent = User32Interop.GetParent(monitorInfo.FgHwnd); if (parent != IntPtr.Zero) @@ -1027,13 +1042,13 @@ private void activateAppAgent(WindowActivityMonitorInfo monitorInfo) (String.Compare(processName, _currentProcessName, true) != 0) && isDialog(monitorInfo)) { - Log.Verbose("Fg window is a dialog. Setting agent to dialog agent"); + _logger?.LogTrace("Fg window is a dialog. Setting agent to dialog agent"); agent = _dialogAgent; } else if (EnableContextualMenusForMenus && isMenu(monitorInfo)) { - Log.Verbose("Fg window is a menu. Setting agent to menu agent"); + _logger?.LogTrace("Fg window is a menu. Setting agent to menu agent"); agent = _menuControlAgent; } } @@ -1042,23 +1057,23 @@ private void activateAppAgent(WindowActivityMonitorInfo monitorInfo) { if (Windows.IsMinimized(monitorInfo.FgHwnd)) { - Log.Verbose("Window is minimized. Use generic agent"); + _logger?.LogTrace("Window is minimized. Use generic agent"); agent = _genericAppAgent; } else { // check if there is a dedicated agent for this process - Log.Verbose("Getting agent for " + processName); + _logger?.LogTrace("Getting agent for " + processName); agent = _agentsCache.GetAgent(monitorInfo.FgProcess); } } } else { - Log.Verbose("Adhoc agent IS present for " + monitorInfo.FgHwnd); + _logger?.LogTrace("Adhoc agent IS present for " + monitorInfo.FgHwnd); } - Log.Verbose("Current agent: " + ((_currentAgent != null) ? + _logger?.LogTrace("Current agent: " + ((_currentAgent != null) ? _currentAgent.Name : "null") + ", agent: " + ((agent != null) ? agent.Name : "null")); @@ -1068,7 +1083,7 @@ private void activateAppAgent(WindowActivityMonitorInfo monitorInfo) if (_currentAgent != null && _currentAgent != agent) { bool allowSwitch = _currentAgent.QueryAgentSwitch(agent); - Log.Verbose("CurrentAgent is " + _currentAgent.Name + ", queryAgentSwitch: " + allowSwitch); + _logger?.LogTrace("CurrentAgent is " + _currentAgent.Name + ", queryAgentSwitch: " + allowSwitch); if (!allowSwitch) { _currentAgent.OnFocusChanged(monitorInfo, ref handled); @@ -1085,7 +1100,7 @@ private void activateAppAgent(WindowActivityMonitorInfo monitorInfo) { agent ??= _genericAppAgent; - Log.Verbose("agent : " + agent.Name); + _logger?.LogTrace("agent : " + agent.Name); agent.OnContextMenuRequest(monitorInfo); return; } @@ -1095,9 +1110,9 @@ private void activateAppAgent(WindowActivityMonitorInfo monitorInfo) // is appropriated for the context. if (agent != null) { - Log.Verbose("Trying agent " + agent.Name); + _logger?.LogTrace("Trying agent " + agent.Name); agent.OnFocusChanged(monitorInfo, ref handled); - Log.Verbose("Returned from agent.OnFOcus"); + _logger?.LogTrace("Returned from agent.OnFOcus"); } // If we have reached here, it means there was no @@ -1105,8 +1120,8 @@ private void activateAppAgent(WindowActivityMonitorInfo monitorInfo) // if it will handle it if (!handled) { - Log.Verbose("Did not find agent for " + processName + ". trying generic app agent"); - Log.Verbose("_genericAppAgent is " + ((_genericAppAgent != null) ? "not null" : "null")); + _logger?.LogTrace("Did not find agent for " + processName + ". trying generic app agent"); + _logger?.LogTrace("_genericAppAgent is " + ((_genericAppAgent != null) ? "not null" : "null")); agent = _genericAppAgent; try { @@ -1114,16 +1129,16 @@ private void activateAppAgent(WindowActivityMonitorInfo monitorInfo) } catch (Exception ex) { - Log.Exception(ex); + _logger?.LogError(ex, ex.Message); } } // even the generic agent refused. Use the null agent // as the last resort - Log.Verbose("handled " + handled); + _logger?.LogTrace("handled " + handled); if (!handled) { - Log.Verbose("generic app agent refused. Using null agent"); + _logger?.LogTrace("generic app agent refused. Using null agent"); agent = _nullAgent; agent.OnFocusChanged(monitorInfo, ref handled); } @@ -1132,7 +1147,7 @@ private void activateAppAgent(WindowActivityMonitorInfo monitorInfo) } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger?.LogError(ex.ToString()); } finally { @@ -1140,7 +1155,7 @@ private void activateAppAgent(WindowActivityMonitorInfo monitorInfo) } } - Log.Verbose("Return"); + _logger?.LogTrace("Return"); } /// @@ -1172,7 +1187,7 @@ private void agent_EvtAgentClose(object sender, AgentCloseEventArgs e) /// event arg private void agent_EvtPanelRequest(object sender, PanelRequestEventArgs arg) { - Log.Debug("Panel request for " + arg.PanelClass); + _logger?.LogDebug("Panel request for " + arg.PanelClass); triggerPanelRequest(sender, arg); } @@ -1213,7 +1228,7 @@ private void disallowContextSwitch(WindowActivityMonitorInfo monitorInfo) agent ??= _genericAppAgent; - Log.Debug("agent : " + agent.Name); + _logger?.LogDebug("agent : " + agent.Name); if (_getContextMenu) { @@ -1241,7 +1256,7 @@ private void Dispose(bool disposing) // Check to see if Dispose has already been called. if (!_disposed) { - Log.Verbose(); + _logger?.LogTrace("Dispose"); if (disposing) { @@ -1304,24 +1319,24 @@ private bool isDialog(WindowActivityMonitorInfo monitorInfo) bool retVal = false; AutomationElement window = AutomationElement.FromHandle(monitorInfo.FgHwnd); - Log.Debug("controltype: " + window.Current.ControlType.ProgrammaticName); + _logger?.LogDebug("controltype: " + window.Current.ControlType.ProgrammaticName); if (Equals(window.Current.ControlType, ControlType.Menu)) { - Log.Debug("**** controltype: IT IS MENU"); + _logger?.LogDebug("**** controltype: IT IS MENU"); retVal = true; } else if (window.TryGetCurrentPattern(WindowPattern.Pattern, out object objPattern)) { var windowPattern = objPattern as WindowPattern; retVal = (!windowPattern.Current.CanMinimize && !windowPattern.Current.CanMaximize) || windowPattern.Current.IsModal; - Log.Debug("CanMinimize: " + windowPattern.Current.CanMinimize + ", canMaximize: " + windowPattern.Current.CanMaximize + ", isModal: " + windowPattern.Current.IsModal); - Log.Debug("retVal: " + retVal); + _logger?.LogDebug("CanMinimize: " + windowPattern.Current.CanMinimize + ", canMaximize: " + windowPattern.Current.CanMaximize + ", isModal: " + windowPattern.Current.IsModal); + _logger?.LogDebug("retVal: " + retVal); retVal = retVal && !Windows.IsMinimized(monitorInfo.FgHwnd); } - Log.Debug("returning " + retVal); + _logger?.LogDebug("returning " + retVal); return retVal; } @@ -1360,7 +1375,7 @@ private void keyboardActuator_EvtKeyDown(object sender, KeyEventArgs keyEventArg _currentEditingMode = EditingMode.Edit; } - Log.Debug("_currentEditingMode: " + _currentEditingMode); + _logger?.LogDebug("_currentEditingMode: " + _currentEditingMode); if (_currentAgent != null && _currentAgent.TextControlAgent != null) { @@ -1394,19 +1409,19 @@ private void keyboardActuator_EvtKeyUp(object sender, KeyEventArgs keyEventArgs) private bool notifyTextChanged(ITextControlAgent textInterface) { uint threadId = GetCurrentThreadId(); - Log.Debug("Entered notifyTextChanged: " + threadId); + _logger?.LogDebug("Entered notifyTextChanged: " + threadId); // Use the semaphore to see if this is blocked if (TextChangedNotifications.OnHold()) { - Log.Debug("NotificationsOnHold. Exit ThreadID: " + threadId); + _logger?.LogDebug("NotificationsOnHold. Exit ThreadID: " + threadId); return false; } // try to acquire a lock if (!tryLock(_syncTextChangeNotifyObj)) { - Log.Debug("_lock is true. returning on thread : " + threadId); + _logger?.LogDebug("_lock is true. returning on thread : " + threadId); return false; } @@ -1418,13 +1433,13 @@ private bool notifyTextChanged(ITextControlAgent textInterface) // the same thread trying to re-enter the function if (_notifyTextChangedLock) { - Log.Debug("REENTRANCY DETECTED. RETURNING"); + _logger?.LogDebug("REENTRANCY DETECTED. RETURNING"); return true; } if (textInterface != _textControlAgent) { - Log.Debug("event source is not the current agent. returning..."); + _logger?.LogDebug("event source is not the current agent. returning..."); return false; } @@ -1434,34 +1449,34 @@ private bool notifyTextChanged(ITextControlAgent textInterface) { if (EvtTextChanged != null) { - Log.Debug("Calling EvtTextChanged"); + _logger?.LogDebug("Calling EvtTextChanged"); EvtTextChanged(this, EventArgs.Empty); - Log.Debug("Returned from EvtTextChanged"); + _logger?.LogDebug("Returned from EvtTextChanged"); } else { - Log.Debug("EvtTextChanged is null"); + _logger?.LogDebug("EvtTextChanged is null"); } } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger?.LogError(ex.ToString()); } _notifyTextChangedLock = false; - Log.Debug("Exit End of function ThreadID: " + threadId); + _logger?.LogDebug("Exit End of function ThreadID: " + threadId); } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger?.LogError(ex.ToString()); } finally { release(_syncTextChangeNotifyObj); } - Log.Debug("Returning"); + _logger?.LogDebug("Returning"); return true; } @@ -1474,13 +1489,13 @@ private void onFocusChanged(WindowActivityMonitorInfo monitorInfo) { if (monitorInfo.FgHwnd == IntPtr.Zero) { - Log.Debug("hWnd is null"); + _logger?.LogDebug("hWnd is null"); return; } - //Log.Debug(monitorInfo.ToString()); + //_logger?.LogDebug(monitorInfo.ToString()); - //Log.Debug(" hwnd: " + hWnd + " Title: [" + title + "] process: " + process.ProcessName + + //_logger?.LogDebug(" hwnd: " + hWnd + " Title: [" + title + "] process: " + process.ProcessName + // ". focusedElement: [" + // ((focusedElement != null) ? focusedElement.Current.ClassName : "null") + "]"); @@ -1490,7 +1505,7 @@ private void onFocusChanged(WindowActivityMonitorInfo monitorInfo) { var functionalAgent = _currentAgent as IFunctionalAgent; - Log.Debug(_currentAgent.Name + ", IsActive: " + functionalAgent.IsActive + ", IsClosing: " + functionalAgent.IsClosing); + _logger?.LogDebug(_currentAgent.Name + ", IsActive: " + functionalAgent.IsActive + ", IsClosing: " + functionalAgent.IsClosing); if (functionalAgent.IsActive && !functionalAgent.IsClosing) { @@ -1516,7 +1531,7 @@ private void onFocusChanged(WindowActivityMonitorInfo monitorInfo) if (_currentAgent != null) { - Log.Debug("CurrentAgent is " + _currentAgent.GetType()); + _logger?.LogDebug("CurrentAgent is " + _currentAgent.GetType()); } if (EvtFocusChanged != null) @@ -1525,7 +1540,7 @@ private void onFocusChanged(WindowActivityMonitorInfo monitorInfo) } else { - Log.Debug("EVTFocusChanged is null!"); + _logger?.LogDebug("EVTFocusChanged is null!"); } } @@ -1541,7 +1556,7 @@ private void release(object sync) } catch (Exception ex) { - Log.Exception(ex); + _logger?.LogError(ex, ex.Message); } } @@ -1551,7 +1566,7 @@ private void release(object sync) /// sets the agent private void setAgent(IApplicationAgent agent) { - Log.Debug("Setting agent to " + ((agent != null) ? agent.Name : "null")); + _logger?.LogDebug("Setting agent to " + ((agent != null) ? agent.Name : "null")); _currentAgent = agent; } @@ -1564,31 +1579,31 @@ private void setAgent(IApplicationAgent agent) private void TextChangedNotifications_EvtUnlocked() { uint threadId = GetCurrentThreadId(); - Log.Debug("Enter ID. calling notifytextchanged on threadID: " + threadId); + _logger?.LogDebug("Enter ID. calling notifytextchanged on threadID: " + threadId); int ii = 0; while (true) { - Log.Debug("UNLOCKED! Calling NotifyTextChanged"); + _logger?.LogDebug("UNLOCKED! Calling NotifyTextChanged"); if (notifyTextChanged(_textControlAgent)) { - Log.Debug("Returned from NotifyTextChanged()"); + _logger?.LogDebug("Returned from NotifyTextChanged()"); break; } - Log.Debug("wait for _lock to release " + ii); + _logger?.LogDebug("wait for _lock to release " + ii); Application.DoEvents(); if (ii > 500) { - Log.Debug("TIMED OUT WAITING FOR LOCK"); + _logger?.LogDebug("TIMED OUT WAITING FOR LOCK"); break; } ii++; } - Log.Debug("Leave ThreadID: " + threadId); + _logger?.LogDebug("Leave ThreadID: " + threadId); } /// @@ -1600,10 +1615,10 @@ private void TextChangedNotifications_EvtUnlocked() /// panel request info private void triggerPanelRequest(object sender, PanelRequestEventArgs arg) { - Log.Debug("PanelClass: " + arg.PanelClass); + _logger?.LogDebug("PanelClass: " + arg.PanelClass); if (_panelChangeNotifications.OnHold()) { - Log.Debug("Panel change request paused. will not change panel"); + _logger?.LogDebug("Panel change request paused. will not change panel"); return; } @@ -1613,7 +1628,7 @@ private void triggerPanelRequest(object sender, PanelRequestEventArgs arg) } else { - Log.Debug("EvtPanelrequest is null"); + _logger?.LogDebug("EvtPanelrequest is null"); } } diff --git a/src/Libraries/ACATCore/AgentManagement/AgentUtils.cs b/src/Libraries/ACATCore/AgentManagement/AgentUtils.cs index b4f608b8..deeb2203 100644 --- a/src/Libraries/ACATCore/AgentManagement/AgentUtils.cs +++ b/src/Libraries/ACATCore/AgentManagement/AgentUtils.cs @@ -18,12 +18,7 @@ namespace ACAT.Core.AgentManagement /// public class AgentUtils { - private static ILogger _logger; - - public static void SetLogger(ILogger logger) - { - _logger = logger; - } + private static readonly ILogger _logger = LoggingConfiguration.CreateLogger(); /// /// Finds a descendent of the focused element that has the specified /// className, controlType and automationID @@ -350,8 +345,8 @@ public static bool IsElementOrAncestorByAutomationId(AutomationElement focusedEl 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 && diff --git a/src/Libraries/ACATCore/AgentManagement/Agents/AgentsCache.cs b/src/Libraries/ACATCore/AgentManagement/Agents/AgentsCache.cs index 2622110a..11132936 100644 --- a/src/Libraries/ACATCore/AgentManagement/Agents/AgentsCache.cs +++ b/src/Libraries/ACATCore/AgentManagement/Agents/AgentsCache.cs @@ -9,6 +9,7 @@ using ACAT.Core.AgentManagement.Interfaces; using ACAT.Core.Utility; using ACAT.Core.Utility.TypeLoader; +using Microsoft.Extensions.Logging; using System; using System.Collections; using System.Collections.Generic; @@ -26,6 +27,8 @@ namespace ACAT.Core.AgentManagement.Agents /// internal class AgentsCache : IDisposable { + private static ILogger _logger; + /// /// Adhoc agents are those that can be added at runtime. Adhoc /// agents are attached to a window handle and activated when that @@ -61,7 +64,7 @@ internal class AgentsCache : IDisposable /// public AgentsCache() { - Log.Verbose(); + _logger?.LogTrace("AgentsCache created"); _agentCache = new List(); _agentLookupTableByProcessName = new Hashtable(); @@ -276,13 +279,13 @@ public IEnumerable GetExtensions() /// true on success public bool Init(IEnumerable extensionDirs) { - Log.Verbose(); + _logger?.LogTrace("Initializing AgentsCache"); loadCache(extensionDirs); _preferredAgents.Load(_agentLookupTableById); - Log.Debug("Done loading cache"); + _logger?.LogDebug("Done loading cache"); populateLookupTableByProcess(); @@ -319,7 +322,7 @@ private void addAgent(Type agentType) try { var agent = (IApplicationAgent)Activator.CreateInstance(agentType); - Log.Debug("Adding agent " + agentType.FullName); + _logger?.LogDebug("Adding agent {AgentType}", agentType.FullName); _agentCache.Add(agent); _agentLookupTableById.Add(agent.Descriptor.Id, agent); @@ -329,7 +332,7 @@ private void addAgent(Type agentType) } catch (Exception ex) { - Log.Exception("Could not load agent " + agentType + ", exception: " + ex); + _logger?.LogError(ex, "Could not load agent {AgentType}", agentType); } } @@ -376,7 +379,7 @@ private void onAgentFound(string agentName) } catch (Exception ex) { - Log.Exception($"Error loading agent from {agentName}: {ex.Message}"); + _logger?.LogError(ex, "Error loading agent from {AgentName}", agentName); } } diff --git a/src/Libraries/ACATCore/AgentManagement/Agents/PreferredAgents.cs b/src/Libraries/ACATCore/AgentManagement/Agents/PreferredAgents.cs index e560092e..f791d152 100644 --- a/src/Libraries/ACATCore/AgentManagement/Agents/PreferredAgents.cs +++ b/src/Libraries/ACATCore/AgentManagement/Agents/PreferredAgents.cs @@ -8,6 +8,7 @@ using ACAT.Core.AgentManagement.Interfaces; using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Collections; using System.Diagnostics; @@ -36,6 +37,8 @@ namespace ACAT.Core.AgentManagement.Agents /// internal class PreferredAgents : IDisposable { + private readonly ILogger _logger; + /// /// Name of the preferences file /// @@ -51,7 +54,7 @@ internal class PreferredAgents : IDisposable /// public PreferredAgents() { - Log.Verbose(); + _logger = LoggingConfiguration.CreateLogger(); _preferredAgents = new Hashtable(); } @@ -193,7 +196,7 @@ public void Load(Hashtable agentsTable) } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex, "Exception loading preferred agents"); } } } diff --git a/src/Libraries/ACATCore/AgentManagement/GenericAppAgentBase.cs b/src/Libraries/ACATCore/AgentManagement/GenericAppAgentBase.cs index b6df6013..673217d4 100644 --- a/src/Libraries/ACATCore/AgentManagement/GenericAppAgentBase.cs +++ b/src/Libraries/ACATCore/AgentManagement/GenericAppAgentBase.cs @@ -155,7 +155,7 @@ private TextControlAgentBase createEditControlTextInterface( private void disposeAndCreateTextInterface(WindowActivityMonitorInfo monitorInfo) { disposeTextInterface(); - Log.Debug("Calling createEditControlTextInterface"); + _logger.LogDebug("Calling createEditControlTextInterface"); var textInterface = createEditControlTextInterface(monitorInfo.FgHwnd, monitorInfo.FocusedElement) ?? createKeyLoggerTextInterface(monitorInfo.FgHwnd, monitorInfo.FocusedElement); diff --git a/src/Libraries/ACATCore/AgentManagement/Keyboard.cs b/src/Libraries/ACATCore/AgentManagement/Keyboard.cs index debd8194..a8499b18 100644 --- a/src/Libraries/ACATCore/AgentManagement/Keyboard.cs +++ b/src/Libraries/ACATCore/AgentManagement/Keyboard.cs @@ -143,7 +143,7 @@ public void Send(Keys extendedKey, int count) } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, "Error sending extended key"); } finally { @@ -290,7 +290,7 @@ public void Send(String str) } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, "Error sending string"); } finally { @@ -307,7 +307,7 @@ protected virtual void Dispose(bool disposing) // Check to see if Dispose has already been called. if (!_disposed) { - Log.Verbose(); + _logger.LogTrace("Disposing Keyboard"); if (disposing) { @@ -369,7 +369,7 @@ private void sendChar(char ch) private bool shiftNeeded(char c) { short virtualKey = User32Interop.VkKeyScanEx(c, _keyboardLayout); - Log.Debug("virtualKey for [" + c + "] is " + virtualKey); + _logger.LogDebug("virtualKey for [{Char}] is {VirtualKey}", c, virtualKey); if ((virtualKey & 0x100) == 0x100) { _logger.LogDebug("Shift needs to be pressed for [{Char}]", c); diff --git a/src/Libraries/ACATCore/AgentManagement/TextControlAgents/EditTextControlAgent.cs b/src/Libraries/ACATCore/AgentManagement/TextControlAgents/EditTextControlAgent.cs index f1963b14..719b5b2d 100644 --- a/src/Libraries/ACATCore/AgentManagement/TextControlAgents/EditTextControlAgent.cs +++ b/src/Libraries/ACATCore/AgentManagement/TextControlAgents/EditTextControlAgent.cs @@ -9,6 +9,7 @@ using System; using System.Windows.Automation; using System.Windows.Forms; +using Microsoft.Extensions.Logging; namespace ACAT.Core.AgentManagement.TextControlAgents { @@ -22,6 +23,8 @@ namespace ACAT.Core.AgentManagement.TextControlAgents /// public class EditTextControlAgent : TextControlAgentBase { + private static ILogger _logger; + /// /// Handle of the active target window (eg the Notepad window) /// @@ -209,7 +212,7 @@ private void onTextChanged(object sender, AutomationEventArgs e) triggerTextChanged(this); CoreGlobals.Stopwatch2.Stop(); - Log.Debug("onTextChanged() TimeElapsed: " + CoreGlobals.Stopwatch2.ElapsedMilliseconds); + _logger?.LogDebug("onTextChanged() TimeElapsed: {ElapsedMs}ms", CoreGlobals.Stopwatch2.ElapsedMilliseconds); } /// @@ -227,7 +230,7 @@ private bool trackTextChanges(IntPtr handleMainWindow, AutomationElement textEle if (!retVal) { - Log.Debug("Text element is null"); + _logger?.LogDebug("Text element is null"); return false; } @@ -244,7 +247,7 @@ private bool trackTextChanges(IntPtr handleMainWindow, AutomationElement textEle AutomationEventManager.RemoveAutomationEventHandler(handleMainWindow, TextPattern.TextSelectionChangedEvent, textElement); - Log.Debug("Adding onTextChanged event handler"); + _logger?.LogDebug("Adding onTextChanged event handler"); AutomationEventManager.AddAutomationEventHandler(handleMainWindow, TextPattern.TextSelectionChangedEvent, textElement, @@ -252,13 +255,13 @@ private bool trackTextChanges(IntPtr handleMainWindow, AutomationElement textEle if (nativeHandle == 0) { - Log.Debug("handle is zero"); + _logger?.LogDebug("handle is zero"); retVal = false; } } else { - Log.Debug("Focused element does not support textpattern"); + _logger?.LogDebug("Focused element does not support textpattern"); retVal = false; } } @@ -267,7 +270,7 @@ private bool trackTextChanges(IntPtr handleMainWindow, AutomationElement textEle // exception can be thrown by AddAutomationEventHandler to the effect that // WindowClosed event can only be attached to top level windows. // For instance, the "Start" menu would throw this exception. - Log.Exception(ex.ToString()); + _logger?.LogError(ex, "Exception tracking text changes"); retVal = false; } diff --git a/src/Libraries/ACATCore/AgentManagement/TextControlAgents/KeyLogTextControlAgent.cs b/src/Libraries/ACATCore/AgentManagement/TextControlAgents/KeyLogTextControlAgent.cs index 17479fdd..a218f32d 100644 --- a/src/Libraries/ACATCore/AgentManagement/TextControlAgents/KeyLogTextControlAgent.cs +++ b/src/Libraries/ACATCore/AgentManagement/TextControlAgents/KeyLogTextControlAgent.cs @@ -6,6 +6,7 @@ //////////////////////////////////////////////////////////////////////////// using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Windows.Forms; @@ -20,6 +21,8 @@ namespace ACAT.Core.AgentManagement.TextControlAgents /// public class KeyLogTextControlAgent : TextControlAgentBase { + private static ILogger _logger; + /// /// Windows constant /// @@ -83,7 +86,7 @@ public override void ClearText() /// caret position public override int GetCaretPos() { - Log.Verbose(); + _logger?.LogTrace("Getting caret position"); if (isValid(_textBox)) { return Windows.GetCaretPosition(_textBox); @@ -178,8 +181,8 @@ public override void OnKeyDown(KeyEventArgs e) break; } - Log.Debug("Keycode: " + e.KeyCode + - ", cursor: " + (_textBox != null ? _textBox.SelectionStart.ToString() : "-1")); + _logger?.LogDebug("Keycode: {KeyCode}, cursor: {Cursor}", e.KeyCode, + (_textBox != null ? _textBox.SelectionStart.ToString() : "-1")); } /// @@ -197,7 +200,7 @@ public override void OnKeyUp(KeyEventArgs e) if (_textBox != null) { - Log.Debug("keyup: " + e.KeyCode); + _logger?.LogDebug("keyup: {KeyCode}", e.KeyCode); switch (e.KeyCode) { @@ -313,7 +316,7 @@ protected override void OnDispose() /// arg private void _textBox_TextChanged(object sender, EventArgs e) { - Log.Verbose(); + _logger?.LogTrace("TextBox text changed"); onTextChanged(); } @@ -325,7 +328,7 @@ private void createTextBox() if (_textBox == null) { var name = string.Format("NullAgent_TB_" + _textBoxNameCounter++); - Log.Debug("Creating textbox window " + name); + _logger?.LogDebug("Creating textbox window {Name}", name); _textBox = new TextBox { Name = name, Multiline = true }; _textBox.TextChanged += _textBox_TextChanged; } @@ -340,7 +343,7 @@ private void createTextBox() /// private void disposeTextInterface() { - Log.Verbose(); + _logger?.LogTrace("Disposing text interface"); if (isValid(_textBox)) { _textBox.TextChanged -= _textBox_TextChanged; @@ -367,9 +370,8 @@ private void onTextChanged() { if (_textBox != null) { - Log.Debug("textbox changed. Name: " + _textBox.Name + - ", caretPos = " + _textBox.SelectionStart + - ", _textBox: " + (_textBox == null ? "null" : _textBox.Text)); + _logger?.LogDebug("textbox changed. Name: {Name}, caretPos: {CaretPos}, text: {Text}", + _textBox.Name, _textBox.SelectionStart, _textBox.Text); } triggerTextChanged(this); diff --git a/src/Libraries/ACATCore/AgentManagement/TextControlAgents/TextControlAgentBase.cs b/src/Libraries/ACATCore/AgentManagement/TextControlAgents/TextControlAgentBase.cs index 5bcdf843..14690b9f 100644 --- a/src/Libraries/ACATCore/AgentManagement/TextControlAgents/TextControlAgentBase.cs +++ b/src/Libraries/ACATCore/AgentManagement/TextControlAgents/TextControlAgentBase.cs @@ -10,6 +10,7 @@ using ACAT.Core.Utility; using ACAT.Core.WordPredictorManagement; using ACAT.Core.WordPredictorManagement.Interfaces; +using Microsoft.Extensions.Logging; using System; using System.Linq; using System.Text; @@ -30,6 +31,11 @@ public class TextControlAgentBase : ITextControlAgent /// private static readonly Keyboard _keyboard = new(); + /// + /// Logger for the class + /// + private readonly ILogger _logger; + /// /// Text manipulation features supported by the base class /// @@ -79,8 +85,9 @@ public class TextControlAgentBase : ITextControlAgent /// /// Initializes a new instance of the class /// - public TextControlAgentBase() + public TextControlAgentBase(ILogger logger = null) { + _logger = logger; _selectMode = false; Context.AppAgentMgr.EvtNonScannerMouseDown += AppAgentMgr_EvtNonScannerMouseDown; } @@ -168,7 +175,7 @@ public virtual void Delete(int offset, int count) { AgentManager.Instance.TextChangedNotifications.Hold(); - Log.Debug("offset: " + offset + ", count: " + count); + _logger?.LogDebug("offset: {Offset}, count: {Count}", offset, count); SetCaretPos(offset + count); int ii = offset + count; @@ -180,7 +187,7 @@ public virtual void Delete(int offset, int count) } catch (Exception ex) { - Log.Exception(ex); + _logger?.LogError(ex, ex.Message); } finally { @@ -554,7 +561,7 @@ public virtual bool GetCharLeftOfCaret(out char value) } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger?.LogError(ex.ToString()); value = '\0'; } @@ -637,7 +644,7 @@ public virtual void GetPrefixAndWordAtCaret(out string prefix, out string word) string text = GetText(); int caretPos = GetCaretPos(); ////Log.Debug("**** text: [" + text + "], caretPos: " + caretPos); - Log.Debug("caretPos: " + caretPos); + _logger?.LogDebug("caretPos: {CaretPos}", caretPos); TextUtils.GetPrefixAndWordAtCaret(text, caretPos, out prefix, out word); } @@ -867,7 +874,7 @@ public virtual void Insert(int offset, string word) } catch (Exception ex) { - Log.Exception(ex); + _logger?.LogError(ex, ex.Message); } finally { @@ -980,7 +987,7 @@ public virtual bool Redo() /// Word to insert at the 'offset' public virtual 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 { @@ -996,7 +1003,7 @@ public virtual void Replace(int offset, int count, string word) Keyboard.Send(Keys.Delete); } - Log.Debug("HARRIS Sending back"); + _logger?.LogDebug("HARRIS Sending back"); SendKeys.SendWait("{BACKSPACE " + count + "}"); @@ -1005,13 +1012,13 @@ public virtual void Replace(int offset, int count, string word) word = word.ToUpper(); } - Log.Debug("Sending word " + word); + _logger?.LogDebug("Sending word {Word}", word); sendWait(word); } catch (Exception ex) { - Log.Exception(ex); + _logger?.LogError(ex, ex.Message); } finally { @@ -1211,7 +1218,7 @@ protected int GetCaretPos(IntPtr handleText) } catch (Exception e) { - Log.Exception(e); + _logger?.LogError(e, e.Message); } return caretPos; @@ -1274,7 +1281,7 @@ protected string GetSelectedText(IntPtr handleText) } catch (Exception e) { - Log.Exception(e); + _logger?.LogError(e, e.Message); } return selectedText; @@ -1288,7 +1295,7 @@ protected string GetText(IntPtr handleText) { string str = string.Empty; - Log.Verbose(); + _logger?.LogDebug("GetText called"); if (handleText == IntPtr.Zero) { @@ -1301,7 +1308,7 @@ protected string GetText(IntPtr handleText) } catch (Exception e) { - Log.Exception(e); + _logger?.LogError(e, e.Message); } return str; @@ -1314,7 +1321,7 @@ protected string GetText(IntPtr handleText) /// protected void learn() { - Log.Verbose(); + _logger?.LogDebug("learn called"); if (!WordPredictionManager.Instance.ActiveWordPredictor.SupportsLearning) { @@ -1325,11 +1332,11 @@ protected void learn() var trimmed = str.Trim(); if (string.IsNullOrEmpty(trimmed)) { - Log.Debug("Nothing to learn. sentence is empty"); + _logger?.LogDebug("Nothing to learn. sentence is empty"); return; } - Log.Debug("Learn : [" + trimmed + "]"); + _logger?.LogDebug("Learn : [{Trimmed}]", trimmed); WordPredictionManager.Instance.ActiveWordPredictor.Learn(trimmed, WordPredictorMessageTypes.None); } @@ -1370,7 +1377,7 @@ protected bool SetCaretPos(IntPtr handleText, int pos) } catch (Exception e) { - Log.Exception(e); + _logger?.LogError(e, e.Message); } return true; @@ -1384,7 +1391,7 @@ protected bool SetFocus(IntPtr handleText) { int ret = 0; - Log.Verbose(); + _logger?.LogDebug("SetFocus called"); if (handleText == IntPtr.Zero) { @@ -1397,7 +1404,7 @@ protected bool SetFocus(IntPtr handleText) } catch (Exception e) { - Log.Exception(e); + _logger?.LogError(e, e.Message); } return ret != 0; @@ -1457,7 +1464,7 @@ private void dispose(bool disposing) { if (!_disposed) { - Log.Verbose(); + _logger?.LogDebug("dispose called"); if (disposing) { diff --git a/src/Libraries/ACATCore/AgentManagement/UnsupportedAppAgent.cs b/src/Libraries/ACATCore/AgentManagement/UnsupportedAppAgent.cs index 8fb71896..fe750fe1 100644 --- a/src/Libraries/ACATCore/AgentManagement/UnsupportedAppAgent.cs +++ b/src/Libraries/ACATCore/AgentManagement/UnsupportedAppAgent.cs @@ -7,6 +7,7 @@ using ACAT.Core.PanelManagement.Common; using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; @@ -77,7 +78,7 @@ public override void OnContextMenuRequest(WindowActivityMonitorInfo monitorInfo) /// true if handled public override void OnFocusChanged(WindowActivityMonitorInfo monitorInfo, ref bool handled) { - Log.Verbose(); + _logger.LogDebug("OnFocusChanged"); if (ignoreApp(monitorInfo.FgProcess.ProcessName)) { @@ -86,7 +87,7 @@ public override void OnFocusChanged(WindowActivityMonitorInfo monitorInfo, ref b } base.OnFocusChanged(monitorInfo, ref handled); - Log.Debug("IsNew: " + monitorInfo.IsNewWindow + ", scannerShown: " + scannerShown); + _logger.LogDebug("IsNew: {IsNewWindow}, scannerShown: {ScannerShown}", monitorInfo.IsNewWindow, scannerShown); if (monitorInfo.IsNewWindow || !scannerShown) { showPanel(this, new PanelRequestEventArgs(PanelClasses.Alphabet, monitorInfo)); diff --git a/src/Libraries/ACATCore/AnimationManagement/Animation.cs b/src/Libraries/ACATCore/AnimationManagement/Animation.cs index 9e25cad1..34754381 100644 --- a/src/Libraries/ACATCore/AnimationManagement/Animation.cs +++ b/src/Libraries/ACATCore/AnimationManagement/Animation.cs @@ -8,6 +8,7 @@ using ACAT.Core.Interpreter; using ACAT.Core.Utility; using ACAT.Core.WidgetManagement; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; @@ -26,6 +27,8 @@ namespace ACAT.Core.AnimationManagement /// public class Animation : IDisposable { + private static ILogger _logger; + /// /// Code to execute when the animation sequence ends without the /// user having selected anything during the sequence @@ -241,7 +244,7 @@ internal void ResolveUIWidgetsReferences(Widget rootWidget, Variables variables) { clearAnimationWidgetList(); - Log.Verbose(rootWidget.Name + ". widgetXMLNodeList count: " + _widgetXMLNodeList.Count); + _logger?.LogTrace("{RootWidgetName}. widgetXMLNodeList count: {Count}", rootWidget.Name, _widgetXMLNodeList.Count); foreach (XmlNode xmlNode in _widgetXMLNodeList) { @@ -259,7 +262,7 @@ protected virtual void Dispose(bool disposing) // Check to see if Dispose has already been called. if (!_disposed) { - Log.Verbose(); + _logger?.LogTrace("Disposing Animation"); if (disposing) { @@ -421,22 +424,22 @@ private void resolveNonWildCardReferences(Widget rootWidget, Variables variables { var name = XmlUtils.GetXMLAttrString(xmlNode, "name"); - Log.Verbose("name=" + name); + _logger?.LogTrace("name={Name}", name); if (!String.IsNullOrEmpty(name) && !name.Contains("*")) { var widgetName = resolveName(variables, name); - Log.Verbose("Resolved name : " + widgetName); + _logger?.LogTrace("Resolved name: {WidgetName}", widgetName); var uiWidget = rootWidget.Finder.FindChild(widgetName); if (uiWidget != null && (uiWidget.UIControl == null || uiWidget.Visible)) { - Log.Verbose("Found child name : " + widgetName); + _logger?.LogTrace("Found child name: {WidgetName}", widgetName); var animationWidget = createAndAddAnimationWidget(uiWidget); animationWidget?.Load(xmlNode); } else { - Log.Debug("Did not find child " + widgetName); + _logger?.LogDebug("Did not find child {WidgetName}", widgetName); } } @@ -458,12 +461,12 @@ private void resolveWildCardReferences(Widget rootWidget, Variables variables, X if (name.Contains("*")) { - Log.Debug("name=" + name); + _logger?.LogDebug("name={Name}", name); var containerWidget = getContainerWidget(rootWidget, variables, name); if (containerWidget != null) { - Log.Debug("containerWidget: " + containerWidget.Name); + _logger?.LogDebug("containerWidget: {ContainerWidgetName}", containerWidget.Name); EvtResolveWidgetChildren?.Invoke(this, new ResolveWidgetChildrenEventArgs(rootWidget, containerWidget, xmlNode)); @@ -471,7 +474,7 @@ private void resolveWildCardReferences(Widget rootWidget, Variables variables, X { if (childWidget.UIControl == null || childWidget.Visible) { - Log.Debug("Found child name : " + childWidget.Name); + _logger?.LogDebug("Found child name: {ChildWidgetName}", childWidget.Name); var animationWidget = createAndAddAnimationWidget(childWidget); animationWidget?.Load(xmlNode); } diff --git a/src/Libraries/ACATCore/AnimationManagement/AnimationManager.cs b/src/Libraries/ACATCore/AnimationManagement/AnimationManager.cs index 2ead59ec..e0c9ba6d 100644 --- a/src/Libraries/ACATCore/AnimationManagement/AnimationManager.cs +++ b/src/Libraries/ACATCore/AnimationManagement/AnimationManager.cs @@ -5,6 +5,7 @@ using ACAT.Core.Utility; using ACAT.Core.WidgetManagement; using ACAT.Core.WidgetManagement.Interfaces; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Media; @@ -86,6 +87,8 @@ namespace ACAT.Core.AnimationManagement { public partial class AnimationManager : IAnimationManager, IDisposable { + private static readonly ILogger _logger = LoggerFactory.Create(builder => builder.AddConsole()).CreateLogger(); + /// /// Collection of animations for this panel /// @@ -381,16 +384,16 @@ public void Stop() { if (_player != null) { - Log.Verbose("Before animation player stop"); + _logger.LogTrace("Before animation player stop"); try { _player.Stop(); } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex, ex.Message); } - Log.Verbose("After animation player stop"); + _logger.LogTrace("After animation player stop"); } } @@ -407,7 +410,7 @@ public void Transition(Animation animation = null) { if (animation != null) { - Log.Verbose("Transition( " + animation.Name + "). _currentPanel: " + _currentPanel.Name); + _logger.LogTrace("Transition( {AnimationName}). _currentPanel: {PanelName}", animation.Name, _currentPanel.Name); _player.Transition(animation); } else @@ -422,7 +425,7 @@ public void Transition(Animation animation = null) } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex, ex.Message); } } @@ -436,7 +439,7 @@ protected void Dispose(bool disposing) // Check to see if Dispose has already been called. if (!_disposed) { - Log.Verbose(); + _logger.LogTrace(""); if (disposing) { @@ -483,7 +486,7 @@ protected virtual void actuatorManager_EvtSwitchDown(object sender, ActuatorSwit var widget = _player.HighlightedAnimationWidget; if (widget != null) { - Log.Verbose("Highlighted widget: " + widget.UIWidget.Name); + _logger.LogTrace("Highlighted widget: {WidgetName}", widget.UIWidget.Name); _switchDownHighlightedWidget = widget; } else @@ -567,13 +570,13 @@ protected void AppInterpreter_EvtActuateNotify(object sender, InterpreterEventA var widget = _currentPanel.Finder.FindChild(widgetName); if (widget != null) { - Log.Info("Actuate. widgetname: " + widget.Name + " Text: " + widget.GetText()); + _logger.LogInformation("Actuate. widgetname: {WidgetName} Text: {Text}", widget.Name, widget.GetText()); widget.Actuate(); } else { - Log.Warn("Did not actuate. Could not find widget " + widgetName); + _logger.LogWarning("Did not actuate. Could not find widget {WidgetName}", widgetName); } } } @@ -623,7 +626,7 @@ protected void AppInterpreter_EvtHighlightSelectedNotify(object sender, Interpre String widgetName = resolvedArgs[0]; - Log.Verbose("_currentPanel " + _currentPanel.Name + " widgetname: " + widgetName); + _logger.LogTrace("_currentPanel {PanelName} widgetname: {WidgetName}", _currentPanel.Name, widgetName); var widget = _currentPanel.Finder.FindChild(widgetName); if (widget != null) { @@ -672,13 +675,13 @@ protected void AppInterpreter_EvtStop(object sender, InterpreterEventArgs e) /// Argument list protected void AppInterpreter_EvtTransitionNotify(object sender, InterpreterEventArgs e) { - Log.Verbose(); + _logger.LogTrace(""); List resolvedArgs = ResolveArgs(e.Args); if (resolvedArgs.Count > 0) { String targetAnimation = resolvedArgs[0]; - Log.Verbose(targetAnimation); + _logger.LogTrace("{TargetAnimation}", targetAnimation); //Transition(GetAnimation(targetAnimation)); TransitionFromName(targetAnimation); } @@ -834,7 +837,7 @@ protected void playBeep(IActuatorSwitch switchObj) } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, ex.Message); } } @@ -851,7 +854,7 @@ protected void playDefaultBeep() } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, ex.Message); } } diff --git a/src/Libraries/ACATCore/AnimationManagement/AnimationPlayer.cs b/src/Libraries/ACATCore/AnimationManagement/AnimationPlayer.cs index f9536c35..bc2c48a7 100644 --- a/src/Libraries/ACATCore/AnimationManagement/AnimationPlayer.cs +++ b/src/Libraries/ACATCore/AnimationManagement/AnimationPlayer.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; @@ -66,6 +67,8 @@ public enum PlayerState /// internal class AnimationPlayer : IDisposable { + private readonly ILogger _logger; + /// /// Interpreter to interpret animation code /// @@ -169,7 +172,8 @@ internal class AnimationPlayer : IDisposable /// variables and their values public AnimationPlayer(Widget rootWidget, Interpret interpreter, Variables variables) { - Log.Verbose("CTOR(" + rootWidget.Name + ")"); + _logger = LoggingConfiguration.CreateLogger(); + _logger.LogTrace("CTOR(" + rootWidget.Name + ")"); if (rootWidget.UIControl is IPanel) { _syncObj = ((IPanel)rootWidget.UIControl).SyncObj; @@ -327,12 +331,12 @@ public void HighlightDefaultHome() /// public void Interrupt() { - Log.Verbose("Interrupt(" + _rootWidget.Name + ")"); + _logger.LogTrace("Interrupt(" + _rootWidget.Name + ")"); if (_timer != null && (_playerState == PlayerState.Running || _playerState == PlayerState.Timeout)) { - Log.Verbose("Interrupt timer for panel " + _rootWidget.Name); + _logger.LogTrace("Interrupt timer for panel " + _rootWidget.Name); _timer.Stop(); setPlayerState(PlayerState.Interrupted); @@ -375,14 +379,14 @@ public void ManualScanActuateWidget(Widget widget) /// public void Pause() { - Log.Verbose("Pause(" + _rootWidget.Name + ")"); + _logger.LogTrace("Pause(" + _rootWidget.Name + ")"); if (_timer != null && (_playerState == PlayerState.Running || _playerState == PlayerState.Timeout || _playerState == PlayerState.Interrupted)) { - Log.Verbose("AP1: Stop timer for panel " + _rootWidget.Name); + _logger.LogTrace("AP1: Stop timer for panel " + _rootWidget.Name); _timer.Stop(); @@ -398,21 +402,21 @@ public void Pause() /// transition to this animation public void Resume(Animation animation = null) { - Log.Verbose("Resume(" + _rootWidget.Name + ") +, state: " + _playerState); + _logger.LogTrace("Resume(" + _rootWidget.Name + ") +, state: " + _playerState); if ((_playerState == PlayerState.Paused || _playerState == PlayerState.Timeout || _playerState == PlayerState.Interrupted) && _timer != null) { - Log.Verbose("Resume(" + _rootWidget.Name + ") Setting player state to running"); + _logger.LogTrace("Resume(" + _rootWidget.Name + ") Setting player state to running"); setPlayerState(PlayerState.Running); if (!CoreGlobals.AppPreferences.EnableManualScan) { if (animation != null) { - Log.Verbose("In Resume Calling Transition"); + _logger.LogTrace("In Resume Calling Transition"); Transition(animation); } } @@ -430,25 +434,25 @@ public void Stop() { if (_timer == null) { - Log.Verbose("_heartbeatTimer is null"); + _logger.LogTrace("_heartbeatTimer is null"); return; } _timer.Elapsed -= timer_Elapsed; - Log.Verbose("Inside stopthread. before enter " + _rootWidget.UIControl.Name); + _logger.LogTrace("Inside stopthread. before enter " + _rootWidget.UIControl.Name); tryEnterUntilSuccess(_transitionSync); - Log.Verbose("Inside stopthread. after enter " + _rootWidget.UIControl.Name); + _logger.LogTrace("Inside stopthread. after enter " + _rootWidget.UIControl.Name); _timer.Stop(); - Log.Verbose("Inside stopthread. before exit" + _rootWidget.UIControl.Name); + _logger.LogTrace("Inside stopthread. before exit" + _rootWidget.UIControl.Name); Monitor.Exit(_transitionSync); - Log.Verbose("Inside stopthread. after exit" + _rootWidget.UIControl.Name); + _logger.LogTrace("Inside stopthread. after exit" + _rootWidget.UIControl.Name); - Log.Verbose("Stop" + _rootWidget.UIControl.Name + ", syncobj.status " + _syncObj.Status + ", intimer: " + _inTimer); + _logger.LogTrace("Stop" + _rootWidget.UIControl.Name + ", syncobj.status " + _syncObj.Status + ", intimer: " + _inTimer); setPlayerState(PlayerState.Stopped); _timer.Dispose(); @@ -464,7 +468,7 @@ public void Transition(Animation animation = null) { if (_syncObj == null) { - Log.Verbose("_syncObj is null. returning"); + _logger.LogTrace("_syncObj is null. returning"); return; } @@ -478,18 +482,18 @@ public void Transition(Animation animation = null) if (animation != null) { - Log.Verbose("Transition to " + animation.Name); + _logger.LogTrace("Transition to " + animation.Name); } setPlayerState(PlayerState.Stopped); - Log.Verbose("Transition : Before Enter " + _rootWidget.UIControl.Name + ", threadid: " + Kernel32Interop.GetCurrentThreadId()); + _logger.LogTrace("Transition : Before Enter " + _rootWidget.UIControl.Name + ", threadid: " + Kernel32Interop.GetCurrentThreadId()); tryEnterUntilSuccess(_transitionSync); - Log.Verbose("Transition : After Enter " + _rootWidget.UIControl.Name + ", status: " + _syncObj.Status); + _logger.LogTrace("Transition : After Enter " + _rootWidget.UIControl.Name + ", status: " + _syncObj.Status); if (_syncObj.IsClosing()) { - Log.Verbose("FORM IS CLOSING. releasing _transitionSync and returning" + _rootWidget.UIControl.Name); + _logger.LogTrace("FORM IS CLOSING. releasing _transitionSync and returning" + _rootWidget.UIControl.Name); release(_transitionSync); return; } @@ -514,11 +518,11 @@ public void Transition(Animation animation = null) _currentWidgetIndex = getFirstAnimatedWidget(); _highlightedAnimationWidget = null; - Log.Verbose("Transition : Before Release " + _rootWidget.UIControl.Name); + _logger.LogTrace("Transition : Before Release " + _rootWidget.UIControl.Name); release(_transitionSync); - Log.Verbose("Transition : After Release " + _rootWidget.UIControl.Name); + _logger.LogTrace("Transition : After Release " + _rootWidget.UIControl.Name); - Log.Verbose("Start new animation " + animation.Name); + _logger.LogTrace("Start new animation " + animation.Name); if (!animation.AutoStart && animation.OnStart) { @@ -537,17 +541,17 @@ public void Transition(Animation animation = null) } */ _timer.Interval = _currentAnimation.SteppingTime; - Log.Verbose(_rootWidget.UIControl.Name + ", syncobj.status " + _syncObj.Status); + _logger.LogTrace(_rootWidget.UIControl.Name + ", syncobj.status " + _syncObj.Status); if (_syncObj.Status == SyncLock.StatusValues.None) { timer_Elapsed(null, null); - Log.Verbose("Starting timer " + _rootWidget.UIControl.Name); + _logger.LogTrace("Starting timer " + _rootWidget.UIControl.Name); _timer.Start(); } else { - Log.Verbose("******** WILL NOT START TIMER!!!" + + _logger.LogTrace("******** WILL NOT START TIMER!!!" + _rootWidget.UIControl.Name + ", syncobj.status " + _syncObj.Status); } @@ -557,10 +561,10 @@ public void Transition(Animation animation = null) } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex.ToString()); } - Log.Verbose("Returning"); + _logger.LogTrace("Returning"); } /// @@ -571,7 +575,7 @@ public void TransitionManualScan(ManualScanModes manualScanMode = ManualScanMode { if (_syncObj == null) { - Log.Verbose("_syncObj is null. returning"); + _logger.LogTrace("_syncObj is null. returning"); return; } @@ -602,9 +606,9 @@ public void TransitionManualScan(ManualScanModes manualScanMode = ManualScanMode _delayedSelect = false; _delayedSelect2 = false; - Log.Verbose("manualScanMode is " + manualScanMode); + _logger.LogTrace("manualScanMode is " + manualScanMode); - Log.Verbose(_playerState + ", " + _manualScanMode); + _logger.LogTrace(_playerState + ", " + _manualScanMode); if (_playerState == PlayerState.Running) { if (checkStopManualAutoScan(manualScanMode)) @@ -625,20 +629,20 @@ public void TransitionManualScan(ManualScanModes manualScanMode = ManualScanMode setPlayerState(PlayerState.Stopped); - Log.Verbose("Transition : Before Enter " + _rootWidget.UIControl.Name + ", threadid: " + Kernel32Interop.GetCurrentThreadId()); + _logger.LogTrace("Transition : Before Enter " + _rootWidget.UIControl.Name + ", threadid: " + Kernel32Interop.GetCurrentThreadId()); tryEnterUntilSuccess(_transitionSync); - Log.Verbose("Transition : After Enter " + _rootWidget.UIControl.Name + ", status: " + _syncObj.Status); + _logger.LogTrace("Transition : After Enter " + _rootWidget.UIControl.Name + ", status: " + _syncObj.Status); if (_syncObj.IsClosing()) { - Log.Verbose("FORM IS CLOSING. releasing _transitionSync and returning" + _rootWidget.UIControl.Name); + _logger.LogTrace("FORM IS CLOSING. releasing _transitionSync and returning" + _rootWidget.UIControl.Name); release(_transitionSync); return; } if (_highlightedWidget == null) { - Log.Verbose("_highlightedWidget is null"); + _logger.LogTrace("_highlightedWidget is null"); HighlightDefaultHome(); } @@ -671,10 +675,10 @@ public void TransitionManualScan(ManualScanModes manualScanMode = ManualScanMode bool handled = handleSingleMove(); - Log.Verbose("Transition : Before Release " + _rootWidget.UIControl.Name); + _logger.LogTrace("Transition : Before Release " + _rootWidget.UIControl.Name); release(_transitionSync); - Log.Verbose("Transition : After Release " + _rootWidget.UIControl.Name); + _logger.LogTrace("Transition : After Release " + _rootWidget.UIControl.Name); if (handled) { @@ -685,17 +689,17 @@ public void TransitionManualScan(ManualScanModes manualScanMode = ManualScanMode if (_timer != null) { _timer.Interval = CoreGlobals.AppPreferences.ScanTime; - Log.Verbose(_rootWidget.UIControl.Name + ", syncobj.status " + _syncObj.Status); + _logger.LogTrace(_rootWidget.UIControl.Name + ", syncobj.status " + _syncObj.Status); if (_syncObj.Status == SyncLock.StatusValues.None) { timer_Elapsed(null, null); - Log.Verbose("Starting timer " + _rootWidget.UIControl.Name); + _logger.LogTrace("Starting timer " + _rootWidget.UIControl.Name); _timer.Start(); } else { - Log.Verbose("******** WILL NOT START TIMER!!!" + _rootWidget.UIControl.Name + ", syncobj.status " + _syncObj.Status); + _logger.LogTrace("******** WILL NOT START TIMER!!!" + _rootWidget.UIControl.Name + ", syncobj.status " + _syncObj.Status); } setPlayerState(PlayerState.Running); @@ -703,10 +707,10 @@ public void TransitionManualScan(ManualScanModes manualScanMode = ManualScanMode } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex.ToString()); } - Log.Verbose("Returning"); + _logger.LogTrace("Returning"); } /// @@ -718,8 +722,6 @@ protected virtual void Dispose(bool disposing) // Check to see if Dispose has already been called. if (!_disposed) { - Log.Verbose(); - if (disposing) { // dispose all managed resources. @@ -745,7 +747,7 @@ private int animatedWidgetCount() } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex.ToString()); return 0; } } @@ -758,7 +760,7 @@ private void check() { if (_syncObj != null && _syncObj.IsClosing()) { - Log.Verbose("Scanner closed" + _rootWidget.UIControl.Name); + _logger.LogTrace("Scanner closed" + _rootWidget.UIControl.Name); throw new Exception(); } } @@ -798,22 +800,22 @@ private bool checkStopManualAutoScan(ManualScanModes scanMode) /// Tag private void dumpManualPath(String tag) { - Log.Verbose(tag + " ---------------------"); + _logger.LogTrace(tag + " ---------------------"); if (_manualScanPath != null) { if (_manualScanPath.Count == 0) { - Log.Verbose("None found"); + _logger.LogTrace("None found"); } else { foreach (var h in _manualScanPath) { - Log.Verbose(h.Name); + _logger.LogTrace(h.Name); } } } - Log.Verbose("---------------------"); + _logger.LogTrace("---------------------"); } /// @@ -824,7 +826,6 @@ private void dumpManualPath(String tag) /// index of the first animation widget private int getFirstAnimatedWidget() { - Log.Verbose(); for (int ii = 0; ii < _currentAnimation.AnimationWidgetList.Count; ii++) { if (_currentAnimation.AnimationWidgetList[ii].UIWidget.CanAddForAnimation()) @@ -865,7 +866,7 @@ private int getNextAnimatedWidget(int index) } catch (Exception ex) { - Log.Exception("ex=" + ex.Message); + _logger.LogError("ex=" + ex.Message); return -1; } } @@ -1149,11 +1150,9 @@ private bool handleSingleMove() /// private void highlightNeighborAbove() { - Log.Verbose(); - if (_highlightedWidget == null) { - Log.Verbose("_widgethighlighted is null"); + _logger.LogTrace("_widgethighlighted is null"); return; } @@ -1173,7 +1172,7 @@ private void highlightNeighborAbove() above ??= _highlightedWidget.Above[0]; - Log.Verbose("above: " + above.Name); + _logger.LogTrace("above: " + above.Name); above.HighlightOn(); if (!_manualScanPath.Contains(above)) { @@ -1184,11 +1183,11 @@ private void highlightNeighborAbove() } else { - Log.Verbose("above is null. Will get wraparound"); + _logger.LogTrace("above is null. Will get wraparound"); var bottomMost = getWraparoundWidgetBottom(); if (bottomMost != null) { - Log.Verbose("bottomMost is " + bottomMost.Name); + _logger.LogTrace("bottomMost is " + bottomMost.Name); bottomMost.HighlightOn(); if (!_manualScanPath.Contains(bottomMost)) @@ -1206,11 +1205,9 @@ private void highlightNeighborAbove() /// private void highlightNeighborBelow() { - Log.Verbose(); - if (_highlightedWidget == null) { - Log.Verbose("_widgethighlighted is null"); + _logger.LogTrace("_widgethighlighted is null"); return; } @@ -1230,7 +1227,7 @@ private void highlightNeighborBelow() below ??= _highlightedWidget.Below[0]; - Log.Verbose("below: " + below.Name); + _logger.LogTrace("below: " + below.Name); below.HighlightOn(); if (!_manualScanPath.Contains(below)) { @@ -1240,11 +1237,11 @@ private void highlightNeighborBelow() } else { - Log.Verbose("Below is null. Will get wraparound"); + _logger.LogTrace("Below is null. Will get wraparound"); var topMost = getWraparoundWidgetTop(); if (topMost != null) { - Log.Verbose("topMost is " + topMost.Name); + _logger.LogTrace("topMost is " + topMost.Name); topMost.HighlightOn(); if (!_manualScanPath.Contains(topMost)) @@ -1263,8 +1260,6 @@ private void highlightNeighborBelow() /// private void highlightNeighborLeft() { - Log.Verbose(); - if (_highlightedWidget == null) { return; @@ -1286,7 +1281,7 @@ private void highlightNeighborLeft() left ??= _highlightedWidget.Left[0]; - Log.Verbose("Left: " + left.Name); + _logger.LogTrace("Left: " + left.Name); left.HighlightOn(); if (!_manualScanPath.Contains(left)) { @@ -1298,11 +1293,11 @@ private void highlightNeighborLeft() { // reached the left edge of the form. Wrap around // to start scanning at the right edge - Log.Verbose("Left is null. Will get wraparound"); + _logger.LogTrace("Left is null. Will get wraparound"); var rightmost = getWraparoundWidgetRight(); if (rightmost != null) { - Log.Verbose("Leftmost is " + rightmost.Name); + _logger.LogTrace("Leftmost is " + rightmost.Name); rightmost.HighlightOn(); if (!_manualScanPath.Contains(rightmost)) @@ -1342,7 +1337,7 @@ private void highlightNeighborRight() right ??= _highlightedWidget.Right[0]; - Log.Verbose("Right: " + right.Name); + _logger.LogTrace("Right: " + right.Name); right.HighlightOn(); if (!_manualScanPath.Contains(right)) { @@ -1397,13 +1392,13 @@ private void release(Object syncObj) { try { - //Log.Verbose("Before EXIT for " + _rootWidget.UIControl.Name); + //_logger.LogTrace("Before EXIT for " + _rootWidget.UIControl.Name); Monitor.Exit(syncObj); - //Log.Verbose("After EXIT for " + _rootWidget.UIControl.Name); + //_logger.LogTrace("After EXIT for " + _rootWidget.UIControl.Name); } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, ex.Message); } } @@ -1414,16 +1409,14 @@ private void release(Object syncObj) /// new state private void setPlayerState(PlayerState playerState) { - Log.Verbose(); - PlayerState oldState = _playerState; if (oldState != playerState) { - Log.Verbose(_rootWidget.Name + ":Set player state to " + playerState); + _logger.LogTrace(_rootWidget.Name + ":Set player state to " + playerState); _playerState = playerState; if (EvtPlayerStateChanged != null) { - Log.Verbose("Calling evtPlayerStateChanged"); + _logger.LogTrace("Calling evtPlayerStateChanged"); EvtPlayerStateChanged.BeginInvoke(this, new PlayerStateChangedEventArgs(oldState, _playerState), null, null); } } @@ -1463,13 +1456,13 @@ private void timerElapsedAutoScan(object sender, ElapsedEventArgs e) { if (_syncObj.IsClosing()) { - Log.Verbose("Form is closing. Returning" + _rootWidget.UIControl.Name); + _logger.LogTrace("Form is closing. Returning" + _rootWidget.UIControl.Name); return; } if (_inTimer) { - Log.Verbose("Timer is busy. returning"); + _logger.LogTrace("Timer is busy. returning"); return; } @@ -1477,24 +1470,24 @@ private void timerElapsedAutoScan(object sender, ElapsedEventArgs e) try { - Log.Verbose("Before tryEnter " + _rootWidget.UIControl.Name + ", threadid: " + Kernel32Interop.GetCurrentThreadId()); + _logger.LogTrace("Before tryEnter " + _rootWidget.UIControl.Name + ", threadid: " + Kernel32Interop.GetCurrentThreadId()); if (!tryEnter(_transitionSync)) { - Log.Verbose("_transition sync will block returning"); + _logger.LogTrace("_transition sync will block returning"); return; } - Log.Verbose("After tryEnter" + _rootWidget.UIControl.Name + ", status: " + _syncObj.Status); + _logger.LogTrace("After tryEnter" + _rootWidget.UIControl.Name + ", status: " + _syncObj.Status); if (_syncObj.IsClosing()) { - Log.Verbose("Form is closing. Returning" + _rootWidget.UIControl.Name); + _logger.LogTrace("Form is closing. Returning" + _rootWidget.UIControl.Name); return; } check(); - Log.Verbose("CurrentAnimation: " + _currentAnimation.Name + + _logger.LogTrace("CurrentAnimation: " + _currentAnimation.Name + ". Count: " + _currentAnimation.AnimationWidgetList.Count + ". currentWidgetIndex: " + _currentWidgetIndex); @@ -1502,14 +1495,14 @@ private void timerElapsedAutoScan(object sender, ElapsedEventArgs e) var animationWidget = _currentAnimation.AnimationWidgetList[_currentWidgetIndex]; - Log.Verbose(_rootWidget.UIControl.Name + ", status: " + _syncObj.Status); + _logger.LogTrace(_rootWidget.UIControl.Name + ", status: " + _syncObj.Status); // if any switch is currently engaged, keep the current widget // highlighted until the user releases the switch //if (ActuatorManager.Instance.IsSwitchActive()) if (IsSwitchActive) { - Log.Verbose("Some switch is active. Will try again"); + _logger.LogTrace("Some switch is active. Will try again"); return; } @@ -1522,7 +1515,7 @@ private void timerElapsedAutoScan(object sender, ElapsedEventArgs e) check(); - Log.Verbose(_rootWidget.UIControl.Name + ", status: " + _syncObj.Status); + _logger.LogTrace(_rootWidget.UIControl.Name + ", status: " + _syncObj.Status); if (!_currentAnimation.IsFirst && animatedWidgetCount() == 0) { @@ -1556,7 +1549,7 @@ private void timerElapsedAutoScan(object sender, ElapsedEventArgs e) } else { - Log.Verbose("Timer is null. returning"); + _logger.LogTrace("Timer is null. returning"); return; } @@ -1578,7 +1571,7 @@ private void timerElapsedAutoScan(object sender, ElapsedEventArgs e) if (_highlightedAnimationWidget != null && _highlightedAnimationWidget != animationWidget) { - Log.Verbose(string.Format("Animation: {0}. Turning off . name = {1}. Count: {2}", + _logger.LogTrace(string.Format("Animation: {0}. Turning off . name = {1}. Count: {2}", _currentAnimation.Name, _highlightedAnimationWidget.UIWidget.Name, _currentAnimation.AnimationWidgetList.Count)); @@ -1600,7 +1593,7 @@ private void timerElapsedAutoScan(object sender, ElapsedEventArgs e) // now turn the highlight on on the next widget in the sequence animationWidget = _currentAnimation.AnimationWidgetList[_currentWidgetIndex]; - Log.Verbose("Animation: " + _currentAnimation.Name + + _logger.LogTrace("Animation: " + _currentAnimation.Name + ". Turning on " + _currentWidgetIndex + ". name = " + animationWidget.UIWidget.Name); @@ -1629,7 +1622,7 @@ private void timerElapsedAutoScan(object sender, ElapsedEventArgs e) } else { - Log.Verbose("timer is null. returning"); + _logger.LogTrace("timer is null. returning"); return; } @@ -1664,18 +1657,18 @@ private void timerElapsedAutoScan(object sender, ElapsedEventArgs e) } catch (Exception ex) { - Log.Exception("AnimationPlayerexception " + ex); + _logger.LogError("AnimationPlayerexception " + ex); } finally { - Log.Verbose("Before release " + _rootWidget.UIControl.Name); + _logger.LogTrace("Before release " + _rootWidget.UIControl.Name); release(_transitionSync); - Log.Verbose("After release " + _rootWidget.UIControl.Name); + _logger.LogTrace("After release " + _rootWidget.UIControl.Name); - Log.Verbose("Setting intimer to false " + _rootWidget.UIControl.Name); + _logger.LogTrace("Setting intimer to false " + _rootWidget.UIControl.Name); _inTimer = false; - Log.Verbose("Exiting timer " + _rootWidget.UIControl.Name); + _logger.LogTrace("Exiting timer " + _rootWidget.UIControl.Name); } } @@ -1688,17 +1681,17 @@ private void timerElapsedManual(object sender, ElapsedEventArgs e) { bool actuate = false; - Log.Verbose("------------->>> ENTER "); + _logger.LogTrace("------------->>> ENTER "); if (_syncObj.IsClosing()) { - Log.Verbose("Form is closing. Returning" + _rootWidget.UIControl.Name); + _logger.LogTrace("Form is closing. Returning" + _rootWidget.UIControl.Name); return; } if (_inTimer) { - Log.Verbose("Timer is busy. returning"); + _logger.LogTrace("Timer is busy. returning"); return; } @@ -1711,31 +1704,31 @@ private void timerElapsedManual(object sender, ElapsedEventArgs e) try { - Log.Verbose("Before tryEnter " + _rootWidget.UIControl.Name + ", threadid: " + Kernel32Interop.GetCurrentThreadId()); + _logger.LogTrace("Before tryEnter " + _rootWidget.UIControl.Name + ", threadid: " + Kernel32Interop.GetCurrentThreadId()); if (!tryEnter(_transitionSync)) { - Log.Verbose("_transition sync will block returning"); + _logger.LogTrace("_transition sync will block returning"); return; } - Log.Verbose("After tryEnter" + _rootWidget.UIControl.Name + ", status: " + _syncObj.Status); + _logger.LogTrace("After tryEnter" + _rootWidget.UIControl.Name + ", status: " + _syncObj.Status); if (_syncObj.IsClosing()) { - Log.Verbose("Form is closing. Returning" + _rootWidget.UIControl.Name); + _logger.LogTrace("Form is closing. Returning" + _rootWidget.UIControl.Name); return; } check(); - Log.Verbose(_rootWidget.UIControl.Name + ", status: " + _syncObj.Status); + _logger.LogTrace(_rootWidget.UIControl.Name + ", status: " + _syncObj.Status); // if any switch is currently engaged, keep the current widget // highlighted until the user releases the switch //if (ActuatorManager.Instance.IsSwitchActive()) if (IsSwitchActive) { - Log.Verbose("Some switch is active. Will try again"); + _logger.LogTrace("Some switch is active. Will try again"); return; } @@ -1765,7 +1758,7 @@ private void timerElapsedManual(object sender, ElapsedEventArgs e) } } - Log.Verbose("_manualScanMode is " + _manualScanMode); + _logger.LogTrace("_manualScanMode is " + _manualScanMode); var prevWidgetHighlighted = _highlightedWidget; @@ -1790,29 +1783,29 @@ private void timerElapsedManual(object sender, ElapsedEventArgs e) if (prevWidgetHighlighted == _highlightedWidget) { - Log.Verbose("Same widget. Stopping timer"); + _logger.LogTrace("Same widget. Stopping timer"); _timer?.Stop(); } check(); } catch (Exception ex) { - Log.Exception("AnimationPlayerexception " + ex); + _logger.LogError("AnimationPlayerexception " + ex); } finally { - Log.Verbose("Before release " + _rootWidget.UIControl.Name); + _logger.LogTrace("Before release " + _rootWidget.UIControl.Name); release(_transitionSync); - Log.Verbose("After release " + _rootWidget.UIControl.Name); + _logger.LogTrace("After release " + _rootWidget.UIControl.Name); - Log.Verbose("Setting intimer to false " + _rootWidget.UIControl.Name); + _logger.LogTrace("Setting intimer to false " + _rootWidget.UIControl.Name); _inTimer = false; if (actuate) { ManualScanActuateWidget(_highlightedWidget); } - Log.Verbose("----------- <<<< Exiting timer " + _rootWidget.UIControl.Name); + _logger.LogTrace("----------- <<<< Exiting timer " + _rootWidget.UIControl.Name); } } @@ -1832,7 +1825,7 @@ private void tryEnterUntilSuccess(object syncObj) { while (!tryEnter(syncObj)) { - Log.Verbose("CALLING DOEVENTS"); + _logger.LogTrace("CALLING DOEVENTS"); if (Application.MessageLoop) { Application.DoEvents(); diff --git a/src/Libraries/ACATCore/AnimationManagement/PanelAnimationManager.cs b/src/Libraries/ACATCore/AnimationManagement/PanelAnimationManager.cs index d42af578..023b24ea 100644 --- a/src/Libraries/ACATCore/AnimationManagement/PanelAnimationManager.cs +++ b/src/Libraries/ACATCore/AnimationManagement/PanelAnimationManager.cs @@ -11,17 +11,23 @@ using ACAT.Core.Utility; using ACAT.Core.WidgetManagement; using ACAT.Core.WidgetManagement.Interfaces; +using Microsoft.Extensions.Logging; using System; namespace ACAT.Core.AnimationManagement { public class PanelAnimationManager : AnimationManager, IPanelAnimationManager { + private readonly ILogger _logger; + private String _panelClass = String.Empty; private PanelConfigMapEntry _panelConfigMapEntry; - public PanelAnimationManager() : base() { } + public PanelAnimationManager(ILogger logger) : base() + { + _logger = logger; + } public bool Init(PanelConfigMapEntry panelConfigMapEntry, Widget panelWidget = null) { @@ -44,14 +50,14 @@ public bool Init(PanelConfigMapEntry panelConfigMapEntry, Widget panelWidget = n subscribeToActuatorEvents(); } - Log.Debug("returning from Anim manager init()"); + _logger.LogDebug("returning from Anim manager init()"); return retVal; } public void Start(Widget panelWidget, String animationName = null) { - Log.Debug("Start animation for panel " + panelWidget.Name); + _logger.LogDebug("Start animation for panel {PanelName}", panelWidget.Name); if (_player != null) { @@ -81,7 +87,7 @@ public void Start(Widget panelWidget, String animationName = null) { if (animations == null) { - Log.Error("Could not find animations entry for panel " + panelWidget.Name); + _logger.LogError("Could not find animations entry for panel {PanelName}", panelWidget.Name); return; } @@ -111,15 +117,15 @@ public override void TransitionFromName(String animationName) { try { - Log.Verbose(); + _logger.LogTrace("TransitionFromName called"); - Log.Debug("_currentPanel: " + _currentPanel); + _logger.LogDebug("_currentPanel: {CurrentPanel}", _currentPanel); resetSwitchEventStates(); if (_player == null) { - Log.Debug("_player is null"); + _logger.LogDebug("_player is null"); return; } @@ -132,16 +138,16 @@ public override void TransitionFromName(String animationName) var animation = animations[animationName]; if (animation == null) { - Log.Debug("Transition: animation is NULL!"); + _logger.LogDebug("Transition: animation is NULL!"); return; } - Log.Debug("Calling player transition"); + _logger.LogDebug("Calling player transition"); _player.Transition(animation); } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex, "{ExceptionMessage}", ex.Message); } } @@ -161,13 +167,13 @@ protected override void actuatorManager_EvtSwitchActivated(object sender, Actuat return; } - Log.Debug("switch: " + switchObj.Name); - Log.Debug(" Panel: " + _currentPanel.Name); + _logger.LogDebug("switch: {SwitchName}", switchObj.Name); + _logger.LogDebug(" Panel: {PanelName}", _currentPanel.Name); if (_currentPanel.UIControl is System.Windows.Forms.Form) { bool visible = Windows.GetVisible(_currentPanel.UIControl); - Log.Debug("Form: " + _currentPanel.UIControl.Name + ", visible: " + visible); + _logger.LogDebug("Form: {FormName}, visible: {Visible}", _currentPanel.UIControl.Name, visible); if (!visible) { return; @@ -178,7 +184,7 @@ protected override void actuatorManager_EvtSwitchActivated(object sender, Actuat String onTrigger = switchObj.Command; if (String.IsNullOrEmpty(onTrigger)) { - Log.Debug("OnTrigger is null. returning"); + _logger.LogDebug("OnTrigger is null. returning"); return; } @@ -195,7 +201,7 @@ protected override void actuatorManager_EvtSwitchActivated(object sender, Actuat return; } - Log.Debug("playerState: " + _player.State); + _logger.LogDebug("playerState: {PlayerState}", _player.State); // execute action if the player is in the right state. if (_player.State != PlayerState.Stopped && @@ -210,11 +216,11 @@ protected override void actuatorManager_EvtSwitchActivated(object sender, Actuat if (CoreGlobals.AppPreferences.EnableManualScan) { - Log.Debug("HOOO form: " + _currentPanel.UIControl.Name + " Player state: " + _player.State); + _logger.LogDebug("HOOO form: {FormName} Player state: {PlayerState}", _currentPanel.UIControl.Name, _player.State); if (_player.State == PlayerState.Paused) { - Log.Debug(_currentPanel.Name + ": Player is paused. Returning"); + _logger.LogDebug("{PanelName}: Player is paused. Returning", _currentPanel.Name); return; } @@ -223,7 +229,7 @@ protected override void actuatorManager_EvtSwitchActivated(object sender, Actuat var widget = _player.HighlightedWidget; if (widget != null) { - Log.Debug("Actuate. widgetname: " + widget.Name + " Text: " + widget.GetText()); + _logger.LogDebug("Actuate. widgetname: {WidgetName} Text: {WidgetText}", widget.Name, widget.GetText()); _player.Interrupt(); _player.ManualScanActuateWidget(widget); } @@ -238,15 +244,15 @@ protected override void actuatorManager_EvtSwitchActivated(object sender, Actuat if (_player.State == PlayerState.Timeout || _player.State == PlayerState.Interrupted) { - Log.Debug("Calling player transition for firstanimation"); + _logger.LogDebug("Calling player transition for firstanimation"); _player.Transition(_firstAnimation); return; } - Log.Debug("Player state is " + _player.State); + _logger.LogDebug("Player state is {PlayerState}", _player.State); if (_player.State != PlayerState.Running) { - Log.Debug(_currentPanel.Name + ": Player is not Running. Returning"); + _logger.LogDebug("{PanelName}: Player is not Running. Returning", _currentPanel.Name); return; } @@ -285,9 +291,10 @@ protected override void actuatorManager_EvtSwitchActivated(object sender, Actuat highlightedWidget.UIWidget.GetType().Name, widgetName)); - Log.Debug(_currentPanel.Name + ": Switch on " + - highlightedWidget.UIWidget.Name + " type: " + - highlightedWidget.UIWidget.GetType().Name); + _logger.LogDebug("{PanelName}: Switch on {WidgetName} type: {WidgetType}", + _currentPanel.Name, + highlightedWidget.UIWidget.Name, + highlightedWidget.UIWidget.GetType().Name); // check if the widget has a onSelect code fragment. If so execute it. Otherwise // then check if the animation seq that this widget is a part of, has a onSelect. @@ -308,12 +315,12 @@ protected override void actuatorManager_EvtSwitchActivated(object sender, Actuat } else { - Log.Debug(_currentPanel.Name + ": No current animation or highlighed widget!!"); + _logger.LogDebug("{PanelName}: No current animation or highlighed widget!!", _currentPanel.Name); } } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex, "{ExceptionMessage}", ex.Message); } finally { @@ -342,17 +349,17 @@ private void runSwitchMappedCommand(IActuatorSwitch switchObj) { if (!arg.Enabled) { - Log.Debug("Command " + onTrigger + " is not currently enabled"); + _logger.LogDebug("Command {Command} is not currently enabled", onTrigger); return; } else { - Log.Debug("Command " + onTrigger + " IS ENABLED"); + _logger.LogDebug("Command {Command} IS ENABLED", onTrigger); } } else { - Log.Debug("arg.handled is false for " + onTrigger); + _logger.LogDebug("arg.handled is false for {Command}", onTrigger); var strTrigger = onTrigger; if (strTrigger[0] == '@') @@ -362,20 +369,20 @@ private void runSwitchMappedCommand(IActuatorSwitch switchObj) var cmdDescriptor = CommandManager.Instance.AppCommandTable.Get(strTrigger); if (cmdDescriptor != null && !cmdDescriptor.EnableSwitchMap) { - Log.Debug("EnableswitchMap is not enabled for " + onTrigger); + _logger.LogDebug("EnableswitchMap is not enabled for {Command}", onTrigger); runCommand = false; } } } else { - Log.Debug("Dialog is active. Will not handle"); + _logger.LogDebug("Dialog is active. Will not handle"); runCommand = false; } if (runCommand) { - Log.Debug("Executing OnTrigger command " + onTrigger + " for panel..." + _currentPanel.Name); + _logger.LogDebug("Executing OnTrigger command {Command} for panel...{PanelName}", onTrigger, _currentPanel.Name); PCode pcode = new() { Script = "run(" + onTrigger + ")" }; var parser = new Parser(); if (parser.Parse(pcode.Script, ref pcode)) diff --git a/src/Libraries/ACATCore/AnimationManagement/UserControlAnimationManager.cs b/src/Libraries/ACATCore/AnimationManagement/UserControlAnimationManager.cs index 729b3a1f..5bc26fa9 100644 --- a/src/Libraries/ACATCore/AnimationManagement/UserControlAnimationManager.cs +++ b/src/Libraries/ACATCore/AnimationManagement/UserControlAnimationManager.cs @@ -12,11 +12,13 @@ using ACAT.Core.ActuatorManagement.Interfaces; using ACAT.Core.PanelManagement.Interfaces; using ACAT.Core.AnimationManagement.Interfaces; +using Microsoft.Extensions.Logging; namespace ACAT.Core.AnimationManagement { public class UserControlAnimationManager : AnimationManager, IUserControlAnimationManager { + private readonly ILogger _logger; private UserControlConfigMapEntry mapEntry { get; set; } = null; private String name { get; set; } = null; @@ -24,7 +26,10 @@ public class UserControlAnimationManager : AnimationManager, IUserControlAnimati public event PlayerAnimationTransition EvtPlayerAnimationTransition; - public UserControlAnimationManager() : base() { } + public UserControlAnimationManager() : base() + { + _logger = LoggerFactory.GetLogger(); + } public bool Init(UserControlConfigMapEntry mapentry) { @@ -44,7 +49,7 @@ public bool Init(UserControlConfigMapEntry mapentry) subscribeToActuatorEvents(); } - Log.Debug("returning from Anim manager init()"); + _logger.LogDebug("Returning from Anim manager init()"); return retVal; } @@ -56,7 +61,7 @@ public bool IsPlayerRunning() public void OnLoad(Widget panelWidget, String animationName = null) { - Log.Debug("Start animation for panel " + panelWidget.Name); + _logger.LogDebug("Start animation for panel {PanelName}", panelWidget.Name); if (_player != null) { @@ -84,7 +89,7 @@ public void OnLoad(Widget panelWidget, String animationName = null) { if (animations == null) { - Log.Error("Could not find animations entry for panel " + panelWidget.Name); + _logger.LogError("Could not find animations entry for panel {PanelName}", panelWidget.Name); return; } @@ -115,12 +120,12 @@ public void Start(String animationName = null) { if (!CoreGlobals.AppPreferences.EnableAutoStartScan) { - Log.Verbose("CALIBTEST: UserControlAnimationManager.Start. Do AutoTransition"); + _logger.LogTrace("CALIBTEST: UserControlAnimationManager.Start. Do AutoTransition"); Transition(); } else { - Log.Verbose("CALIBTEST: UserControlAnimationManager.Start."); + _logger.LogTrace("CALIBTEST: UserControlAnimationManager.Start."); Transition(_firstAnimation); } } @@ -129,15 +134,15 @@ public override void TransitionFromName(string animationName) { try { - Log.Verbose(); + _logger.LogTrace("TransitionFromName called"); - Log.Debug("_currentPanel: " + _currentPanel); + _logger.LogDebug("_currentPanel: {CurrentPanel}", _currentPanel); resetSwitchEventStates(); if (_player == null) { - Log.Debug("_player is null"); + _logger.LogDebug("_player is null"); return; } @@ -150,17 +155,17 @@ public override void TransitionFromName(string animationName) var animation = animations[animationName]; if (animation == null) { - Log.Debug("Transition: animation is NULL!"); + _logger.LogDebug("Transition: animation is NULL!"); return; } - Log.Debug("Calling player transition"); + _logger.LogDebug("Calling player transition"); EvtPlayerAnimationTransition?.Invoke(this, animation.Name, animation.IsFirst); _player.Transition(animation); } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex, "Exception in TransitionFromName"); } } @@ -188,13 +193,13 @@ protected override void actuatorManager_EvtSwitchActivated(object sender, Actuat return; } - Log.Debug("switch: " + switchObj.Name); - Log.Debug(" Panel: " + _currentPanel.Name); + _logger.LogDebug("switch: {SwitchName}", switchObj.Name); + _logger.LogDebug(" Panel: {PanelName}", _currentPanel.Name); if (_currentPanel.UIControl is System.Windows.Forms.Form) { bool visible = Windows.GetVisible(_currentPanel.UIControl); - Log.Debug("Form: " + _currentPanel.UIControl.Name + ", playerState: " + _player.State + ", visible: " + visible); + _logger.LogDebug("Form: {FormName}, playerState: {PlayerState}, visible: {Visible}", _currentPanel.UIControl.Name, _player.State, visible); if (!visible) { return; @@ -205,7 +210,7 @@ protected override void actuatorManager_EvtSwitchActivated(object sender, Actuat String onTrigger = switchObj.Command; if (String.IsNullOrEmpty(onTrigger)) { - Log.Debug("OnTrigger is null. returning"); + _logger.LogDebug("OnTrigger is null. returning"); return; } @@ -226,11 +231,11 @@ protected override void actuatorManager_EvtSwitchActivated(object sender, Actuat if (CoreGlobals.AppPreferences.EnableManualScan) { - Log.Debug("HOOO form: " + _currentPanel.UIControl.Name + " Player state: " + _player.State); + _logger.LogDebug("HOOO form: {FormName} Player state: {PlayerState}", _currentPanel.UIControl.Name, _player.State); if (_player.State == PlayerState.Paused) { - Log.Debug(_currentPanel.Name + ": Player is paused. Returning"); + _logger.LogDebug("{PanelName}: Player is paused. Returning", _currentPanel.Name); return; } @@ -239,7 +244,7 @@ protected override void actuatorManager_EvtSwitchActivated(object sender, Actuat var widget = _player.HighlightedWidget; if (widget != null) { - Log.Debug("Actuate. widgetname: " + widget.Name + " Text: " + widget.GetText()); + _logger.LogDebug("Actuate. widgetname: {WidgetName} Text: {WidgetText}", widget.Name, widget.GetText()); _player.Interrupt(); _player.ManualScanActuateWidget(widget); } @@ -252,10 +257,10 @@ protected override void actuatorManager_EvtSwitchActivated(object sender, Actuat return; } - Log.Debug("Player state is " + _player.State); + _logger.LogDebug("Player state is {PlayerState}", _player.State); if (_player.State != PlayerState.Running) { - Log.Debug(_currentPanel.Name + ": Player is not Running. Returning"); + _logger.LogDebug("{PanelName}: Player is not Running. Returning", _currentPanel.Name); return; } @@ -294,9 +299,7 @@ protected override void actuatorManager_EvtSwitchActivated(object sender, Actuat highlightedWidget.UIWidget.GetType().Name, widgetName)); - Log.Debug(_currentPanel.Name + ": Switch on " + - highlightedWidget.UIWidget.Name + " type: " + - highlightedWidget.UIWidget.GetType().Name); + _logger.LogDebug("{PanelName}: Switch on {WidgetName} type: {WidgetType}", _currentPanel.Name, highlightedWidget.UIWidget.Name, highlightedWidget.UIWidget.GetType().Name); // check if the widget has a onSelect code fragment. If so execute it. Otherwise // then check if the animation seq that this widget is a part of, has a onSelect. @@ -319,12 +322,12 @@ protected override void actuatorManager_EvtSwitchActivated(object sender, Actuat } else { - Log.Debug(_currentPanel.Name + ": No current animation or highlighed widget!!"); + _logger.LogDebug("{PanelName}: No current animation or highlighed widget!!", _currentPanel.Name); } } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex, "Exception in actuatorManager_EvtSwitchActivated"); } finally { @@ -353,35 +356,35 @@ private void runSwitchMappedCommand(IActuatorSwitch switchObj) { if (!arg.Enabled) { - Log.Debug("Command " + onTrigger + " is not currently enabled"); + _logger.LogDebug("Command {Command} is not currently enabled", onTrigger); return; } else { - Log.Debug("Command " + onTrigger + " IS ENABLED"); + _logger.LogDebug("Command {Command} IS ENABLED", onTrigger); } } else { - Log.Debug("arg.handled is false for " + onTrigger); + _logger.LogDebug("arg.handled is false for {Command}", onTrigger); var cmdDescriptor = CommandManager.Instance.AppCommandTable.Get(onTrigger); if (cmdDescriptor != null && !cmdDescriptor.EnableSwitchMap) { - Log.Debug("EnableswitchMap is not enabled for " + onTrigger); + _logger.LogDebug("EnableswitchMap is not enabled for {Command}", onTrigger); runCommand = false; } } } else { - Log.Debug("Dialog is active. Will not handle"); + _logger.LogDebug("Dialog is active. Will not handle"); runCommand = false; } if (runCommand) { - Log.Debug("Executing OnTrigger command " + onTrigger + " for panel..." + _currentPanel.Name); + _logger.LogDebug("Executing OnTrigger command {Command} for panel...{PanelName}", onTrigger, _currentPanel.Name); PCode pcode = new() { Script = "run(" + onTrigger + ")" }; var parser = new Parser(); if (parser.Parse(pcode.Script, ref pcode)) diff --git a/src/Libraries/ACATCore/AnimationManagement/Variables.cs b/src/Libraries/ACATCore/AnimationManagement/Variables.cs index 58ccf598..b4e000c9 100644 --- a/src/Libraries/ACATCore/AnimationManagement/Variables.cs +++ b/src/Libraries/ACATCore/AnimationManagement/Variables.cs @@ -142,7 +142,7 @@ public String GetString(String variableName) /// It's value public void Set(String variableName, object value) { - //Log.Debug("Set variable " + variableName); + //_logger.LogDebug("Set variable {VariableName}", variableName); if (_list.ContainsKey(variableName)) { _list[variableName] = value; diff --git a/src/Libraries/ACATCore/Extensions/ExtensionInvoker.cs b/src/Libraries/ACATCore/Extensions/ExtensionInvoker.cs index 5ca0fe8d..bc486100 100644 --- a/src/Libraries/ACATCore/Extensions/ExtensionInvoker.cs +++ b/src/Libraries/ACATCore/Extensions/ExtensionInvoker.cs @@ -6,6 +6,7 @@ //////////////////////////////////////////////////////////////////////////// using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Reflection; @@ -27,6 +28,7 @@ namespace ACAT.Core.Extensions /// public class ExtensionInvoker : IExtension { + private static readonly ILogger _logger = LogManager.GetLogger(); /// /// The object whose methods/properties/events are to /// be invoked through reflection @@ -193,7 +195,7 @@ public object GetValue(String property) } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, "Error getting value for property {Property}", property); } return null; @@ -233,7 +235,7 @@ public object InvokeExtensionMethod(string methodName, params object[] args) } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex, "Error invoking extension method {MethodName}", methodName); } return result; @@ -287,7 +289,7 @@ public bool SetValue(String property, object value) } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex, "Error setting value for property {Property}", property); retVal = false; } diff --git a/src/Libraries/ACATCore/Interpreter/Interpret.cs b/src/Libraries/ACATCore/Interpreter/Interpret.cs index 73f78edd..fa076945 100644 --- a/src/Libraries/ACATCore/Interpreter/Interpret.cs +++ b/src/Libraries/ACATCore/Interpreter/Interpret.cs @@ -6,6 +6,7 @@ //////////////////////////////////////////////////////////////////////////// using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Reflection; @@ -29,6 +30,8 @@ namespace ACAT.Core.Interpreter /// public class Interpret { + private static readonly ILogger _logger = LoggingConfiguration.CreateLogger(); + #pragma warning disable IDE0051 /// @@ -223,12 +226,12 @@ public bool Execute(ActionVerb actionVerb) } else { - Log.Debug("Error executing verb " + actionVerb.Action + ". Mi is null"); + _logger.LogDebug("Error executing verb {Action}. Mi is null", actionVerb.Action); } } catch (Exception e) { - Log.Exception("Error executing verb " + actionVerb.Action + ". Exception: " + e.ToString()); + _logger.LogError(e, "Error executing verb {Action}", actionVerb.Action); retVal = false; } diff --git a/src/Libraries/ACATCore/Interpreter/Parser.cs b/src/Libraries/ACATCore/Interpreter/Parser.cs index 1d23ca8e..6ca608dd 100644 --- a/src/Libraries/ACATCore/Interpreter/Parser.cs +++ b/src/Libraries/ACATCore/Interpreter/Parser.cs @@ -6,6 +6,7 @@ //////////////////////////////////////////////////////////////////////////// using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Text; @@ -19,6 +20,7 @@ namespace ACAT.Core.Interpreter /// public class Parser { + private static readonly ILogger _logger = LogManager.GetLogger(); /// /// State of parsing /// @@ -159,7 +161,7 @@ private bool getActionAndArguments(String parseString, ref String retAction, ref break; case ParseState.Invalid: - Log.Error("Parse error at index " + index + ". String: " + parseString); + _logger.LogError("Parse error at index {Index}. String: {ParseString}", index, parseString); retVal = false; done = true; break; @@ -168,13 +170,13 @@ private bool getActionAndArguments(String parseString, ref String retAction, ref if (!done) { - Log.Error("Parse error at index " + index + ". String: " + parseString); + _logger.LogError("Parse error at index {Index}. String: {ParseString}", index, parseString); retVal = false; } if (retVal && index < parseString.Length) { - Log.Error("Parse error at index " + index + ". String: " + parseString); + _logger.LogError("Parse error at index {Index}. String: {ParseString}", index, parseString); retVal = false; } diff --git a/src/Libraries/ACATCore/PanelManagement/CommandDispatcher/RunCommands.cs b/src/Libraries/ACATCore/PanelManagement/CommandDispatcher/RunCommands.cs index 9a123397..9ea16997 100644 --- a/src/Libraries/ACATCore/PanelManagement/CommandDispatcher/RunCommands.cs +++ b/src/Libraries/ACATCore/PanelManagement/CommandDispatcher/RunCommands.cs @@ -6,6 +6,7 @@ //////////////////////////////////////////////////////////////////////////// using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; @@ -17,6 +18,8 @@ namespace ACAT.Core.PanelManagement.CommandDispatcher /// public class RunCommands { + private static readonly ILogger _logger = LogManager.GetLogger(typeof(RunCommands)); + /// /// Command dispatcher object. Caller can set this and the dispatcher /// will be called to dispatch the command. @@ -70,7 +73,7 @@ public bool Add(RunCommandHandler handler) catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, ex.Message); ret = false; } diff --git a/src/Libraries/ACATCore/PanelManagement/Common/DialogCommon.cs b/src/Libraries/ACATCore/PanelManagement/Common/DialogCommon.cs index d24d6e49..cbda9b73 100644 --- a/src/Libraries/ACATCore/PanelManagement/Common/DialogCommon.cs +++ b/src/Libraries/ACATCore/PanelManagement/Common/DialogCommon.cs @@ -21,6 +21,7 @@ using System.Windows.Automation; using System.Windows.Forms; using ACAT.Core.PanelManagement.PanelConfig; +using Microsoft.Extensions.Logging; namespace ACAT.Core.PanelManagement.Common { @@ -39,6 +40,8 @@ namespace ACAT.Core.PanelManagement.Common /// public class DialogCommon : IDisposable, IPanelCommon { + private static ILogger _logger; + /// /// All dialog forms should derive from IDialogPanel /// @@ -269,15 +272,16 @@ public void OnFormClosing(FormClosingEventArgs e) { if (_syncLock.Status != SyncLock.StatusValues.None) { - Log.Debug(_form.Name + ", _syncObj.Status: " + _syncLock.Status + ", form already closed. returning"); + _logger?.LogDebug("{FormName}, _syncObj.Status: {Status}, form already closed. returning", + _form.Name, _syncLock.Status); return; } _syncLock.Status = SyncLock.StatusValues.Closing; - Log.Debug("Before animationmangoer.stop"); + _logger?.LogDebug("Before animationmanager.stop"); _form.Invoke(new StopDelegate(_animationManager.Stop)); - Log.Debug("After animationmangoer.stop"); + _logger?.LogDebug("After animationmanager.stop"); unsubscribeFromEvents(); } @@ -339,14 +343,14 @@ protected virtual void Dispose(bool disposing) // Check to see if Dispose has already been called. if (!_disposed) { - Log.Verbose(); + _logger?.LogTrace("Disposing DialogCommon"); if (disposing) { PanelManager.Instance.EvtScannerShow -= Instance_EvtScannerShow; // dispose all managed resources. - Log.Verbose(); + _logger?.LogTrace("Disposing managed resources"); _animationManager?.Dispose(); @@ -388,7 +392,7 @@ private void createAndShowScannerForWidget(Widget widget) var startupArg = createStartupArgForScanner(widget); - Log.Debug("Creating Panel " + widget.Panel); + _logger?.LogDebug("Creating Panel {PanelName}", widget.Panel); Form panel = Context.AppPanelManager.CreatePanel(widget.Panel, string.Empty, startupArg); var child = panel as IScannerPanel; if (child != null) @@ -427,7 +431,7 @@ private bool initAnimationManager(PanelConfigMapEntry panelConfigMapEntry) bool retVal = _animationManager.Init(panelConfigMapEntry); if (!retVal) { - Log.Error("Error initializing animation manager"); + _logger?.LogError("Error initializing animation manager"); } return retVal; @@ -447,7 +451,7 @@ private bool initWidgetManager(PanelConfigMapEntry panelConfigMapEntry) if (!retVal) { - Log.Error("Unable to initialize widget manager"); + _logger?.LogError("Unable to initialize widget manager"); } else { @@ -555,7 +559,7 @@ private void widget_EvtActuated(object sender, WidgetActuatedEventArgs e) string value = widget.Value; if (!string.IsNullOrEmpty(value)) { - Log.Debug("**Actuate** " + widget.Name + " Value: " + value); + _logger?.LogDebug("**Actuate** {WidgetName} Value: {Value}", widget.Name, value); _dialogPanel.OnButtonActuated(widget); } @@ -595,7 +599,7 @@ form is IScannerPanel && Windows.DockWithScanner(_form, form, Context.AppWindowPosition, false); } - Log.Debug("Left: " + _form.Left); + _logger?.LogDebug("Left: {Left}", _form.Left); if (_form.Left < 0) { diff --git a/src/Libraries/ACATCore/PanelManagement/Common/ScannerCommon.cs b/src/Libraries/ACATCore/PanelManagement/Common/ScannerCommon.cs index 314506a3..c766d680 100644 --- a/src/Libraries/ACATCore/PanelManagement/Common/ScannerCommon.cs +++ b/src/Libraries/ACATCore/PanelManagement/Common/ScannerCommon.cs @@ -663,7 +663,7 @@ public void OnLoad() /// public void OnPause(PauseDisplayMode mode = PauseDisplayMode.Default) { - Log.Debug("CALIBTEST_isPaused: " + _isPaused); + _logger?.LogDebug("CALIBTEST_isPaused: " + _isPaused); if (_isPaused) { return; @@ -675,18 +675,18 @@ public void OnPause(PauseDisplayMode mode = PauseDisplayMode.Default) { if (DialogMode) { - Log.Debug("CALIBTEST Dialog mode is true. Returning"); + _logger?.LogDebug("CALIBTEST Dialog mode is true. Returning"); return; } - Log.Verbose("CALIBTEST Pausing animation manager"); + _logger?.LogTrace("CALIBTEST Pausing animation manager"); AnimationManager.Pause(); - Log.Verbose("CALIBTEST calling setDisplayStateOnpause"); + _logger?.LogTrace("CALIBTEST calling setDisplayStateOnpause"); setDisplayStateOnPause(mode); } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger?.LogError(ex.ToString()); } } @@ -695,7 +695,7 @@ public void OnPause(PauseDisplayMode mode = PauseDisplayMode.Default) /// public void OnResume() { - Log.Debug("CALIBTEST Scannercommon2 OnResume. is_paused: " + _isPaused); + _logger?.LogDebug("CALIBTEST Scannercommon2 OnResume. is_paused: " + _isPaused); if (!_isPaused) { return; @@ -707,10 +707,10 @@ public void OnResume() { PositionSizeController.ScaleForm(); - Log.Verbose("CALIBTEST Scannercommon2 Showing scanner"); + _logger?.LogTrace("CALIBTEST Scannercommon2 Showing scanner"); ShowScanner(); - Log.Verbose("CALIBTEST Calling Animationmanager resume"); + _logger?.LogTrace("CALIBTEST Calling Animationmanager resume"); AnimationManager.Resume(); updateStatusBar(); @@ -722,7 +722,7 @@ public void OnResume() } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger?.LogError(ex.ToString()); } } @@ -809,7 +809,7 @@ protected virtual void Dispose(bool disposing) // Check to see if Dispose has already been called. if (!_disposed) { - Log.Verbose(); + _logger?.LogTrace("Dispose called"); if (disposing) { @@ -875,7 +875,7 @@ widget is WordListItemWidget || SendKeys.SendWait(widget.Value + " "); Context.AppAgentMgr.TextChangedNotifications.Release(); CoreGlobals.Stopwatch1.Stop(); - Log.Verbose("TimeElapsed 1: " + CoreGlobals.Stopwatch1.ElapsedMilliseconds); + _logger?.LogTrace("TimeElapsed 1: " + CoreGlobals.Stopwatch1.ElapsedMilliseconds); } else { @@ -885,7 +885,7 @@ widget is WordListItemWidget || actuateKey(button.GetWidgetAttribute(), widget.Value[0]); CoreGlobals.Stopwatch1.Stop(); - Log.Verbose("TimeElapsed 2 : " + CoreGlobals.Stopwatch1.ElapsedMilliseconds); + _logger?.LogTrace("TimeElapsed 2 : " + CoreGlobals.Stopwatch1.ElapsedMilliseconds); } } @@ -900,7 +900,7 @@ widget is WordListItemWidget || /// String to send private void actuateKey(WidgetAttribute widgetAttribute, char value) { - Log.Verbose(value.ToString()); + _logger?.LogTrace(value.ToString()); if (!TextController.HandlePunctuation(widgetAttribute.Modifiers, value)) { if ((KeyStateTracker.IsShiftOn() || KeyStateTracker.IsCapsLockOn()) && @@ -924,7 +924,7 @@ private void actuateKey(WidgetAttribute widgetAttribute, char value) /// value of the key private void actuateVirtualKey(WidgetAttribute widgetAttribute, string value) { - Log.Verbose("VirtualKey: " + value); + _logger?.LogTrace("VirtualKey: " + value); Keys key = TextController.MapVirtualKey(value); if (key == Keys.Escape && _dialogMode) @@ -953,7 +953,7 @@ private void animationManager_EvtPlayerStateChanged(object sender, PlayerStateCh try { var newState = _animationManager.GetPlayerState(); - Log.Debug(ScannerForm.Name + ": PlayerState changed from " + e.OldState + " to " + newState); + _logger?.LogDebug(ScannerForm.Name + ": PlayerState changed from " + e.OldState + " to " + newState); switch (newState) { case PlayerState.Timeout: @@ -969,7 +969,7 @@ private void animationManager_EvtPlayerStateChanged(object sender, PlayerStateCh } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger?.LogError(ex.ToString()); } } @@ -1003,7 +1003,7 @@ private bool AppAgent_EvtScannerHitTest(int x, int y) /// private void AppAgent_EvtTextChanged(object sender, EventArgs e) { - Log.Debug("Enter " + Kernel32Interop.GetCurrentThreadId()); + _logger?.LogDebug("Enter " + Kernel32Interop.GetCurrentThreadId()); try { if (Windows.GetVisible(ScannerForm) && @@ -1023,18 +1023,18 @@ ScannerForm is not MenuPanelBase && if (!abbreviationDetected && !context.TextAgent().SupportsSpellCheck()) { - Log.Verbose("Calling spellccheck " + Kernel32Interop.GetCurrentThreadId()); + _logger?.LogTrace("Calling spellccheck " + Kernel32Interop.GetCurrentThreadId()); TextController.SpellCheck(); - Log.Verbose("Returned from spellccheck " + Kernel32Interop.GetCurrentThreadId()); + _logger?.LogTrace("Returned from spellccheck " + Kernel32Interop.GetCurrentThreadId()); } } } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger?.LogError(ex.ToString()); } - Log.Verbose("Leave " + Kernel32Interop.GetCurrentThreadId()); + _logger?.LogTrace("Leave " + Kernel32Interop.GetCurrentThreadId()); } /// @@ -1044,11 +1044,11 @@ ScannerForm is not MenuPanelBase && /// event args private void AppPanelManager_EvtCalibrationEndNotify(object sender, EventArgs e) { - Log.Debug("CALIBTEST Calibration end notify for " + ScannerForm.Name); + _logger?.LogDebug("CALIBTEST Calibration end notify for " + ScannerForm.Name); if (Context.AppPanelManager.GetCurrentForm() as Form != ScannerForm) { - Log.Verbose("CALIBTESTForm is not the current form. returning " + ScannerForm.Name + " CurrentForm is " + (Context.AppPanelManager.GetCurrentForm() as Form).Name); + _logger?.LogTrace("CALIBTESTForm is not the current form. returning " + ScannerForm.Name + " CurrentForm is " + (Context.AppPanelManager.GetCurrentForm() as Form).Name); return; } @@ -1059,7 +1059,7 @@ private void AppPanelManager_EvtCalibrationEndNotify(object sender, EventArgs e) } else { - Log.Verbose("CALIBTESTCalling OnResume for scanner"); + _logger?.LogTrace("CALIBTESTCalling OnResume for scanner"); (ScannerForm as IScannerPanel).OnResume(); } } @@ -1070,11 +1070,11 @@ private void AppPanelManager_EvtCalibrationEndNotify(object sender, EventArgs e) /// event args private void AppPanelManager_EvtCalibrationStartNotify(ActuatorManagement.CalibrationNotifyEventArgs args) { - Log.Debug("CALIBTEST ScannerCommon2: Calibration start notify for " + ScannerForm.Name); + _logger?.LogDebug("CALIBTEST ScannerCommon2: Calibration start notify for " + ScannerForm.Name); if (Context.AppPanelManager.GetCurrentForm() as Form != ScannerForm) { - Log.Verbose("CALIBTEST Form is not the current form. returning " + ScannerForm.Name + " CurrentForm is " + (Context.AppPanelManager.GetCurrentForm() as Form).Name); + _logger?.LogTrace("CALIBTEST Form is not the current form. returning " + ScannerForm.Name + " CurrentForm is " + (Context.AppPanelManager.GetCurrentForm() as Form).Name); return; } @@ -1087,7 +1087,7 @@ private void AppPanelManager_EvtCalibrationStartNotify(ActuatorManagement.Calibr } else { - Log.Verbose("CALIBTEST Calling onPause for " + ScannerForm.Name); + _logger?.LogTrace("CALIBTEST Calling onPause for " + ScannerForm.Name); (ScannerForm as IScannerPanel).OnPause(); } @@ -1165,7 +1165,7 @@ private void createIdleTimer() /// private void form_Shown(object sender, EventArgs e) { - Log.Debug("Shown " + ScannerForm.Name); + _logger?.LogDebug("Shown " + ScannerForm.Name); } /// @@ -1175,7 +1175,7 @@ private void form_Shown(object sender, EventArgs e) /// event args private void form_VisibleChanged(object sender, EventArgs e) { - Log.Debug("Form Visibility for " + ScannerForm.Name + ": " + ScannerForm.Visible); + _logger?.LogDebug("Form Visibility for " + ScannerForm.Name + ": " + ScannerForm.Visible); if (ScannerForm.Visible) { @@ -1196,7 +1196,7 @@ private void form_VisibleChanged(object sender, EventArgs e) if (_scannerPanel.PanelClass == "Alphabet") { - Log.Verbose("form_visibleChanged " + ScannerForm.Width); + _logger?.LogTrace("form_visibleChanged " + ScannerForm.Width); } notifyScannerShow(); } @@ -1239,7 +1239,7 @@ private bool initAnimationManager(PanelConfigMapEntry panelConfigMapEntry) } else { - Log.Error("Error initializing animation manager"); + _logger?.LogError("Error initializing animation manager"); _animationManager = null; retVal = false; } @@ -1262,7 +1262,7 @@ private bool initWidgetManager(PanelConfigMapEntry panelConfigMapEntry) bool retVal = _widgetManager.Initialize(panelConfigMapEntry.ConfigFileName); if (!retVal) { - Log.Error("Unable to initialize widget manager"); + _logger?.LogError("Unable to initialize widget manager"); } else { @@ -1302,7 +1302,7 @@ private void Interpreter_EvtRun(object sender, InterpreterRunEventArgs e) return; } - Log.Verbose(e.Script); + _logger?.LogTrace(e.Script); runCommand(e.Script); } @@ -1384,7 +1384,7 @@ private void runCommand(string command) command = command.Substring(1); } - Log.Debug("Calling scanner common runcomand with " + command); + _logger?.LogDebug("Calling scanner common runcomand with " + command); ScannerForm.Invoke(new MethodInvoker(delegate { string[] parts = command.Split('.'); @@ -1441,7 +1441,7 @@ private void ScannerForm_SizeChanged(object sender, EventArgs e) { if (_scannerPanel.PanelClass == "Alphabet") { - Log.Debug("ScannerForm_SizeChanged " + ScannerForm.Width); + _logger?.LogDebug("ScannerForm_SizeChanged " + ScannerForm.Width); } notifyScannerShow(); } @@ -1452,7 +1452,7 @@ private void ScannerForm_SizeChanged(object sender, EventArgs e) /// what to do? private void setDisplayStateOnPause(PauseDisplayMode mode) { - Log.Debug("setDisplayStateOnPause. mode: " + mode); + _logger?.LogDebug("setDisplayStateOnPause. mode: " + mode); if (mode == PauseDisplayMode.None) { return; @@ -1484,7 +1484,7 @@ private void setWidgetEnabledStates(WindowActivityMonitorInfo monitorInfo) { if (_syncLock.IsClosing()) { - Log.Debug("Form is closing " + ScannerForm.Name); + _logger?.LogDebug("Form is closing " + ScannerForm.Name); WindowActivityMonitor.EvtWindowMonitorHeartbeat -= WindowActivityMonitor_EvtWindowMonitorHeartbeat; return; } @@ -1513,7 +1513,7 @@ private void setWidgetEnabledStates(WindowActivityMonitorInfo monitorInfo) break; } - Log.Verbose("widget.Enabled set to : " + widget.Enabled + " for feature " + widget.SubClass); + _logger?.LogTrace("widget.Enabled set to : " + widget.Enabled + " for feature " + widget.SubClass); } } } @@ -1551,7 +1551,7 @@ private void subscribeToEvents() AnimationManager.Interpreter.EvtRun -= Interpreter_EvtRun; AnimationManager.Interpreter.EvtRun += Interpreter_EvtRun; - Log.Debug("Subscribing on instance " + AnimationManager.Interpreter.GetHashCode()); + _logger?.LogDebug("Subscribing on instance " + AnimationManager.Interpreter.GetHashCode()); AnimationManager.Interpreter.EvtShowPopup -= Interpreter_EvtShowPopup; AnimationManager.Interpreter.EvtShowPopup += Interpreter_EvtShowPopup; subscribeToButtonEvents(); @@ -1564,7 +1564,7 @@ private void subscribeToEvents() /// text to convert private void textToSpeech(string text) { - Log.Debug("Convert to speech. text=" + text); + _logger?.LogDebug("Convert to speech. text=" + text); Context.AppTTSManager.ActiveEngine.Speak(text); AuditLog.Audit(new AuditEventTextToSpeech(Context.AppTTSManager.ActiveEngine.Descriptor.Name)); } @@ -1626,7 +1626,7 @@ private void widget_EvtActuated(object sender, WidgetActuatedEventArgs e) var value = widget.Value; if (!string.IsNullOrEmpty(value)) { - Log.Debug("**Actuate** " + widget.Name + " Value: " + value); + _logger?.LogDebug("**Actuate** " + widget.Name + " Value: " + value); actuateButton(widget); } @@ -1666,7 +1666,7 @@ private void Windows_EvtWindowPositionChanged(Form form, Windows.WindowPosition if (_scannerPanel.PanelClass == "Alphabet") { - Log.Debug("WindowPosChanged" + ScannerForm.Width); + _logger?.LogDebug("WindowPosChanged" + ScannerForm.Width); } notifyScannerShow(); } diff --git a/src/Libraries/ACATCore/PanelManagement/Common/ScannerPositionSizeController.cs b/src/Libraries/ACATCore/PanelManagement/Common/ScannerPositionSizeController.cs index dd4b5199..ece24508 100644 --- a/src/Libraries/ACATCore/PanelManagement/Common/ScannerPositionSizeController.cs +++ b/src/Libraries/ACATCore/PanelManagement/Common/ScannerPositionSizeController.cs @@ -8,6 +8,7 @@ using ACAT.Core.PanelManagement.Utils; using ACAT.Core.Utility; using ACAT.Core.WidgetManagement; +using Microsoft.Extensions.Logging; using System; using System.Drawing; using System.Windows.Forms; @@ -23,6 +24,8 @@ namespace ACAT.Core.PanelManagement.Common /// public class ScannerPositionSizeController { + private readonly ILogger _logger; + /// /// Multiplier to calculate the scanner size based /// on the scale factor @@ -102,8 +105,9 @@ public class ScannerPositionSizeController /// Initializes a new instance of the class. /// /// ScannerForm object associated with the form - internal ScannerPositionSizeController(ScannerCommon scannerCommon) + internal ScannerPositionSizeController(ScannerCommon scannerCommon, ILogger logger = null) { + _logger = logger; AutoPosition = true; ManualPosition = Context.AppWindowPosition; _prevAutoPositionScannerValue = AutoPosition; @@ -238,11 +242,11 @@ public void RestoreDefaults() /// public void SaveScaleSetting(SystemPreferences prefs) { - Log.Debug("saving scale factor. _scaleFactor=" + ScaleFactor); + _logger?.LogDebug("Saving scale factor: {ScaleFactor}", ScaleFactor); prefs.ScannerScaleFactor = CoreGlobals.AppPreferences.ScannerScaleFactor = Convert.ToInt16(ScaleFactor * IntMultiplier); prefs.Save(); CoreGlobals.AppPreferences.NotifyPreferencesChanged(); - Log.Debug("scale factor saved is:" + prefs.ScannerScaleFactor); + _logger?.LogDebug("Scale factor saved: {SavedScaleFactor}", prefs.ScannerScaleFactor); } /// @@ -250,16 +254,16 @@ public void SaveScaleSetting(SystemPreferences prefs) /// public void SaveSettings(SystemPreferences prefs) { - Log.Debug("saving scale factor. _scaleFactor=" + ScaleFactor); + _logger?.LogDebug("Saving scale factor: {ScaleFactor}", ScaleFactor); prefs.ScannerScaleFactor = CoreGlobals.AppPreferences.ScannerScaleFactor = Convert.ToInt16(ScaleFactor * IntMultiplier); - Log.Debug("Saving window position as " + Context.AppWindowPosition); + _logger?.LogDebug("Saving window position: {WindowPosition}", Context.AppWindowPosition); prefs.ScannerPosition = CoreGlobals.AppPreferences.ScannerPosition = Context.AppWindowPosition; prefs.Save(); AutoPosition = true; CoreGlobals.AppPreferences.NotifyPreferencesChanged(); - Log.Debug("scale factor saved is:" + prefs.ScannerScaleFactor); + _logger?.LogDebug("Scale factor saved: {SavedScaleFactor}", prefs.ScannerScaleFactor); } /// @@ -277,7 +281,7 @@ public void ScaleDefault() /// public void ScaleDown() { - Log.Debug("scaling down. _scaleFactor=" + ScaleFactor + " SCALE_FACTOR_MINIMUM=" + ScaleFactorMinimum); + _logger?.LogDebug("Scaling down - current scale factor: {ScaleFactor}, minimum: {Minimum}", ScaleFactor, ScaleFactorMinimum); if (ScaleFactor > ScaleFactorMinimum) { ScaleFactor -= ScaleFactorAmount; @@ -308,13 +312,12 @@ public void ScaleForm() /// the scale factor public void ScaleForm(float scaleFactor) { - Log.Debug("Enter. scaleFactor: " + scaleFactor); + _logger?.LogDebug("Scaling form - scale factor: {ScaleFactor}", scaleFactor); var newSize = new Size(Convert.ToInt32(_originalSize.Width * scaleFactor), Convert.ToInt32(_originalSize.Height * scaleFactor)); - Log.Debug(_form.Name + "," + "scalefactor: " + scaleFactor + - "orig/new width: " + _originalSize.Width + ", " + newSize.Width + - "orig/new height: " + _originalSize.Height + ", " + newSize.Height); + _logger?.LogDebug("Form: {FormName}, scale factor: {ScaleFactor}, original width: {OrigWidth}, new width: {NewWidth}, original height: {OrigHeight}, new height: {NewHeight}", + _form.Name, scaleFactor, _originalSize.Width, newSize.Width, _originalSize.Height, newSize.Height); //_rootWidget.Dump(); @@ -323,7 +326,7 @@ public void ScaleForm(float scaleFactor) _form.Size = newSize; - Log.Debug("Exit"); + _logger?.LogDebug("Form scaling complete"); } /// @@ -331,8 +334,7 @@ public void ScaleForm(float scaleFactor) /// public void ScaleUp() { - Log.Debug("Enter"); - Log.Debug("scaling up. _scaleFactor=" + ScaleFactor + " SCALE_FACTOR_MAXIMUM=" + ScaleFactorMaximum); + _logger?.LogDebug("Scaling up - current scale factor: {ScaleFactor}, maximum: {Maximum}", ScaleFactor, ScaleFactorMaximum); if (ScaleFactor < ScaleFactorMaximum) { ScaleFactor += ScaleFactorAmount; @@ -340,7 +342,7 @@ public void ScaleUp() SetPositionAndNotify(); } - Log.Debug("Exit"); + _logger?.LogDebug("Scale up complete"); } /// @@ -374,7 +376,7 @@ private void _autoPostionScanner_EvtAutoPostionScannerStopped(object sender, Eve /// private void _form_ResizeEnd(object sender, EventArgs e) { - Log.Debug("Formwidth: " + _form.Width + ", originalWidth: " + _originalSize.Width); + _logger?.LogDebug("Form resize end - form width: {Width}, original width: {OriginalWidth}", _form.Width, _originalSize.Width); float aspectRatio = (float)_originalSize.Width / _originalSize.Height; float scaleFactor = 0.0f; @@ -444,7 +446,7 @@ private void resizeScannerToFitDesktop(float scaleFactor) { _form.Invoke(new MethodInvoker(delegate { - Log.Debug("Enter. scaleFactor: " + scaleFactor); + _logger?.LogDebug("Resizing scanner to fit desktop - scale factor: {ScaleFactor}", scaleFactor); var newSize = new Size(Convert.ToInt32(_originalSize.Width * scaleFactor), Convert.ToInt32(_originalSize.Height * scaleFactor)); diff --git a/src/Libraries/ACATCore/PanelManagement/Common/Splash.cs b/src/Libraries/ACATCore/PanelManagement/Common/Splash.cs index 5920bbe6..cccd7bed 100644 --- a/src/Libraries/ACATCore/PanelManagement/Common/Splash.cs +++ b/src/Libraries/ACATCore/PanelManagement/Common/Splash.cs @@ -6,6 +6,7 @@ //////////////////////////////////////////////////////////////////////////// using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Diagnostics; using System.Threading; @@ -21,6 +22,8 @@ namespace ACAT.Core.PanelManagement.Common /// public class Splash { + private static readonly ILogger _logger = LogManager.GetLogger(typeof(Splash)); + /// /// The splash screen form /// @@ -70,7 +73,7 @@ public void Close() } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex, ex.Message); } } diff --git a/src/Libraries/ACATCore/PanelManagement/Common/TextController.cs b/src/Libraries/ACATCore/PanelManagement/Common/TextController.cs index 603a16b7..74a5d352 100644 --- a/src/Libraries/ACATCore/PanelManagement/Common/TextController.cs +++ b/src/Libraries/ACATCore/PanelManagement/Common/TextController.cs @@ -310,7 +310,7 @@ public Abbreviation CheckAndReplaceAbbreviation(ref bool handled) } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, ex.Message); } return abbr; @@ -345,26 +345,25 @@ public void DeletePreviousWord() caretPos == _autoCompleteCaretPos && _beforeAutoCompleteCaretPos >= 0) { - Log.Debug("Delete: _autoCompleteCaretPos: " + _autoCompleteCaretPos + - ", _beforeAutoCOmpleteCaretPos: " + _beforeAutoCompleteCaretPos + ", count: " + - (_autoCompleteCaretPos - _beforeAutoCompleteCaretPos)); + _logger.LogDebug("Delete: _autoCompleteCaretPos: {AutoCompleteCaretPos}, _beforeAutoCompleteCaretPos: {BeforeAutoCompleteCaretPos}, count: {Count}", + _autoCompleteCaretPos, _beforeAutoCompleteCaretPos, (_autoCompleteCaretPos - _beforeAutoCompleteCaretPos)); int prefixLen = _autoCompletePartialWord.Length; - Log.Debug("prefixLen: " + prefixLen); + _logger.LogDebug("prefixLen: {PrefixLen}", prefixLen); if (prefixLen > 0) { int start = _autocompleteStartOffset; - Log.Debug("start: " + start); + _logger.LogDebug("start: {Start}", start); start = Math.Max(0, start); - Log.Debug("Deleting from " + start + ", numchars: " + (_autoCompleteCaretPos - start)); + _logger.LogDebug("Deleting from {Start}, numchars: {NumChars}", start, (_autoCompleteCaretPos - start)); context.TextAgent().Delete(start, _autoCompleteCaretPos - start); - Log.Debug("Inserting at " + start + ", string: " + _autoCompletePartialWord); + _logger.LogDebug("Inserting at {Start}, string: {String}", start, _autoCompletePartialWord); context.TextAgent().Insert(start, _autoCompletePartialWord); } else { - Log.Debug("Delete from " + _beforeAutoCompleteCaretPos); + _logger.LogDebug("Delete from {BeforeAutoCompleteCaretPos}", _beforeAutoCompleteCaretPos); context.TextAgent().Delete(_beforeAutoCompleteCaretPos, _autoCompleteCaretPos - _beforeAutoCompleteCaretPos); } } @@ -379,7 +378,7 @@ public void DeletePreviousWord() } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, ex.Message); } finally { @@ -422,7 +421,7 @@ public void HandleAlphaNumericChar(char inputChar) /// true on success public bool HandlePunctuation(ArrayList modifiers, char punctuation) { - Log.Verbose(); + _logger.LogTrace("HandlePunctuation called with punctuation: {Punctuation}", punctuation); try { @@ -455,15 +454,15 @@ public bool HandlePunctuation(ArrayList modifiers, char punctuation) { // delete any spaces before the punctuation context.TextAgent().GetPrecedingWhiteSpaces(out int offset, out int count); - Log.Debug("Preceding whitespace count: " + count); + _logger.LogDebug("Preceding whitespace count: {Count}", count); if (count > 0) { - Log.Debug("Deleting whitespaces from offset " + offset); + _logger.LogDebug("Deleting whitespaces from offset {Offset}", offset); context.TextAgent().Delete(offset, count); } } - Log.Debug("Sending punctuation"); + _logger.LogDebug("Sending punctuation"); Context.AppAgentMgr.Keyboard.Send(modifiers != null ? modifiers.Cast().ToList() : KeyStateTracker.GetExtendedKeys(), punctuation); @@ -475,7 +474,7 @@ public bool HandlePunctuation(ArrayList modifiers, char punctuation) _autoCompleteCaretPos = context.TextAgent().GetCaretPos(); - Log.Debug("after actuating, caretpos is " + _autoCompleteCaretPos); + _logger.LogDebug("after actuating, caretpos is {CaretPos}", _autoCompleteCaretPos); KeyStateTracker.KeyTriggered(punctuation); @@ -483,7 +482,7 @@ public bool HandlePunctuation(ArrayList modifiers, char punctuation) } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, ex.Message); } finally { @@ -517,7 +516,7 @@ public void HandleVirtualKey(ArrayList modifiers, string value) } catch { - Log.Error("Invalid virtual key " + value.Substring(1)); + _logger.LogError("Invalid virtual key {VirtualKey}", value.Substring(1)); } } @@ -535,7 +534,7 @@ public Keys MapVirtualKey(string value) } catch { - Log.Error("Invalid virtual key " + value.Substring(1)); + _logger.LogError("Invalid virtual key {VirtualKey}", value.Substring(1)); return Keys.None; } @@ -578,8 +577,8 @@ public void SmartDeletePrevWord() { try { - Log.Debug("LastAction: " + _lastAction + ", currentEditingMode: " + - Context.AppAgentMgr.CurrentEditingMode); + _logger.LogDebug("LastAction: {LastAction}, currentEditingMode: {CurrentEditingMode}", + _lastAction, Context.AppAgentMgr.CurrentEditingMode); using (var context = Context.AppAgentMgr.ActiveContext()) { @@ -608,7 +607,7 @@ public void SmartDeletePrevWord() } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, ex.Message); } _lastAction = LastAction.Unknown; @@ -627,15 +626,15 @@ public void SpellCheck() return; } - Log.Debug("char left of caret: [" + charAtCaret + "]"); + _logger.LogDebug("char left of caret: [{CharAtCaret}]", charAtCaret); if (!TextUtils.IsTerminatorOrWhiteSpace(charAtCaret)) { - Log.Debug("no sentence terminator or white space here. returning"); + _logger.LogDebug("no sentence terminator or white space here. returning"); return; } int startPos = AgentManager.Instance.TextControlAgent.GetPreviousWordAtCaret(out string word); - Log.Debug("Prev word: [" + word + "]"); + _logger.LogDebug("Prev word: [{Word}]", word); if (string.IsNullOrEmpty(word)) { return; @@ -643,9 +642,9 @@ public void SpellCheck() bool isFirstWord = AgentManager.Instance.TextControlAgent.IsPreviousWordAtCaretTheFirstWord(); - Log.Debug("Looking up " + word); + _logger.LogDebug("Looking up {Word}", word); string replacement = Context.AppSpellCheckManager.ActiveSpellChecker.Lookup(word); - Log.Debug("Replacement is [" + replacement + "]"); + _logger.LogDebug("Replacement is [{Replacement}]", replacement); if (string.IsNullOrEmpty(replacement) && isFirstWord) { replacement = word; @@ -670,8 +669,8 @@ public void UndoLastEditChange() { try { - Log.Debug("LastAction: " + _lastAction + ", currentEditingMode: " + - Context.AppAgentMgr.CurrentEditingMode); + _logger.LogDebug("LastAction: {LastAction}, currentEditingMode: {CurrentEditingMode}", + _lastAction, Context.AppAgentMgr.CurrentEditingMode); if (Context.AppAgentMgr.CurrentEditingMode != EditingMode.TextEntry) { @@ -715,7 +714,7 @@ public void UndoLastEditChange() } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, ex.Message); } _lastAction = LastAction.Unknown; @@ -760,7 +759,7 @@ private void deletePreviousPunctuation() { int numChars = 2; // punctuation + space after punctuation context.TextAgent().GetPrecedingCharacters(numChars, out string precedingChars); - Log.Debug("prev " + numChars + " chars are : [" + precedingChars + "]"); + _logger.LogDebug("prev {NumChars} chars are : [{PrecedingChars}]", numChars, precedingChars); if (precedingChars.Length == numChars && ResourceUtils.LanguageSettings().IsInsertSpaceAfterChar(precedingChars[0])) { Context.AppAgentMgr.Keyboard.Send(Keys.Back, numChars); @@ -778,7 +777,7 @@ private void deletePreviousPunctuation() } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, ex.Message); } } @@ -795,12 +794,12 @@ private void postAutoCompleteWord() { bool retVal = context.TextAgent().GetCharAtCaret(out char charAtCaret); - Log.Debug("charAtCaret is " + Convert.ToInt32(charAtCaret)); + _logger.LogDebug("charAtCaret is {CharAtCaretInt}", Convert.ToInt32(charAtCaret)); if (!char.IsPunctuation(charAtCaret) && (!retVal || charAtCaret == 0x0D || !char.IsWhiteSpace(charAtCaret))) { - Log.Debug("Sending space suffix... caretpos is " + context.TextAgent().GetCaretPos()); + _logger.LogDebug("Sending space suffix... caretpos is {CaretPos}", context.TextAgent().GetCaretPos()); Context.AppAgentMgr.Keyboard.Send(KeyStateTracker.GetExtendedKeys(), ' '); - Log.Debug("Done sending space suffix caretPos is " + context.TextAgent().GetCaretPos()); + _logger.LogDebug("Done sending space suffix caretPos is {CaretPos}", context.TextAgent().GetCaretPos()); KeyStateTracker.KeyTriggered(' '); } else if (char.IsWhiteSpace(charAtCaret)) @@ -812,7 +811,7 @@ private void postAutoCompleteWord() } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, ex.Message); } } @@ -831,9 +830,9 @@ private void replaceMisspeltWord(string word, string replacement, int startPos, { using AgentContext context = Context.AppAgentMgr.ActiveContext(); string textToCaret = context.TextAgent().GetStringToCaret(startPos); - Log.Debug("textToCaret : [" + textToCaret + "]"); + _logger.LogDebug("textToCaret : [{TextToCaret}]", textToCaret); replacement = textToCaret.Replace(word, replacement); - Log.Debug("After replacement, replacement : [" + replacement + "]"); + _logger.LogDebug("After replacement, replacement : [{Replacement}]", replacement); if (isFirstWord) { string cap = TextUtils.Capitalize(replacement); @@ -843,14 +842,14 @@ private void replaceMisspeltWord(string word, string replacement, int startPos, } } - Log.Debug("Replace word at " + startPos + ". Length: " + replacement.Length + ". replacement: " + - replacement); + _logger.LogDebug("Replace word at {StartPos}. Length: {Length}. replacement: {Replacement}", + startPos, replacement.Length, replacement); context.TextAgent().Replace(startPos, word.Length + 1, replacement); } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, ex.Message); } } diff --git a/src/Libraries/ACATCore/PanelManagement/Context.cs b/src/Libraries/ACATCore/PanelManagement/Context.cs index 6f38f83a..a7588042 100644 --- a/src/Libraries/ACATCore/PanelManagement/Context.cs +++ b/src/Libraries/ACATCore/PanelManagement/Context.cs @@ -383,7 +383,7 @@ public static bool Init(StartupFlags startup = StartupFlags.All) retVal = false; } - Log.Debug("Returning " + retVal + " from context init"); + LogManager.GetLogger(typeof(Context)).LogDebug("Returning {RetVal} from context init", retVal); return retVal; } diff --git a/src/Libraries/ACATCore/PanelManagement/PanelConfig/PanelConfigMap.cs b/src/Libraries/ACATCore/PanelManagement/PanelConfig/PanelConfigMap.cs index ec8195c2..179d6864 100644 --- a/src/Libraries/ACATCore/PanelManagement/PanelConfig/PanelConfigMap.cs +++ b/src/Libraries/ACATCore/PanelManagement/PanelConfig/PanelConfigMap.cs @@ -7,6 +7,7 @@ using ACAT.Core.UserManagement; using ACAT.Core.Utility; using ACAT.Core.Utility.TypeLoader; +using Microsoft.Extensions.Logging; using System; using System.Collections; using System.Collections.Generic; @@ -28,6 +29,8 @@ namespace ACAT.Core.PanelManagement.PanelConfig /// public class PanelConfigMap { + private static readonly ILogger _logger = LogManager.GetLogger(); + /// /// Name of the panel class config file. This file contains a /// list of panel configurations to use @@ -237,7 +240,7 @@ public static bool Load(IEnumerable extensionDirs) var agents = AgentManager.Instance.GetExtensions(); foreach (IApplicationAgent agent in agents.Cast()) { - Log.Debug("Loading agent " + agent); + _logger?.LogDebug("Loading agent {Agent}", agent); addTypeToCache(agent.GetType()); } @@ -251,7 +254,7 @@ public static bool Load(IEnumerable extensionDirs) } var configsDir = FileUtils.GetPanelConfigDir(); - Log.Debug($"Loading resources from {configsDir}"); + _logger?.LogDebug("Loading resources from {ConfigsDir}", configsDir); if (Directory.Exists(Path.Combine(configsDir, "common"))) { @@ -377,11 +380,11 @@ internal static void AddFormToCache(Guid guid, Type type) { if (_formsCache.ContainsKey(guid)) { - Log.Debug("Form Type " + type.FullName + ", guid " + guid + " is already added"); + _logger?.LogDebug("Form Type {TypeName} with guid {Guid} is already added", type.FullName, guid); return; } - Log.Debug("Adding form " + type.FullName + ", guid " + guid + " to cache"); + _logger?.LogDebug("Adding form {TypeName} with guid {Guid} to cache", type.FullName, guid); _formsCache.Add(guid, type); updateFormTypeReferences(guid, type); @@ -393,29 +396,29 @@ internal static void AddFormToCache(Guid guid, Type type) /// internal static void CleanupOrphans() { - Log.Debug("Cleaning up panelConfigMap entries..."); + _logger?.LogDebug("Cleaning up panelConfigMap entries"); var removeList = new List(); foreach (var mapEntry in _masterPanelConfigMapTable.Values) { - Log.Debug("Looking up " + mapEntry.ToString()); + _logger?.LogDebug("Looking up entry: {Entry}", mapEntry.ToString()); if (_formsCache.ContainsKey(mapEntry.FormId)) { mapEntry.FormType = (Type)_formsCache[mapEntry.FormId]; } - Log.IsNull("mapEntry.FormType ", mapEntry.FormType); + _logger?.LogTrace("FormType is null: {IsNull}", mapEntry.FormType == null); var configFilePath = getConfigFilePathFromLocationMap(mapEntry.ConfigFileName); if (mapEntry.FormType != null && !string.IsNullOrEmpty(configFilePath)) { - Log.Debug("Yes. _configFileLocationMap has configFile " + mapEntry.ConfigFileName); + _logger?.LogDebug("Found config file {ConfigFileName} in location map", mapEntry.ConfigFileName); mapEntry.ConfigFileName = configFilePath; } else { - Log.Debug("No. _configFileLocationMap does not have configFile " + mapEntry.ConfigFileName); + _logger?.LogDebug("Config file {ConfigFileName} not found in location map - marking for removal", mapEntry.ConfigFileName); removeList.Add(mapEntry); } } @@ -448,7 +451,7 @@ internal static Guid GetFormId(Type type) } else { - Log.Error("Type " + type.FullName + " does not have a valid ACAT descriptor guid"); + _logger?.LogError("Type {TypeName} does not have a valid ACAT descriptor guid", type.FullName); } } @@ -661,7 +664,7 @@ private static bool loadTypesFromAssembly(Assembly assembly) } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger?.LogError(ex, "Error loading types from assembly"); retVal = false; } @@ -684,26 +687,26 @@ private static void onDllFound(string dllName) try { - Log.Debug("Found dll " + dllName); + _logger?.LogDebug("Found dll {DllName}", dllName); typeLoader.LoadFromAssembly(dllName, false); foreach (var type in typeLoader.LoadedTypes.Values) { - Log.Debug("Found type " + type.FullName); + _logger?.LogDebug("Found type {TypeName}", type.FullName); addTypeToCache(type); } } catch (BadImageFormatException ex) { - Log.Exception($"Error loading dll {dllName} Exception: {ex.Message}"); + _logger?.LogError(ex, "Error loading dll {DllName}", dllName); //_DLLError = true; } catch (Exception ex) { - Log.Exception($"Error loading dll{dllName} Exception: {ex.Message}"); + _logger?.LogError(ex, "Error loading dll {DllName}", dllName); _DLLError = true; } } @@ -738,7 +741,7 @@ private static void onPanelConfigMapFileFound(string configFileName) } catch (Exception ex) { - Log.Exception(ex); + _logger?.LogError(ex, "Error loading panel config map"); } } /// @@ -758,12 +761,12 @@ private static void onXmlFileFound(string xmlFileName) if (_loadConfigFileLocationMap.ContainsKey(fileName)) { - Log.Debug($"Updating xmlfile {fileName}, fullPath: {xmlFileName}"); + _logger?.LogDebug("Updating xml file {FileName}, full path: {FullPath}", fileName, xmlFileName); _loadConfigFileLocationMap[fileName] = xmlFileName; } else { - Log.Debug($"Adding xmlfile {fileName}, fullPath: {xmlFileName}"); + _logger?.LogDebug("Adding xml file {FileName}, full path: {FullPath}", fileName, xmlFileName); _loadConfigFileLocationMap.Add(fileName, xmlFileName); } } diff --git a/src/Libraries/ACATCore/PanelManagement/PanelConfig/PanelConfigMapEntry.cs b/src/Libraries/ACATCore/PanelManagement/PanelConfig/PanelConfigMapEntry.cs index 0992d7fe..83be6962 100644 --- a/src/Libraries/ACATCore/PanelManagement/PanelConfig/PanelConfigMapEntry.cs +++ b/src/Libraries/ACATCore/PanelManagement/PanelConfig/PanelConfigMapEntry.cs @@ -6,6 +6,7 @@ //////////////////////////////////////////////////////////////////////////// using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Xml; @@ -18,6 +19,8 @@ namespace ACAT.Core.PanelManagement.PanelConfig /// public class PanelConfigMapEntry { + private static readonly ILogger _logger = LogManager.GetLogger(typeof(PanelConfigMapEntry)); + private readonly Dictionary _userControlsDict = new(); /// @@ -175,7 +178,7 @@ public override string ToString() { if (FormType == null) { - Log.Debug("FORM TYPE IS NULL"); + _logger.LogDebug("FORM TYPE IS NULL"); } return "PanelConfigMapEntry. configName: " + ConfigName + diff --git a/src/Libraries/ACATCore/PanelManagement/PanelConfig/PreferredPanelConfig.cs b/src/Libraries/ACATCore/PanelManagement/PanelConfig/PreferredPanelConfig.cs index 07da4242..ede8096c 100644 --- a/src/Libraries/ACATCore/PanelManagement/PanelConfig/PreferredPanelConfig.cs +++ b/src/Libraries/ACATCore/PanelManagement/PanelConfig/PreferredPanelConfig.cs @@ -24,6 +24,7 @@ using System.IO; using System.Xml; using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; #region SupressStyleCopWarnings @@ -69,6 +70,8 @@ namespace ACAT.Core.PanelManagement /// internal class PreferredPanelConfig { + private static readonly ILogger _logger = LoggingConfiguration.CreateLogger(); + /// /// Name of the preferred config file /// @@ -226,8 +229,7 @@ private bool loadPreferredPanelConfig(String file) String name = XmlUtils.GetXMLAttrString(node, "name").ToLower().Trim(); if (String.IsNullOrEmpty(name) || _mapping.ContainsKey(name)) { - Log.Debug("PreferredPanelconfig will not be added. Name either already exists or is empty " + - name); + _logger.LogDebug("PreferredPanelconfig will not be added. Name either already exists or is empty {Name}", name); continue; } @@ -240,7 +242,7 @@ private bool loadPreferredPanelConfig(String file) } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex, "Error loading preferred panel config"); retVal = false; } diff --git a/src/Libraries/ACATCore/PanelManagement/PanelStack.cs b/src/Libraries/ACATCore/PanelManagement/PanelStack.cs index 2930b5f6..5d338e92 100644 --- a/src/Libraries/ACATCore/PanelManagement/PanelStack.cs +++ b/src/Libraries/ACATCore/PanelManagement/PanelStack.cs @@ -365,12 +365,12 @@ public void CloseCurrentForm() /// public void CloseCurrentPanel() { - Log.Verbose(); + _logger?.LogTrace(nameof(CloseCurrentPanel)); bool isCurrentForm = false; if (_currentPanel != null) { - Log.Debug("Will close panel. _currentPanel.name is " + _currentPanel.Name); + _logger?.LogDebug("Will close panel. _currentPanel.name is " + _currentPanel.Name); Form f = _currentPanel; while (true) { @@ -381,18 +381,18 @@ public void CloseCurrentPanel() if (f is IScannerPanel) { - Log.Debug("panelClass: " + ((IScannerPanel)f).PanelClass); + _logger?.LogDebug("panelClass: " + ((IScannerPanel)f).PanelClass); } if (f.Owner != null) { - Log.Debug("This one has a owner"); + _logger?.LogDebug("This one has a owner"); Control form = f.Owner; f = (Form)form; } else { - Log.Debug("Setting currentpanel to null. This one does not has a owner. Closing " + + _logger?.LogDebug("Setting currentpanel to null. This one does not has a owner. Closing " + f.Name + ", type: " + f.GetType()); Windows.CloseForm(f); @@ -404,7 +404,7 @@ public void CloseCurrentPanel() } else { - Log.Debug("_currentPanel is null"); + _logger?.LogDebug("_currentPanel is null"); } if (isCurrentForm) @@ -443,11 +443,11 @@ public Form CreatePanel(String panelClass, String title) /// the form for the panel public Form CreatePanel(String panelClass, String panelTitle, StartupArg startupArg) { - Log.Debug("panelClass: " + panelClass); + _logger?.LogDebug("panelClass: " + panelClass); Form form = CreatePanel(ref panelClass, panelTitle, IntPtr.Zero, null); - Log.IsNull("Form for this panel ", form); + _logger?.LogDebug("Form for this panel " + ". " + ((form != null) ? " is not null " : " is null ")); if (form is IPanel) { @@ -455,7 +455,7 @@ public Form CreatePanel(String panelClass, String panelTitle, StartupArg startup (form as IPanel).Initialize(startupArg); } - Log.Debug("Returning form from DynamicallyCreatePanelForm"); + _logger?.LogDebug("Returning form from DynamicallyCreatePanelForm"); return form; } @@ -474,24 +474,24 @@ public Form CreatePanel( IntPtr winHandle, AutomationElement focusedElement) { - Log.Debug($"Searching for panel of type {panelClass}"); + _logger?.LogDebug($"Searching for panel of type {panelClass}"); var panelConfigMapEntry = PanelConfigMap.GetPanelConfigMapEntry(panelClass); if (panelConfigMapEntry == null) { - Log.Warn($"Could not find panel for {panelClass} - Using default."); + _logger?.LogWarning($"Could not find panel for {panelClass} - Using default."); panelClass = PanelClasses.Alphabet; panelConfigMapEntry = PanelConfigMap.GetPanelConfigMapEntry(PanelClasses.Alphabet); if (panelConfigMapEntry == null) { - Log.Error($"Unable to find an appropriate panel class."); + _logger?.LogError($"Unable to find an appropriate panel class."); return null; } } - Log.Debug($"Found panel class {panelConfigMapEntry.PanelClass} with. name {panelConfigMapEntry.FormType.Name}"); + _logger?.LogDebug($"Found panel class {panelConfigMapEntry.PanelClass} with. name {panelConfigMapEntry.FormType.Name}"); var form = DynamicallyCreatePanelForm(panelClass, panelTitle, panelConfigMapEntry.FormType, winHandle, focusedElement); return form; @@ -540,7 +540,7 @@ public void Pause() { if (_currentForm is IPanel) { - Log.Debug("Pausing _currentForm " + _currentForm.Name + ", IsModal: " + _currentForm.Modal); + _logger?.LogDebug("Pausing _currentForm " + _currentForm.Name + ", IsModal: " + _currentForm.Modal); (_currentForm as IPanel).OnPause(); IsPaused = true; } @@ -556,7 +556,7 @@ public void Resume() return; } - Log.Debug("Calling OnResume on " + _currentForm.Name); + _logger?.LogDebug("Calling OnResume on " + _currentForm.Name); (_currentForm as IPanel).OnResume(); @@ -618,7 +618,7 @@ public bool ShowDialog(IPanel parent, IPanel panel) var form = (Form)panel; - Log.Debug("showDialog " + form.Name + ", type: " + form.GetType()); + _logger?.LogDebug("showDialog " + form.Name + ", type: " + form.GetType()); bool retVal; // if parent has not been specified, used the current form @@ -626,18 +626,18 @@ public bool ShowDialog(IPanel parent, IPanel panel) // show. if (parent == null) { - Log.Debug("parent passed is null"); - Log.IsNull("_currentForm ", _currentForm); - Log.IsNull("_currentPanel ", _currentPanel); + _logger?.LogDebug("parent passed is null"); + _logger?.LogDebug("_currentForm " + ". " + ((_currentForm != null) ? " is not null " : " is null ")); + _logger?.LogDebug("_currentPanel " + ". " + ((_currentPanel != null) ? " is not null " : " is null ")); if (_currentForm is IPanel) { - Log.Debug("Showing as dialog child: " + panel.GetType() + ", parent: " + _currentForm.GetType()); + _logger?.LogDebug("Showing as dialog child: " + panel.GetType() + ", parent: " + _currentForm.GetType()); retVal = show((IPanel)_currentForm, panel, DisplayModeTypes.Dialog); } else { - Log.Debug("Just showing " + form.GetType()); + _logger?.LogDebug("Just showing " + form.GetType()); //retVal = Show(panel); retVal = show(null, panel, DisplayModeTypes.Dialog); } @@ -645,7 +645,7 @@ public bool ShowDialog(IPanel parent, IPanel panel) else { var parentForm = parent as Form; - Log.Debug("showDialog parent: " + parentForm.Name + ", type: " + parentForm.GetType()); + _logger?.LogDebug("showDialog parent: " + parentForm.Name + ", type: " + parentForm.GetType()); retVal = show(parent, panel, DisplayModeTypes.Dialog); } @@ -748,7 +748,7 @@ private Form DynamicallyCreatePanelForm( IntPtr winHandle, AutomationElement focusedElement) { - Log.Debug($"*** panelClass: [{panelClass}], panel: [{type.FullName}] title: [{panelTitle ?? "null"}]"); + _logger?.LogDebug($"*** panelClass: [{panelClass}], panel: [{type.FullName}] title: [{panelTitle ?? "null"}]"); var constructorArgSets = new object[][] { @@ -775,11 +775,11 @@ private Form DynamicallyCreatePanelForm( } catch (Exception ex) { - Log.Exception($"Constructor failed with args ({string.Join(", ", args.Select(a => a?.ToString() ?? "null"))}): {ex}"); + _logger?.LogError(ex, $"Constructor failed with args ({string.Join(", ", args.Select(a => a?.ToString() ?? "null"))})"); } } - Log.Debug($"No suitable constructor found for {type.FullName}"); + _logger?.LogDebug($"No suitable constructor found for {type.FullName}"); return null; } @@ -800,7 +800,7 @@ private bool initializePanel(IScannerPanel scannerPanel, PanelRequestEventArgs a var panelConfigMapEntry = PanelConfigMap.GetPanelConfigMapEntry(arg.PanelClass); - Log.Debug("panelClass: " + arg.PanelClass + ", ConfigFile: " + ((panelConfigMapEntry != null) ? panelConfigMapEntry.ConfigFileName : String.Empty)); + _logger?.LogDebug("panelClass: " + arg.PanelClass + ", ConfigFile: " + ((panelConfigMapEntry != null) ? panelConfigMapEntry.ConfigFileName : String.Empty)); return scannerPanel.Initialize(startupArg); } @@ -814,16 +814,16 @@ private void panel_FormClosed(object sender, FormClosedEventArgs e) { var form = (Form)sender; - Log.Debug("Enter (" + form.Name + ")"); + _logger?.LogDebug("Enter (" + form.Name + ")"); IPanel panel = form as IPanel; if (panel.SyncObj.Status == SyncLock.StatusValues.Closed) { - Log.Debug("Form is already closed. Returning " + form.Name); + _logger?.LogDebug("Form is already closed. Returning " + form.Name); return; } - Log.Debug("Setting CLOSED for " + form.Name); + _logger?.LogDebug("Setting CLOSED for " + form.Name); (form as IPanel).SyncObj.Status = SyncLock.StatusValues.Closed; form.FormClosed -= panel_FormClosed; @@ -834,7 +834,7 @@ private void panel_FormClosed(object sender, FormClosedEventArgs e) auditLogScannerEvent(form, "close"); - Log.Debug("number of owned forms: " + array.Length); + _logger?.LogDebug("number of owned forms: " + array.Length); // close all the forms this panel owns while (true) @@ -842,17 +842,17 @@ private void panel_FormClosed(object sender, FormClosedEventArgs e) Form[] ownedForms = form.OwnedForms; if (ownedForms.Length == 0) { - Log.Debug(form.Name + ": No more owned forms. Breaking"); + _logger?.LogDebug(form.Name + ": No more owned forms. Breaking"); break; } - Log.Debug("Removing owned form from list. " + ownedForms[0].Name); + _logger?.LogDebug("Removing owned form from list. " + ownedForms[0].Name); form.RemoveOwnedForm(ownedForms[0]); - Log.Debug("Calling close on " + ownedForms[0].Name); + _logger?.LogDebug("Calling close on " + ownedForms[0].Name); Windows.CloseForm(ownedForms[0]); } - Log.Debug("form Name: " + form.Name + ", type: " + form.GetType()); + _logger?.LogDebug("form Name: " + form.Name + ", type: " + form.GetType()); // Exit the application if instructed to do so. if (Context.AppQuit) @@ -870,23 +870,23 @@ private void panel_FormClosed(object sender, FormClosedEventArgs e) { // Resume the parent if it is prudent to do so. - Log.Debug("parent Form is " + parentForm.Name); + _logger?.LogDebug("parent Form is " + parentForm.Name); IPanel parentPanel = (IPanel)parentForm; if (parentPanel.SyncObj.IsClosing()) { - Log.Debug("*** Parent is closing. Will not call OnResume"); + _logger?.LogDebug("*** Parent is closing. Will not call OnResume"); } else { - Log.Debug("parent form is not closing. Setting _currentPanel to " + parentForm.Name + + _logger?.LogDebug("parent form is not closing. Setting _currentPanel to " + parentForm.Name + ", type: " + parentForm.GetType()); _currentPanel = parentForm; _currentForm = parentForm; - Log.Debug("Calling OnResume on parentForm " + parentForm.Name); + _logger?.LogDebug("Calling OnResume on parentForm " + parentForm.Name); parentPanel.OnResume(); @@ -898,7 +898,7 @@ private void panel_FormClosed(object sender, FormClosedEventArgs e) } else { - Log.Debug("parentform is null"); + _logger?.LogDebug("parentform is null"); _currentPanel = null; _currentForm = null; } @@ -906,23 +906,23 @@ private void panel_FormClosed(object sender, FormClosedEventArgs e) var panelClass = (form is IScannerPanel) ? ((IScannerPanel)form).PanelClass : PanelClasses.None; if (!PanelConfigMap.AreEqual(panelClass, PanelClasses.None)) { - Log.Debug("Calling AppAgentMgr.OnPanelClosed for " + panelClass); + _logger?.LogDebug("Calling AppAgentMgr.OnPanelClosed for " + panelClass); Context.AppAgentMgr.OnPanelClosed(panelClass); } if (EvtScannerClosed != null) { - Log.Debug("Calling evetscannerclosed for " + form.Name); + _logger?.LogDebug("Calling evetscannerclosed for " + form.Name); EvtScannerClosed(this, new ScannerCloseEventArg(form as IPanel)); } else { - Log.Debug("EvtScannerClosed is NULL"); + _logger?.LogDebug("EvtScannerClosed is NULL"); } // (form as IPanel).SyncObj.Status = SyncLock.StatusValues.Closed; // moved this up - Log.Debug("Exit " + form.Name); + _logger?.LogDebug("Exit " + form.Name); } /// @@ -940,7 +940,7 @@ private bool show(IPanel parent, IPanel panel, DisplayModeTypes displayMode) Form panelForm = (Form)panel; Form parentForm = (Form)parent; - Log.Debug("parentForm: " + ((parentForm != null) ? parentForm.Name : " null") + + _logger?.LogDebug("parentForm: " + ((parentForm != null) ? parentForm.Name : " null") + ". panel: " + panelForm.Name); panelForm.FormClosed += panel_FormClosed; @@ -956,7 +956,7 @@ private bool show(IPanel parent, IPanel panel, DisplayModeTypes displayMode) if (displayMode == DisplayModeTypes.Dialog) { - Log.Debug("Showing Dialog" + panelForm.Name + " with parent " + parentForm.Name); + _logger?.LogDebug("Showing Dialog" + panelForm.Name + " with parent " + parentForm.Name); auditLogScannerEvent(panelForm, "show"); Context.AppPanelManager.NotifyPanelPreShow(new PanelPreShowEventArg(panel, displayMode)); @@ -964,9 +964,9 @@ private bool show(IPanel parent, IPanel panel, DisplayModeTypes displayMode) } else { - Log.Debug("Showing " + panelForm.Name); + _logger?.LogDebug("Showing " + panelForm.Name); - Log.Debug("parent is not null. Setting _currentPanel to " + panelForm.Name + + _logger?.LogDebug("parent is not null. Setting _currentPanel to " + panelForm.Name + ", type: " + panelForm.GetType()); _currentPanel = panelForm; auditLogScannerEvent(panelForm, "show"); @@ -978,8 +978,8 @@ private bool show(IPanel parent, IPanel panel, DisplayModeTypes displayMode) } else { - Log.Debug("showing " + panelForm.Name + ", parent is null"); - Log.Debug("parent is null. Setting _currentPanel to " + panelForm.Name + + _logger?.LogDebug("showing " + panelForm.Name + ", parent is null"); + _logger?.LogDebug("parent is null. Setting _currentPanel to " + panelForm.Name + ", type: " + panelForm.GetType()); _currentPanel = panelForm; @@ -1013,38 +1013,38 @@ private bool show(IPanel parent, IPanel panel, DisplayModeTypes displayMode) /// Info about which scanner to display private void switchCurrentPanel(PanelRequestEventArgs eventArg) { - Log.Verbose(); + _logger?.LogTrace(nameof(switchCurrentPanel)); - Log.Debug(eventArg.ToString()); + _logger?.LogDebug(eventArg.ToString()); if (!eventArg.UseCurrentScreenAsParent) { - Log.Debug("UseCurrentScreenAsParent is false. closing current panel " + + _logger?.LogDebug("UseCurrentScreenAsParent is false. closing current panel " + ((_currentPanel != null) ? _currentPanel.Name : "")); CloseCurrentPanel(); } - Log.Debug("Creating panel ..." + eventArg.PanelClass); + _logger?.LogDebug("Creating panel ..." + eventArg.PanelClass); Form form = createPanel(eventArg); - Log.Debug("Calling show for ..." + eventArg.PanelClass); + _logger?.LogDebug("Calling show for ..." + eventArg.PanelClass); if (form == null) { - Log.Debug("DynamicallyCreatePanelForm returned null!!"); + _logger?.LogDebug("DynamicallyCreatePanelForm returned null!!"); } else { initializePanel(form as IScannerPanel, eventArg); - Log.Debug("Calling show for ..." + eventArg.PanelClass); + _logger?.LogDebug("Calling show for ..." + eventArg.PanelClass); if (eventArg.UseCurrentScreenAsParent && _currentForm is IPanel) { - Log.Debug("Showing form " + form.Name + ", parent " + _currentForm.Name); + _logger?.LogDebug("Showing form " + form.Name + ", parent " + _currentForm.Name); Show((IPanel)_currentForm, (IPanel)form); } else { - Log.Debug("Showing form " + form.Name + " without parent."); + _logger?.LogDebug("Showing form " + form.Name + " without parent."); Show(null, (IPanel)form); } } diff --git a/src/Libraries/ACATCore/PanelManagement/UI/MenuPanelBase.cs b/src/Libraries/ACATCore/PanelManagement/UI/MenuPanelBase.cs index e8178107..a39b60c5 100644 --- a/src/Libraries/ACATCore/PanelManagement/UI/MenuPanelBase.cs +++ b/src/Libraries/ACATCore/PanelManagement/UI/MenuPanelBase.cs @@ -12,6 +12,7 @@ using ACAT.Core.Utility; using ACAT.Core.WidgetManagement; using ACAT.Core.WidgetManagement.Interfaces; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; @@ -27,6 +28,8 @@ namespace ACAT.Core.PanelManagement /// public partial class MenuPanelBase : Form, IScannerPanel { + private static readonly ILogger _logger = LogManager.GetLogger(typeof(MenuPanelBase)); + /// /// Title of the scanner /// @@ -188,7 +191,7 @@ public bool Initialize(StartupArg arg) if (!scannerCommon.Initialize(startupArg)) { - Log.Error($"Could not initialize form {Name}"); + _logger.LogError("Could not initialize form {FormName}", Name); return false; } diff --git a/src/Libraries/ACATCore/PanelManagement/UI/ToastForm.cs b/src/Libraries/ACATCore/PanelManagement/UI/ToastForm.cs index 610b1082..b2d971ec 100644 --- a/src/Libraries/ACATCore/PanelManagement/UI/ToastForm.cs +++ b/src/Libraries/ACATCore/PanelManagement/UI/ToastForm.cs @@ -6,6 +6,7 @@ //////////////////////////////////////////////////////////////////////////// using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.ComponentModel; using System.Threading; @@ -20,6 +21,8 @@ namespace ACAT.Core.PanelManagement /// public partial class ToastForm : Form { + private static readonly ILogger _logger = LogManager.GetLogger(typeof(ToastForm)); + /// /// Thread proc for fading out /// @@ -87,7 +90,7 @@ private void fadeOutProc() } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, ex.Message); } } } diff --git a/src/Libraries/ACATCore/PanelManagement/UI/ToastForm2.cs b/src/Libraries/ACATCore/PanelManagement/UI/ToastForm2.cs index 88d57807..d2cd7c9e 100644 --- a/src/Libraries/ACATCore/PanelManagement/UI/ToastForm2.cs +++ b/src/Libraries/ACATCore/PanelManagement/UI/ToastForm2.cs @@ -6,6 +6,7 @@ //////////////////////////////////////////////////////////////////////////// using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.ComponentModel; using System.Threading; @@ -20,6 +21,8 @@ namespace ACAT.Core.PanelManagement /// public partial class ToastForm2 : Form { + private static readonly ILogger _logger = LogManager.GetLogger(typeof(ToastForm2)); + /// /// Thread proc for fading out /// @@ -88,7 +91,7 @@ private void fadeOutProc() } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, ex.Message); } } } diff --git a/src/Libraries/ACATCore/PanelManagement/Utils/DockScanner.cs b/src/Libraries/ACATCore/PanelManagement/Utils/DockScanner.cs index 71219cde..2a00fff2 100644 --- a/src/Libraries/ACATCore/PanelManagement/Utils/DockScanner.cs +++ b/src/Libraries/ACATCore/PanelManagement/Utils/DockScanner.cs @@ -1,4 +1,5 @@ using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Windows.Automation; using System.Windows.Forms; @@ -11,6 +12,8 @@ namespace ACAT.Core.PanelManagement.Utils /// public class DockScanner : IDisposable { + private static readonly ILogger _logger = LogManager.GetLogger(typeof(DockScanner)); + /// /// If docking to a window, relative position of the dock /// @@ -85,7 +88,7 @@ public void Dock() } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex, ex.Message); _automationElementDockTo = null; } } @@ -124,7 +127,7 @@ protected virtual void Dispose(bool disposing) // Check to see if Dispose has already been called. if (!_disposed) { - Log.Verbose(); + _logger.LogDebug("Disposing DockScanner"); if (disposing) { diff --git a/src/Libraries/ACATCore/PanelManagement/Utils/Fonts.cs b/src/Libraries/ACATCore/PanelManagement/Utils/Fonts.cs index fe36a076..db34a00b 100644 --- a/src/Libraries/ACATCore/PanelManagement/Utils/Fonts.cs +++ b/src/Libraries/ACATCore/PanelManagement/Utils/Fonts.cs @@ -6,6 +6,7 @@ //////////////////////////////////////////////////////////////////////////// using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Drawing; using System.Drawing.Text; @@ -29,6 +30,8 @@ public class Fonts : IDisposable /// private static readonly Fonts _instance = new(); + private static readonly ILogger _logger = LogManager.GetLogger(); + /// /// Collection of installed fonts /// @@ -65,7 +68,7 @@ public static void LoadFontsFromDir(string directory) { if (!Directory.Exists(directory)) { - Log.Info("No user fonts installed."); + _logger.LogInformation("No user fonts installed"); return; } loadFontsFromDir(directory, "*.ttf"); @@ -87,7 +90,7 @@ public bool AddFontFile(string fontFileName) } catch (Exception ex) { - Log.Exception("Could not add font file " + fontFileName + ", exception: " + ex); + _logger.LogError(ex, "Could not add font file {FontFileName}", fontFileName); retVal = false; } return retVal; @@ -133,7 +136,7 @@ public FontFamily GetFontFamily(string[] fontNames) private static void loadFontsFromDir(string directory, string wildCard) { var walker = new DirectoryWalker(directory, wildCard); - Log.Verbose("Walking dir " + directory); + _logger.LogTrace("Walking dir {Directory}", directory); walker.Walk(new OnFileFoundDelegate(onFileFound)); } @@ -143,7 +146,7 @@ private static void loadFontsFromDir(string directory, string wildCard) /// private static void onFileFound(string file) { - Log.Verbose("Found font file " + file); + _logger.LogTrace("Found font file {File}", file); Instance.AddFontFile(file); } diff --git a/src/Libraries/ACATCore/PanelManagement/Utils/OutlineWindow.cs b/src/Libraries/ACATCore/PanelManagement/Utils/OutlineWindow.cs index 6c3f560b..8b60a9e9 100644 --- a/src/Libraries/ACATCore/PanelManagement/Utils/OutlineWindow.cs +++ b/src/Libraries/ACATCore/PanelManagement/Utils/OutlineWindow.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.PanelManagement.Utils /// internal class OutlineWindow : IDisposable { + private static ILogger _logger; + /// /// Width of the pen to draw the border /// @@ -71,7 +74,7 @@ public void Dispose() /// width of the pen public void Draw(Rectangle rectangle, int penWidth = 0) { - Log.Debug(rectangle.ToString()); + _logger?.LogDebug("Drawing rectangle: {Rectangle}", rectangle); _form.Invalidate(); _form.Refresh(); @@ -118,7 +121,7 @@ public void Draw(Rectangle rectangle, int penWidth = 0) var width = rectangle.X > 0 ? rectangle.Width : rectangle.Width + (float)rectangle.X; var height = rectangle.Y > 0 ? rectangle.Height : rectangle.Height + (float)rectangle.Y; - Log.Debug("Draw rectangle " + x + " " + y + " " + width + " " + height); + _logger?.LogDebug("Draw rectangle x={X} y={Y} width={Width} height={Height}", x, y, width, height); formGraphics.DrawRectangle(pen, x, y, width, height); } @@ -141,7 +144,7 @@ protected virtual void Dispose(bool disposing) // Check to see if Dispose has already been called. if (!_disposed) { - Log.Verbose(); + _logger?.LogTrace("Disposing OutlineWindow"); if (disposing) { @@ -170,10 +173,10 @@ private void initForm(Form form) form.FormBorderStyle = FormBorderStyle.None; form.WindowState = FormWindowState.Maximized; - Log.Debug("Form width: " + form.Width + "Form height: " + form.Height); + _logger?.LogDebug("Form width: {Width}, Form height: {Height}", form.Width, form.Height); int boundWidth = Screen.PrimaryScreen.Bounds.Width; int boundHeight = Screen.PrimaryScreen.Bounds.Height; - Log.Debug("boundWidth=" + boundWidth + " boundHeight=" + boundHeight); + _logger?.LogDebug("boundWidth={BoundWidth}, boundHeight={BoundHeight}", boundWidth, boundHeight); form.Location = new Point(0, 0); } diff --git a/src/Libraries/ACATCore/PanelManagement/Utils/WindowHighlight.cs b/src/Libraries/ACATCore/PanelManagement/Utils/WindowHighlight.cs index 0ccc4f3b..1684aff8 100644 --- a/src/Libraries/ACATCore/PanelManagement/Utils/WindowHighlight.cs +++ b/src/Libraries/ACATCore/PanelManagement/Utils/WindowHighlight.cs @@ -1,4 +1,5 @@ using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Windows.Automation; using System.Windows.Forms; @@ -11,6 +12,8 @@ namespace ACAT.Core.PanelManagement.Utils /// public class WindowHighlight : IDisposable { + private static readonly ILogger _logger = LoggerFactory.Create(builder => builder.AddConsole()).CreateLogger(); + /// /// Scanner form. /// @@ -58,7 +61,7 @@ public WindowHighlight(IntPtr targetWindow, Form form) } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex, ex.Message); _automationElement = null; } } @@ -84,12 +87,12 @@ protected virtual void Dispose(bool disposing) // Check to see if Dispose has already been called. if (!_disposed) { - Log.Verbose(); + _logger.LogTrace(""); if (disposing) { // dispose all managed resources. - Log.Verbose(); + _logger.LogTrace(""); stopTimer(); @@ -97,13 +100,13 @@ protected virtual void Dispose(bool disposing) { try { - Log.Debug("Disposing highlight overlay window"); + _logger.LogDebug("Disposing highlight overlay window"); _outlineWindow.Dispose(); _outlineWindow = null; } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex, ex.Message); } } @@ -130,7 +133,7 @@ private void _timer_Tick(object sender, EventArgs e) private void highlightWindow(AutomationElement focusedElement) { - Log.Verbose(); + _logger.LogTrace(""); try { lock (_sync) @@ -149,14 +152,14 @@ private void highlightWindow(AutomationElement focusedElement) } catch (Exception exp) { - Log.Exception(exp.ToString()); + _logger.LogError(exp, exp.Message); } })); } } catch (Exception e) { - Log.Exception(e.ToString()); + _logger.LogError(e, e.Message); } } diff --git a/src/Libraries/ACATCore/PreferencesManagement/PreferencesBase.cs b/src/Libraries/ACATCore/PreferencesManagement/PreferencesBase.cs index 75ac0a17..bdd16969 100644 --- a/src/Libraries/ACATCore/PreferencesManagement/PreferencesBase.cs +++ b/src/Libraries/ACATCore/PreferencesManagement/PreferencesBase.cs @@ -16,6 +16,7 @@ using ACAT.Core.PreferencesManagement.Interfaces; using ACAT.Core.Utility; using CommunityToolkit.Mvvm.ComponentModel; +using Microsoft.Extensions.Logging; using System; using System.ComponentModel; using System.Reflection; @@ -34,6 +35,8 @@ namespace ACAT.Core.PreferencesManagement [Serializable] public abstract class PreferencesBase : ObservableValidator, IPreferences, IDisposable { + private static readonly ILogger _logger = LogManager.GetLogger(); + [XmlIgnore] public bool IsDirty { get; private set; } = false; @@ -103,7 +106,7 @@ protected override void OnPropertyChanged(PropertyChangedEventArgs e) if (preferences == null) { - Log.Warn($"Could not load preferences from {preferencesFile} - creating a new one."); + _logger.LogWarning("Could not load preferences from {PreferencesFile} - creating a new one", preferencesFile); if (loadDefaultsOnFail == true) { preferences = new T(); @@ -114,7 +117,7 @@ protected override void OnPropertyChanged(PropertyChangedEventArgs e) { if (!XmlUtils.XmlFileSave(preferences, preferencesFile)) { - Log.Error("Unable to save default preferences!"); + _logger.LogError("Unable to save default preferences"); preferences = default; } } @@ -145,7 +148,7 @@ public static bool Save(T prefs, String preferencesFile) if (retVal == false) { - Log.Error("Error saving preferences! file=" + preferencesFile); + _logger.LogError("Error saving preferences to file {PreferencesFile}", preferencesFile); } return retVal; diff --git a/src/Libraries/ACATCore/SpellCheckManagement/SpellCheckManager.cs b/src/Libraries/ACATCore/SpellCheckManagement/SpellCheckManager.cs index fd9cb53b..8414537f 100644 --- a/src/Libraries/ACATCore/SpellCheckManagement/SpellCheckManager.cs +++ b/src/Libraries/ACATCore/SpellCheckManagement/SpellCheckManager.cs @@ -319,7 +319,7 @@ protected virtual void Dispose(bool disposing) // Check to see if Dispose has already been called. if (!_disposed) { - Log.Verbose(); + _logger?.LogTrace("Disposing SpellCheckManager"); if (disposing) { @@ -370,7 +370,7 @@ private bool createAndSetActiveSpellChecker(Type type, CultureInfo ci) } catch (Exception ex) { - Log.Exception("Unable to load spellchecker " + type + ", assembly: " + type.Assembly.FullName + ". Exception: " + ex); + _logger?.LogError(ex, "Unable to load spellchecker {Type}, assembly: {AssemblyName}", type, type.Assembly.FullName); retVal = false; } diff --git a/src/Libraries/ACATCore/SpellCheckManagement/SpellCheckers.cs b/src/Libraries/ACATCore/SpellCheckManagement/SpellCheckers.cs index c87d4bb3..2c7614a8 100644 --- a/src/Libraries/ACATCore/SpellCheckManagement/SpellCheckers.cs +++ b/src/Libraries/ACATCore/SpellCheckManagement/SpellCheckers.cs @@ -167,7 +167,8 @@ public Guid GetDefaultByCulture(CultureInfo ci) ClassDescriptorAttribute descriptor = ClassDescriptorAttribute.GetDescriptor(foundTuple.Item2); if (descriptor != null) { - Log.Debug("Found spellchecker for culture " + (ci != null ? ci.TwoLetterISOLanguageName : "Neutral") + "[" + descriptor.Name + "]"); + _logger?.LogDebug("Found spellchecker for culture {Culture} [{Name}]", + (ci != null ? ci.TwoLetterISOLanguageName : "Neutral"), descriptor.Name); return descriptor.Id; } } @@ -260,12 +261,12 @@ public Type Lookup(Guid guid) ClassDescriptorAttribute descriptor = ClassDescriptorAttribute.GetDescriptor(type); if (descriptor != null && Equals(guid, descriptor.Id)) { - Log.Debug($"Found spellchecker of type {type}"); + _logger?.LogDebug("Found spellchecker of type {Type}", type); return type; } } - Log.Error($"Could not find spellchecker for id {guid}"); + _logger?.LogError("Could not find spellchecker for id {Guid}", guid); return null; } @@ -322,7 +323,7 @@ protected virtual void Dispose(bool disposing) // Check to see if Dispose has already been called. if (!_disposed) { - Log.Verbose(); + _logger?.LogTrace("Disposing SpellCheckers"); if (disposing) { @@ -399,7 +400,7 @@ private void onFileFound(String dllName) } catch (Exception ex) { - Log.Exception("Could get types from assembly " + dllName + ". Exception : " + ex); + _logger?.LogError(ex, "Could not get types from assembly {DllName}", dllName); } } } diff --git a/src/Libraries/ACATCore/TTSManagement/Pronunciation.cs b/src/Libraries/ACATCore/TTSManagement/Pronunciation.cs index 25f27729..048062be 100644 --- a/src/Libraries/ACATCore/TTSManagement/Pronunciation.cs +++ b/src/Libraries/ACATCore/TTSManagement/Pronunciation.cs @@ -6,6 +6,7 @@ //////////////////////////////////////////////////////////////////////////// using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; namespace ACAT.Core.TTSManagement @@ -21,6 +22,8 @@ namespace ACAT.Core.TTSManagement /// public class Pronunciation : IDisposable { + private readonly ILogger _logger; + /// /// Has this object been disposed /// @@ -31,9 +34,10 @@ public class Pronunciation : IDisposable /// /// original word /// phonetic spelling - public Pronunciation(String word, String altPronunciation) + public Pronunciation(String word, String altPronunciation, ILogger logger = null) { - Log.Debug("Entering...word=" + word + " altPronunciation=" + altPronunciation); + _logger = logger; + _logger?.LogDebug("Creating pronunciation: word={Word}, altPronunciation={AltPronunciation}", word, altPronunciation); Word = word; AltPronunciation = altPronunciation; } diff --git a/src/Libraries/ACATCore/TTSManagement/Pronunciations.cs b/src/Libraries/ACATCore/TTSManagement/Pronunciations.cs index 2a244e3d..e7746f8f 100644 --- a/src/Libraries/ACATCore/TTSManagement/Pronunciations.cs +++ b/src/Libraries/ACATCore/TTSManagement/Pronunciations.cs @@ -7,6 +7,7 @@ using ACAT.Core.UserManagement; using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Globalization; @@ -29,6 +30,8 @@ namespace ACAT.Core.TTSManagement /// public class Pronunciations : IDisposable { + private readonly ILogger _logger; + /// /// xml attribute to get the alternate pronunciation /// @@ -49,6 +52,11 @@ public class Pronunciations : IDisposable /// private bool _disposed; + public Pronunciations(ILogger logger = null) + { + _logger = logger; + } + /// /// Holds a mapping between words and their pronunciations /// @@ -130,7 +138,7 @@ public bool Load(String filePath) { _pronunciationList.Clear(); - Log.Debug("Found pronuncation file " + filePath); + _logger?.LogDebug("Found pronuncation file {FilePath}", filePath); doc.Load(filePath); @@ -144,7 +152,7 @@ public bool Load(String filePath) } catch (Exception ex) { - Log.Exception("Error processing pronunciation file " + filePath + ". Exception: " + ex); + _logger?.LogError(ex, "Error processing pronunciation file {FilePath}", filePath); retVal = false; } @@ -160,7 +168,7 @@ public bool Load(String filePath) /// true on success public bool Load(CultureInfo ci, String pronunciationsFileName) { - Log.Debug("Entering..."); + _logger?.LogDebug("Loading pronunciations for culture {Culture}, file {FileName}", ci.Name, pronunciationsFileName); String filePath = getPronunciationsFilePath(ci, pronunciationsFileName); @@ -217,7 +225,7 @@ public String ReplaceWithAlternatePronunciations(String inputString) var strWord = new StringBuilder(); Pronunciation pronunciation; - Log.Debug("inputString: " + inputString); + _logger?.LogDebug("Processing input string: {InputString}", inputString); foreach (char ch in inputString) { @@ -242,7 +250,7 @@ public String ReplaceWithAlternatePronunciations(String inputString) var retVal = strOutput.ToString(); - Log.Debug("replacedString: " + retVal); + _logger?.LogDebug("Replaced string: {ReplacedString}", retVal); return retVal; } @@ -273,7 +281,7 @@ public bool Save(String pronunciationsFile) } catch (IOException ex) { - Log.Exception(ex); + _logger?.LogError(ex, "IO exception while saving pronunciations"); retVal = false; } @@ -301,7 +309,7 @@ protected virtual void Dispose(bool disposing) // Check to see if Dispose has already been called. if (!_disposed) { - Log.Verbose(); + _logger?.LogTrace("Disposing Pronunciations"); if (disposing) { @@ -333,7 +341,7 @@ private static void closePronunciationFile(XmlWriter xmlTextWriter) } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger?.LogError(ex, "Exception closing pronunciation file"); } } @@ -356,7 +364,7 @@ private static XmlTextWriter createPronunciationsFile(String fileName) } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger?.LogError(ex, "Exception creating pronunciations file"); xmlTextWriter = null; } @@ -372,7 +380,7 @@ private void createAndAddPronunciation(XmlNode node) { var word = XmlUtils.GetXMLAttrString(node, WordAttr).Trim().ToLower(); var pronunciation = XmlUtils.GetXMLAttrString(node, PronunciationAttr); - Log.Debug("word=" + word + " pronunciation=" + pronunciation); + _logger?.LogDebug("Adding pronunciation - word: {Word}, pronunciation: {Pronunciation}", word, pronunciation); Add(new Pronunciation(word, pronunciation)); } diff --git a/src/Libraries/ACATCore/TTSManagement/TTSEngines.cs b/src/Libraries/ACATCore/TTSManagement/TTSEngines.cs index 4fa413b1..1fac076e 100644 --- a/src/Libraries/ACATCore/TTSManagement/TTSEngines.cs +++ b/src/Libraries/ACATCore/TTSManagement/TTSEngines.cs @@ -132,12 +132,12 @@ public Type this[Guid guid] ClassDescriptorAttribute descriptor = ClassDescriptorAttribute.GetDescriptor(type); if (descriptor != null && Guid.Equals(guid, descriptor.Id)) { - Log.Debug($"Found TTS engine of type {type}"); + _logger?.LogDebug("Found TTS engine of type {Type}", type); return type; } } - Log.Error($"Could not find TTS engine for id {guid}"); + _logger?.LogError("Could not find TTS engine for id {Guid}", guid); return null; } } @@ -205,7 +205,8 @@ public Guid GetDefaultByCulture(CultureInfo ci) ClassDescriptorAttribute descriptor = ClassDescriptorAttribute.GetDescriptor(foundTuple.Item2); if (descriptor != null) { - Log.Debug("Found TTS Engine for culture " + (ci != null ? ci.TwoLetterISOLanguageName : "Neutral") + "[" + descriptor.Name + "]"); + _logger?.LogDebug("Found TTS Engine for culture {Culture} [{Name}]", + ci != null ? ci.TwoLetterISOLanguageName : "Neutral", descriptor.Name); return descriptor.Id; } } @@ -299,12 +300,12 @@ public Type Lookup(Guid guid) ClassDescriptorAttribute descriptor = ClassDescriptorAttribute.GetDescriptor(type); if (descriptor != null && Equals(guid, descriptor.Id)) { - Log.Debug($"Found TTS Engine of type {type}"); + _logger?.LogDebug("Found TTS Engine of type {Type}", type); return type; } } - Log.Error($"Could not find TTS Engine for id {guid}"); + _logger?.LogError("Could not find TTS Engine for id {Guid}", guid); return null; } @@ -352,7 +353,7 @@ protected virtual void Dispose(bool disposing) // Check to see if Dispose has already been called. if (!_disposed) { - Log.Verbose(); + _logger?.LogTrace("Disposing TTSEngines"); if (disposing) { @@ -400,7 +401,7 @@ private void onFileFound(String dllName) } catch (Exception ex) { - Log.Exception("Could not load assembly " + dllName + ". Exception: " + ex.ToString()); + _logger?.LogError(ex, "Could not load assembly {DllName}", dllName); _DLLError = true; return; // skip further processing if there was a DLL error } diff --git a/src/Libraries/ACATCore/TTSManagement/TTSManager.cs b/src/Libraries/ACATCore/TTSManagement/TTSManager.cs index 9d0dd08d..c5aabcae 100644 --- a/src/Libraries/ACATCore/TTSManagement/TTSManager.cs +++ b/src/Libraries/ACATCore/TTSManagement/TTSManager.cs @@ -386,7 +386,7 @@ protected virtual void Dispose(bool disposing) // Check to see if Dispose has already been called. if (!_disposed) { - Log.Verbose(); + _logger?.LogTrace("Disposing TTSManager"); if (disposing) { @@ -435,7 +435,7 @@ private bool createAndSetActiveEngine(Type type, CultureInfo ci) } catch (Exception ex) { - Log.Exception("Unable to load TTS Engine" + type + ", assembly: " + type.Assembly.FullName + ". Exception: " + ex); + _logger?.LogError(ex, "Unable to load TTS Engine {Type}, assembly: {AssemblyName}", type, type.Assembly.FullName); retVal = false; } diff --git a/src/Libraries/ACATCore/ThemeManagement/ColorScheme.cs b/src/Libraries/ACATCore/ThemeManagement/ColorScheme.cs index 303b6578..096d8cc7 100644 --- a/src/Libraries/ACATCore/ThemeManagement/ColorScheme.cs +++ b/src/Libraries/ACATCore/ThemeManagement/ColorScheme.cs @@ -6,6 +6,7 @@ //////////////////////////////////////////////////////////////////////////// using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Drawing; using System.IO; @@ -20,6 +21,7 @@ namespace ACAT.Core.ThemeManagement /// public class ColorScheme : IDisposable { + private static readonly ILogger _logger = LogManager.GetLogger(); /// /// Default bg color to use if not defined in the config file /// @@ -523,7 +525,7 @@ protected virtual void Dispose(bool disposing) // Check to see if Dispose has already been called. if (!_disposed) { - Log.Verbose(); + _logger.LogTrace("Disposing ColorScheme"); if (disposing) { @@ -564,16 +566,16 @@ private 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/ThemeManagement/Theme.cs b/src/Libraries/ACATCore/ThemeManagement/Theme.cs index 8e65ac89..1620ffcd 100644 --- a/src/Libraries/ACATCore/ThemeManagement/Theme.cs +++ b/src/Libraries/ACATCore/ThemeManagement/Theme.cs @@ -6,6 +6,7 @@ //////////////////////////////////////////////////////////////////////////// using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.IO; using System.Xml; @@ -25,6 +26,8 @@ public class Theme : IDisposable /// public const String PreviewScannerImageName = "Preview.png"; + private readonly ILogger _logger; + /// /// Has this object been disposed? /// @@ -34,8 +37,9 @@ public class Theme : IDisposable /// Initializes a new instance of the class. /// /// Name of the color scheme - private Theme(String name) + private Theme(String name, ILogger logger = null) { + _logger = logger; Name = name; Colors = new ColorSchemes(); } @@ -69,7 +73,7 @@ public static Theme Create(String name) /// directory where theme assets are located /// name of the theme config file /// - public static Theme Create(String themeName, String themeDir, String themeFile) + public static Theme Create(String themeName, String themeDir, String themeFile, ILogger logger = null) { Theme theme = null; @@ -88,12 +92,12 @@ public static Theme Create(String themeName, String themeDir, String themeFile) var colorSchemesNode = doc.SelectSingleNode("/ACAT/Theme/ColorSchemes"); if (colorSchemesNode != null) { - theme = new Theme(themeName) { Colors = ColorSchemes.Create(colorSchemesNode, themeDir) }; + theme = new Theme(themeName, logger) { Colors = ColorSchemes.Create(colorSchemesNode, themeDir) }; } } catch (Exception ex) { - Log.Exception(ex.ToString()); + logger?.LogError(ex, "Failed to create theme from file: {ThemeFile}", themeFile); } return theme; @@ -120,7 +124,7 @@ protected virtual void Dispose(bool disposing) // Check to see if Dispose has already been called. if (!_disposed) { - Log.Verbose(); + _logger?.LogTrace("Disposing Theme"); if (disposing) { diff --git a/src/Libraries/ACATCore/ThemeManagement/ThemeManager.cs b/src/Libraries/ACATCore/ThemeManagement/ThemeManager.cs index ecafe98d..6df5f527 100644 --- a/src/Libraries/ACATCore/ThemeManagement/ThemeManager.cs +++ b/src/Libraries/ACATCore/ThemeManagement/ThemeManager.cs @@ -10,6 +10,7 @@ using System; using System.Collections.Generic; using System.IO; +using Microsoft.Extensions.Logging; namespace ACAT.Core.ThemeManagement { @@ -25,6 +26,8 @@ namespace ACAT.Core.ThemeManagement /// public class ThemeManager : IDisposable { + private static ILogger _logger; + /// /// Name of the default theme /// @@ -85,7 +88,7 @@ public Theme ActiveTheme { get { - Log.Debug("Active Theme name is " + _activeTheme.Name); + _logger?.LogDebug("Active Theme name is {ThemeName}", _activeTheme.Name); return _activeTheme; } } @@ -168,12 +171,12 @@ public bool Init() public bool SetActiveTheme(String name) { bool retVal = true; - Log.Debug("Set active Theme to " + name); + _logger?.LogDebug("Set active Theme to {ThemeName}", name); var themeDir = GetThemeDir(name); if (String.IsNullOrEmpty(themeDir)) { - Log.Error($"Could not find Theme {name}, using default."); + _logger?.LogError("Could not find Theme {ThemeName}, using default", name); themeDir = GetThemeDir(DefaultThemeName); if (String.IsNullOrEmpty(themeDir)) { @@ -185,7 +188,7 @@ public bool SetActiveTheme(String name) var themeFile = Path.Combine(themeDir, ThemeConfigFileName); - Log.Debug($"Creating Theme {name}, themeDir: {themeDir}"); + _logger?.LogDebug("Creating Theme {ThemeName}, themeDir: {ThemeDir}", name, themeDir); // create the Theme object. This parses the Theme xml file and // creates the Theme object @@ -196,11 +199,11 @@ public bool SetActiveTheme(String name) _activeTheme = theme; ActiveThemeName = name; - Log.Debug("$Created Theme successfully. active Theme is {_activeTheme.Name}."); + _logger?.LogDebug("Created Theme successfully. active Theme is {ThemeName}", _activeTheme.Name); } else { - Log.Error($"Error creating theme with name {theme}"); + _logger?.LogError("Error creating theme with name {ThemeName}", name); retVal = false; } @@ -216,7 +219,7 @@ protected virtual void Dispose(bool disposing) // Check to see if Dispose has already been called. if (!_disposed) { - Log.Verbose(); + _logger?.LogTrace("Disposing ThemeManager"); if (disposing) { @@ -243,7 +246,7 @@ private void onFileFound(String filePath) var file = new FileInfo(filePath); if (!ThemesLookupTable.ContainsKey(file.Directory.Name)) { - Log.Debug("Adding Theme: " + file.Directory.Name + ", themeDir: " + file.Directory.FullName); + _logger?.LogDebug("Adding Theme: {ThemeName}, themeDir: {ThemeDir}", file.Directory.Name, file.Directory.FullName); ThemesLookupTable.Add(file.Directory.Name, file.Directory.FullName); } } diff --git a/src/Libraries/ACATCore/UserControlManagement/UserControlConfigMap.cs b/src/Libraries/ACATCore/UserControlManagement/UserControlConfigMap.cs index 2cd13dc9..0fc1382b 100644 --- a/src/Libraries/ACATCore/UserControlManagement/UserControlConfigMap.cs +++ b/src/Libraries/ACATCore/UserControlManagement/UserControlConfigMap.cs @@ -10,6 +10,7 @@ using ACAT.Core.UserControlManagement.Interfaces; using ACAT.Core.Utility; using ACAT.Core.Utility.TypeLoader; +using Microsoft.Extensions.Logging; using System; using System.Collections; using System.Collections.Generic; @@ -28,6 +29,8 @@ namespace ACAT.Core.UserControlManagement /// public class UserControlConfigMap { + private static readonly ILogger _logger = LogManager.GetLogger(); + private const String DefaultKey = "panelconfigs"; /// @@ -70,11 +73,11 @@ public static void AddUserControlToCache(Guid guid, Type type) { if (_userControlsCache.ContainsKey(guid)) { - Log.Debug("Form Type " + type.FullName + ", guid " + guid + " is already added"); + _logger?.LogDebug("Form Type {TypeName} with guid {Guid} is already added", type.FullName, guid); return; } - Log.Debug("Adding form " + type.FullName + ", guid " + guid + " to cache"); + _logger?.LogDebug("Adding form {TypeName} with guid {Guid} to cache", type.FullName, guid); _userControlsCache.Add(guid, type); updateUserControlTypeReferences(guid, type); @@ -217,14 +220,17 @@ public static bool Load(IEnumerable extensionDirs) var usercontrolConfigMapFile = Path.Combine(FileUtils.GetPanelConfigDir(), UserControlConfigMapFileName); LoadUserControlConfigMap(usercontrolConfigMapFile); + var configsDir = FileUtils.GetPanelConfigDir(); + _logger?.LogDebug("Loading resources from {ConfigsDir}", configsDir); + // load the panels from the default culture (which is English) var resourcesDir = Path.Combine(FileUtils.GetPanelConfigDir(), "common"); - Log.Debug("DefaultResourcesDir: " + resourcesDir); + _logger?.LogDebug("Default resources directory: {ResourcesDir}", resourcesDir); load(resourcesDir, "*.xml"); // Also pick up any overrides for the current culture resourcesDir = Path.Combine(FileUtils.GetPanelConfigDir(), CultureInfo.CurrentUICulture.TwoLetterISOLanguageName); - Log.Debug("DefaultResourcesDir: " + resourcesDir); + _logger?.LogDebug("Culture-specific resources directory: {ResourcesDir}", resourcesDir); load(resourcesDir, "*.xml"); _ConfigIdMapTable.Add(DefaultKey, _loadUserControlConfigMapTable); @@ -266,29 +272,29 @@ public static void Reset() /// internal static void CleanupOrphans() { - Log.Debug("Cleaning up userControlConfigMap entries..."); + _logger?.LogDebug("Cleaning up userControlConfigMap entries"); var removeList = new List(); foreach (var mapEntry in _masterUserControlConfigMapTable.Values) { - Log.Debug("Looking up " + mapEntry.ToString()); + _logger?.LogDebug("Looking up entry: {Entry}", mapEntry.ToString()); if (_userControlsCache.ContainsKey(mapEntry.UserControlId)) { mapEntry.UserControlType = (Type)_userControlsCache[mapEntry.UserControlId]; } - Log.IsNull("mapEntry.UsercontrolType", mapEntry.UserControlType); + _logger?.LogTrace("UserControlType is null: {IsNull}", mapEntry.UserControlType == null); var configFilePath = getConfigFilePathFromLocationMap(mapEntry.ConfigFileName); if (mapEntry.UserControlType != null && !String.IsNullOrEmpty(configFilePath)) { - Log.Debug("Yes. _configFileLocationMap has configfile " + mapEntry.ConfigFileName); + _logger?.LogDebug("Found config file {ConfigFileName} in location map", mapEntry.ConfigFileName); mapEntry.ConfigFileName = configFilePath; } else { - Log.Debug("No. _configFileLocationMap does not have configfile " + mapEntry.ConfigFileName); + _logger?.LogDebug("Config file {ConfigFileName} not found in location map - marking for removal", mapEntry.ConfigFileName); removeList.Add(mapEntry); } } @@ -430,7 +436,7 @@ private static void load(String dir, string wildcard) if (Directory.Exists(dir) && !_DLLError) { var walker = new DirectoryWalker(dir, wildcard); - Log.Debug("Walking dir " + dir); + _logger?.LogDebug("Walking directory {Directory}", dir); walker.Walk(new OnFileFoundDelegate(onFileFound)); } } @@ -447,26 +453,26 @@ private static void onDllFound(String dllName) try { - Log.Debug("Found dll " + dllName); + _logger?.LogDebug("Found dll {DllName}", dllName); typeLoader.LoadFromAssembly(dllName, false); foreach (var type in typeLoader.LoadedTypes.Values) { - Log.Debug("Found type " + type.FullName); + _logger?.LogDebug("Found type {TypeName}", type.FullName); addUserControlTypeToCache(type); } } catch (BadImageFormatException ex) { - Log.Exception($"Error loading dll {dllName} Exception: {ex.Message}"); + _logger?.LogError(ex, "Error loading dll {DllName}", dllName); //_DLLError = true; } catch (Exception ex) { - Log.Exception($"Error loading dll{dllName} Exception: {ex.Message}"); + _logger?.LogError(ex, "Error loading dll {DllName}", dllName); _DLLError = true; } } @@ -523,7 +529,7 @@ private static void LoadUserControlConfigMap(String configFileName) } catch (Exception ex) { - Log.Exception(ex); + _logger?.LogError(ex, "Error loading user control config map"); } } @@ -538,12 +544,12 @@ private static void onXmlFileFound(String xmlFileName) if (_loadConfigFileLocationMap.ContainsKey(fileName)) { - Log.Debug("Updating xmlfile " + fileName + ", fullPath: " + xmlFileName); + _logger?.LogDebug("Updating xml file {FileName}, full path: {FullPath}", fileName, xmlFileName); _loadConfigFileLocationMap[fileName] = xmlFileName; } else { - Log.Debug("Adding xmlfile " + fileName + ", fullPath: " + xmlFileName); + _logger?.LogDebug("Adding xml file {FileName}, full path: {FullPath}", fileName, xmlFileName); _loadConfigFileLocationMap.Add(fileName, xmlFileName); } } diff --git a/src/Libraries/ACATCore/UserControlManagement/UserControlKeyboardCommon.cs b/src/Libraries/ACATCore/UserControlManagement/UserControlKeyboardCommon.cs index 935fac3c..eb0c4ab0 100644 --- a/src/Libraries/ACATCore/UserControlManagement/UserControlKeyboardCommon.cs +++ b/src/Libraries/ACATCore/UserControlManagement/UserControlKeyboardCommon.cs @@ -12,6 +12,7 @@ using ACAT.Core.WidgetManagement.Interfaces; using ACAT.Core.WidgetManagement.Layout; using ACAT.Core.Widgets; +using Microsoft.Extensions.Logging; using System; using System.Windows.Forms; @@ -19,9 +20,12 @@ namespace ACAT.Core.UserControlManagement { public class UserControlKeyboardCommon : UserControlCommon { - public UserControlKeyboardCommon(IUserControl userControl, UserControlConfigMapEntry mapEntry, TextController textController, IScannerPanel iScannerPanel) : + private readonly ILogger _logger; + + public UserControlKeyboardCommon(IUserControl userControl, UserControlConfigMapEntry mapEntry, TextController textController, IScannerPanel iScannerPanel, ILogger logger = null) : base(userControl, mapEntry, iScannerPanel) { + _logger = logger; TextController = textController; } @@ -68,7 +72,7 @@ widget is WordListItemWidget || SendKeys.SendWait(widget.Value + " "); Context.AppAgentMgr.TextChangedNotifications.Release(); CoreGlobals.Stopwatch1.Stop(); - Log.Debug("TimeElapsed 1: " + CoreGlobals.Stopwatch1.ElapsedMilliseconds); + _logger?.LogDebug("TimeElapsed 1: {ElapsedMs}", CoreGlobals.Stopwatch1.ElapsedMilliseconds); } else { @@ -78,7 +82,7 @@ widget is WordListItemWidget || actuateKey(button.GetWidgetAttribute(), widget.Value[0]); CoreGlobals.Stopwatch1.Stop(); - Log.Debug("TimeElapsed 2 : " + CoreGlobals.Stopwatch1.ElapsedMilliseconds); + _logger?.LogDebug("TimeElapsed 2 : {ElapsedMs}", CoreGlobals.Stopwatch1.ElapsedMilliseconds); } } @@ -87,7 +91,7 @@ widget is WordListItemWidget || private void actuateKey(WidgetAttribute widgetAttribute, char value) { - Log.Debug(value.ToString()); + _logger?.LogDebug("{Value}", value); if (!TextController.HandlePunctuation(widgetAttribute.Modifiers, value)) { if ((KeyStateTracker.IsShiftOn() || KeyStateTracker.IsCapsLockOn()) && @@ -104,7 +108,7 @@ private void actuateKey(WidgetAttribute widgetAttribute, char value) private void actuateVirtualKey(WidgetAttribute widgetAttribute, String value) { - Log.Debug("VirtualKey: " + value); + _logger?.LogDebug("VirtualKey: {Value}", value); TextController.HandleVirtualKey(widgetAttribute.Modifiers, value); } diff --git a/src/Libraries/ACATCore/UserManagement/ProfileManager.cs b/src/Libraries/ACATCore/UserManagement/ProfileManager.cs index 86f8f7db..6daf6b84 100644 --- a/src/Libraries/ACATCore/UserManagement/ProfileManager.cs +++ b/src/Libraries/ACATCore/UserManagement/ProfileManager.cs @@ -6,6 +6,7 @@ //////////////////////////////////////////////////////////////////////////// using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.IO; @@ -21,6 +22,8 @@ namespace ACAT.Core.UserManagement /// public class ProfileManager { + private static readonly ILogger _logger = LoggingConfiguration.CreateLogger(); + /// /// Name of the default profile /// @@ -112,7 +115,7 @@ public static bool CreateProfileDir(String profileName) } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex, "Failed to create profile directory: {ProfileName}", profileName); retVal = false; } diff --git a/src/Libraries/ACATCore/UserManagement/UserManager.cs b/src/Libraries/ACATCore/UserManagement/UserManager.cs index 195cea50..063c0ed2 100644 --- a/src/Libraries/ACATCore/UserManagement/UserManager.cs +++ b/src/Libraries/ACATCore/UserManagement/UserManager.cs @@ -24,7 +24,7 @@ namespace ACAT.Core.UserManagement /// public class UserManager { - private static ILogger _logger; + private static readonly ILogger _logger = LoggingConfiguration.CreateLogger(); public const String BaseUserInstallDir = "Install\\Users"; @@ -43,7 +43,6 @@ public class UserManager /// static UserManager() { - _logger = LoggerFactory.Create(builder => builder.AddConsole()).CreateLogger(); _currentUserName = DefaultUserName; } @@ -107,7 +106,7 @@ public static bool CreateUser(String userName, String sourceUserInstallPath = nu var targetDir = Path.Combine(UserManager.CurrentUserDir); - Log.Debug("Copy directory " + srcDir + "=> " + targetDir); + _logger.LogDebug("Copy directory {SourceDir} => {TargetDir}", srcDir, targetDir); return FileUtils.CopyDir(srcDir, targetDir); } @@ -140,7 +139,7 @@ public static bool CreateUserDir(String userName) { MessageBox.Show("Error creating dir. ex: " + ex); - _logger.LogError(ex, ex.Message); + _logger.LogError(ex, "Failed to create user directory: {UserName}", userName); retVal = false; } diff --git a/src/Libraries/ACATCore/Utility/FileUtils.cs b/src/Libraries/ACATCore/Utility/FileUtils.cs index e4f4ae84..d0a1206f 100644 --- a/src/Libraries/ACATCore/Utility/FileUtils.cs +++ b/src/Libraries/ACATCore/Utility/FileUtils.cs @@ -728,7 +728,7 @@ public static bool RunBatchFile(String batchFileName, params String[] argList) } catch (Exception ex) { - Log.Exception(ex); + _logger?.LogError(ex, "Exception in RunBatchFile"); retVal = false; } @@ -764,7 +764,7 @@ private static void copyDir(string srcDir, string targetDir, bool recursive = tr if (!dir.Exists) { - Log.Error("No such directory: " + srcDir); + _logger?.LogError("No such directory: {SrcDir}", srcDir); return; } @@ -794,7 +794,7 @@ private static void copyDir(string srcDir, string targetDir, bool recursive = tr } catch (Exception ex) { - Log.Exception("Error copying file " + file.FullName + " to " + targetFile + ", exception: " + ex); + _logger?.LogError(ex, "Error copying file {SourceFile} to {TargetFile}", file.FullName, targetFile); } } diff --git a/src/Libraries/ACATCore/Utility/KeyStateTracker.cs b/src/Libraries/ACATCore/Utility/KeyStateTracker.cs index 0227d58c..679e53df 100644 --- a/src/Libraries/ACATCore/Utility/KeyStateTracker.cs +++ b/src/Libraries/ACATCore/Utility/KeyStateTracker.cs @@ -110,19 +110,19 @@ public static List GetExtendedKeys() if (IsCtrlOn()) { - Log.Debug("Ctrl is on"); + _logger?.LogDebug("Ctrl is on"); retVal.Add(Keys.LControlKey); } if (IsAltOn()) { - Log.Debug("Alt is on"); + _logger?.LogDebug("Alt is on"); retVal.Add(Keys.LMenu); } if (IsShiftOn() && !IsCapsLockOn()) { - Log.Debug("Shift is on"); + _logger?.LogDebug("Shift is on"); retVal.Add(Keys.LShiftKey); } @@ -246,7 +246,7 @@ public static bool KeyDown(Keys key) { bool retVal = true; - Log.Debug(key.ToString()); + _logger?.LogDebug("Key down: {Key}", key); switch (key) { @@ -354,7 +354,7 @@ public static void KeyTriggered(Keys key) /// public static void KeyUp(Keys key) { - Log.Debug(key.ToString()); + _logger?.LogDebug("Key up: {Key}", key); switch (key) { diff --git a/src/Libraries/ACATCore/Utility/Mouse/MouseGridScanWindow.xaml.cs b/src/Libraries/ACATCore/Utility/Mouse/MouseGridScanWindow.xaml.cs index 95c5eb49..2436b267 100644 --- a/src/Libraries/ACATCore/Utility/Mouse/MouseGridScanWindow.xaml.cs +++ b/src/Libraries/ACATCore/Utility/Mouse/MouseGridScanWindow.xaml.cs @@ -6,6 +6,7 @@ //////////////////////////////////////////////////////////////////////////// using ACAT.Core.Utility.Mouse; +using Microsoft.Extensions.Logging; using System; //using System.Drawing; @@ -36,6 +37,8 @@ namespace ACAT.Core.Utility /// public partial class MouseGridScanWindow { + private readonly ILogger _logger; + /// /// Used for the state machine /// @@ -163,8 +166,9 @@ public partial class MouseGridScanWindow /// /// Initializes an instance of the class /// - public MouseGridScanWindow() + public MouseGridScanWindow(ILogger logger = null) { + _logger = logger; InitializeComponent(); init(); @@ -487,7 +491,7 @@ private void animateSetCursorPos() System.Windows.Point screen = MyCanvas.PointToScreen(new System.Windows.Point(x, y)); System.Drawing.Point winFormsPoint = new((int)screen.X, (int)screen.Y); - Log.Debug($"Setting cursor position to {winFormsPoint}"); + _logger?.LogDebug("Setting cursor position to {Position}", winFormsPoint); System.Windows.Forms.Cursor.Position = winFormsPoint; } diff --git a/src/Libraries/ACATCore/Utility/TextUtils.cs b/src/Libraries/ACATCore/Utility/TextUtils.cs index c5a9a018..6176ea89 100644 --- a/src/Libraries/ACATCore/Utility/TextUtils.cs +++ b/src/Libraries/ACATCore/Utility/TextUtils.cs @@ -19,6 +19,12 @@ namespace ACAT.Core.Utility public class TextUtils { private static ILogger _logger; + + static TextUtils() + { + _logger = LoggingConfiguration.CreateLogger(); + } + /// /// Converts a byte array into a hex string /// @@ -115,12 +121,12 @@ public static bool CheckInsertOrReplaceWord(String inputString, int caretPos, ou int index = caretPos; insertOrReplaceOffset = caretPos; - Log.Debug("index: " + index + ", inputString[index] is [" + inputString[index] + "]"); + _logger.LogDebug("index: " + index + ", inputString[index] is [" + inputString[index] + "]"); // cursor is not within a word if (Char.IsWhiteSpace(inputString[index])) { insertOrReplaceOffset = caretPos + 1; - Log.Debug("iswhiespace. return true " + insertOrReplaceOffset); + _logger.LogDebug("iswhiespace. return true " + insertOrReplaceOffset); return true; } @@ -129,7 +135,7 @@ public static bool CheckInsertOrReplaceWord(String inputString, int caretPos, ou if (IsSentenceTerminator(inputString[index])) { insertOrReplaceOffset = caretPos + 1; - Log.Debug("is sentence terminator. return true " + insertOrReplaceOffset); + _logger.LogDebug("is sentence terminator. return true " + insertOrReplaceOffset); return true; } @@ -137,19 +143,19 @@ public static bool CheckInsertOrReplaceWord(String inputString, int caretPos, ou if (IsWordElement(inputString[index])) { insertOrReplaceOffset = getWordToReplace(inputString, caretPos, out wordToReplace); - Log.Debug("iswordelement is true. return false " + insertOrReplaceOffset); + _logger.LogDebug("iswordelement is true. return false " + insertOrReplaceOffset); return false; } else { insertOrReplaceOffset = caretPos + 1; - Log.Debug("iswordelement is false. return true " + insertOrReplaceOffset); + _logger.LogDebug("iswordelement is false. return true " + insertOrReplaceOffset); return true; } } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex.ToString()); insertOrReplaceOffset = 0; wordToReplace = String.Empty; return true; @@ -211,7 +217,7 @@ public static int GetEntireParagraphAtCaret(String inputString, int caretPos, ou int startPos = index + 1; - Log.Debug("startPos = " + startPos); + _logger.LogDebug("startPos = " + startPos); index = startPos; @@ -223,21 +229,21 @@ public static int GetEntireParagraphAtCaret(String inputString, int caretPos, ou int endPos = index - 1; - Log.Debug("endPos = " + endPos); + _logger.LogDebug("endPos = " + endPos); int count = endPos - startPos + 1; - Log.Debug("count = " + count); + _logger.LogDebug("count = " + count); paragraphAtCaret = (count > 0) ? inputString.Substring(startPos, count) : String.Empty; - Log.Debug("para: [" + paragraphAtCaret + "]"); + _logger.LogDebug("para: [" + paragraphAtCaret + "]"); return startPos; } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex.ToString()); paragraphAtCaret = String.Empty; return 0; } @@ -402,7 +408,7 @@ public static int GetParagraphAtCaret(String inputString, int caretPos, out Stri } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex.ToString()); paragraphAtCaret = String.Empty; return 0; } @@ -426,7 +432,7 @@ public static int GetPrecedingCharacters(String input, int caretPos, int numberO } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex.ToString()); word = String.Empty; return 0; } @@ -473,7 +479,7 @@ public static bool GetPrecedingWhiteSpaces(String inputString, int caretPos, out offset = index; count = caretPos - offset; - Log.Debug("offset: " + offset + ", caretPos: " + caretPos + ", count: " + count); + _logger.LogDebug("offset: " + offset + ", caretPos: " + caretPos + ", count: " + count); return true; } @@ -496,21 +502,17 @@ public static int GetPrefixAndWordAtCaret(String inputString, int caretPos, out prefix = String.Empty; wordAtCaret = String.Empty; - Log.Verbose(); - - //Log.Debug("inputstring: [" + inputString + "]"); - // first get the current sentence int startPos = GetSentenceAtCaret(inputString, caretPos, out string sentenceAtCaret); if (startPos < 0) { - Log.Debug("returning " + startPos); + _logger.LogDebug("returning " + startPos); return startPos; } if (String.IsNullOrEmpty(sentenceAtCaret)) { - Log.Debug("returning " + startPos); + _logger.LogDebug("returning " + startPos); return startPos; } @@ -518,27 +520,27 @@ public static int GetPrefixAndWordAtCaret(String inputString, int caretPos, out //Log.Debug("Calling getwordatcaret. InputString: [" + inputString + "]"); int wordPos = GetWordAtCaret(inputString, caretPos, out string w); - Log.Debug("startPos: " + startPos + "wordPos: " + wordPos + " wordPos-startPos: " + (wordPos - startPos)); - Log.Debug("Getwordatcaret returned [" + w + "]"); + _logger.LogDebug("startPos: " + startPos + "wordPos: " + wordPos + " wordPos-startPos: " + (wordPos - startPos)); + _logger.LogDebug("Getwordatcaret returned [" + w + "]"); int count = wordPos - startPos; - Log.Debug("count: " + count); + _logger.LogDebug("count: " + count); if (count > 0) { - Log.Debug("Getting substring: startPos: " + startPos + ", count: " + count); + _logger.LogDebug("Getting substring: startPos: " + startPos + ", count: " + count); } prefix = (count > 0) ? inputString.Substring(startPos, count) : String.Empty; - Log.Debug("prefix: [" + prefix + "]"); + _logger.LogDebug("prefix: [" + prefix + "]"); if (!String.IsNullOrEmpty(w)) { - Log.Debug("caretPos: " + caretPos + " wordPos: " + wordPos); + _logger.LogDebug("caretPos: " + caretPos + " wordPos: " + wordPos); count = caretPos - wordPos; if (count > 0) { - Log.Debug("calling w.Substring starting at 0, count = " + count); + _logger.LogDebug("calling w.Substring starting at 0, count = " + count); } if (count >= w.Length) @@ -553,12 +555,12 @@ public static int GetPrefixAndWordAtCaret(String inputString, int caretPos, out wordAtCaret = String.Empty; } - Log.Debug("returning " + startPos); + _logger.LogDebug("returning " + startPos); return startPos; } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex.ToString()); prefix = String.Empty; wordAtCaret = String.Empty; return 0; @@ -616,13 +618,13 @@ public static int GetPreviousWord(String input, int caretPos, out String word) word = (count > 0) ? input.Substring(startPos, count) : String.Empty; - Log.Debug("word: " + word); + _logger.LogDebug("word: " + word); return startPos; } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex.ToString()); word = String.Empty; return 0; } @@ -663,14 +665,14 @@ public static bool GetPrevWordOffset(String inputString, int caretPos, out int o int index = caretPos; offset = caretPos; int endPos = caretPos; - Log.Debug("endPos: " + endPos); + _logger.LogDebug("endPos: " + endPos); while (index >= 0 && Char.IsWhiteSpace(inputString[index])) { index--; } - Log.Debug("HARRIS Before: index: " + index + " char: [" + inputString[index] + "]"); + _logger.LogDebug("HARRIS Before: index: " + index + " char: [" + inputString[index] + "]"); /* while (index >= 0 && (IsTerminator(inputString[index]) || inputString[index] == '-')) @@ -691,8 +693,8 @@ public static bool GetPrevWordOffset(String inputString, int caretPos, out int o index--; } - Log.Debug("HARRIS After index: " + index + " char: [" + inputString[index] + "]"); - Log.Debug("HARRIS Count dash: " + countDash); + _logger.LogDebug("HARRIS After index: " + index + " char: [" + inputString[index] + "]"); + _logger.LogDebug("HARRIS Count dash: " + countDash); if (countDash > 1) { @@ -737,7 +739,7 @@ public static bool GetPrevWordOffset(String inputString, int caretPos, out int o } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex.ToString()); offset = 0; count = 0; return false; @@ -779,14 +781,14 @@ public static bool GetPrevWordOffsetAutoComplete(String inputString, int caretPo int index = caretPos; offset = caretPos; int endPos = caretPos; - Log.Debug("endPos: " + endPos); + _logger.LogDebug("endPos: " + endPos); while (index >= 0 && Char.IsWhiteSpace(inputString[index])) { index--; } - Log.Debug("HARRIS Before: index: " + index + " char: [" + inputString[index] + "]"); + _logger.LogDebug("HARRIS Before: index: " + index + " char: [" + inputString[index] + "]"); /* while (index >= 0 && (IsTerminator(inputString[index]) || inputString[index] == '-')) @@ -807,8 +809,8 @@ public static bool GetPrevWordOffsetAutoComplete(String inputString, int caretPo index--; } - Log.Debug("HARRIS After index: " + index + " char: [" + inputString[index] + "]"); - Log.Debug("HARRIS Count dash: " + countDash); + _logger.LogDebug("HARRIS After index: " + index + " char: [" + inputString[index] + "]"); + _logger.LogDebug("HARRIS Count dash: " + countDash); if (countDash > 1) { @@ -854,7 +856,7 @@ public static bool GetPrevWordOffsetAutoComplete(String inputString, int caretPo } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex.ToString()); offset = 0; count = 0; return false; @@ -876,10 +878,9 @@ public static int GetSentenceAtCaret(String inputString, int caretPos, out Strin { sentenceAtCaret = String.Empty; - Log.Verbose(); if (String.IsNullOrEmpty(inputString.Trim())) { - Log.Debug("returning -1"); + _logger.LogDebug("returning -1"); return -1; } @@ -915,12 +916,12 @@ public static int GetSentenceAtCaret(String inputString, int caretPos, out Strin int count = endPos - startPos + 1; sentenceAtCaret = (count > 0) ? inputString.Substring(startPos, count) : String.Empty; - Log.Debug("returning " + startPos); + _logger.LogDebug("returning " + startPos); return startPos; } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex.ToString()); sentenceAtCaret = String.Empty; return 0; } @@ -1037,13 +1038,13 @@ public static int GetWordAtCaret(String inputString, int caretPos, out String wo { int startPos = caretPos; - //Log.Debug("inputString: [" + inputString + "], caretPos: " + caretPos); - Log.Debug("caretPos: " + caretPos); + //_logger.LogDebug("inputString: [" + inputString + "], caretPos: " + caretPos); + _logger.LogDebug("caretPos: " + caretPos); wordAtCaret = String.Empty; if (String.IsNullOrEmpty(inputString)) { - Log.Debug("inputstring is empty. returning"); + _logger.LogDebug("inputstring is empty. returning"); return -1; } @@ -1109,21 +1110,21 @@ public static int GetWordAtCaret(String inputString, int caretPos, out String wo if (endPos >= startPos) { - Log.Debug("wordAtCaret: Getting substring from startPos: " + startPos + ", length: " + (endPos - startPos)); + _logger.LogDebug("wordAtCaret: Getting substring from startPos: " + startPos + ", length: " + (endPos - startPos)); wordAtCaret = inputString.Substring(startPos, endPos - startPos).Trim(); - Log.Debug("wordAtCaret: [" + wordAtCaret + "]"); + _logger.LogDebug("wordAtCaret: [" + wordAtCaret + "]"); } else { wordAtCaret = String.Empty; } - Log.Debug("returning " + startPos + ", wordatCaret: " + wordAtCaret); + _logger.LogDebug("returning " + startPos + ", wordatCaret: " + wordAtCaret); return startPos; } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex.ToString()); wordAtCaret = String.Empty; return 0; } @@ -1288,12 +1289,12 @@ private static int getWordToReplace(String inputString, int caretPos, out String { int startPos = caretPos; - Log.Debug("Enter startPos: " + startPos); + _logger.LogDebug("Enter startPos: " + startPos); while (startPos >= 0) { if (!IsWordElement(inputString[startPos])) { - Log.Debug("Breaking. No word element at : " + startPos); + _logger.LogDebug("Breaking. No word element at : " + startPos); break; } @@ -1302,7 +1303,7 @@ private static int getWordToReplace(String inputString, int caretPos, out String startPos++; - Log.Debug("1 startPos: " + startPos); + _logger.LogDebug("1 startPos: " + startPos); if (startPos < 0) { @@ -1311,36 +1312,36 @@ private static int getWordToReplace(String inputString, int caretPos, out String int endPos = caretPos; - Log.Debug("endPos: " + endPos); + _logger.LogDebug("endPos: " + endPos); while (endPos < inputString.Length) { if (!IsWordElement(inputString[endPos])) { - Log.Debug("Breaking. No word element at : " + endPos); + _logger.LogDebug("Breaking. No word element at : " + endPos); break; } endPos++; } - Log.Debug("After loop endPos : " + endPos); + _logger.LogDebug("After loop endPos : " + endPos); if (endPos > inputString.Length) { endPos = inputString.Length; } - Log.Debug("getWordAt: startpos, endpos = " + startPos + ", " + endPos); + _logger.LogDebug("getWordAt: startpos, endpos = " + startPos + ", " + endPos); int count = endPos - startPos; - Log.Debug("count: " + count); - Log.Debug("Calling substring: " + startPos + ", " + (endPos - startPos)); + _logger.LogDebug("count: " + count); + _logger.LogDebug("Calling substring: " + startPos + ", " + (endPos - startPos)); wordAtCaret = (count > 0) ? inputString.Substring(startPos, endPos - startPos) : String.Empty; - Log.Debug("returning startPos : " + startPos); + _logger.LogDebug("returning startPos : " + startPos); return startPos; } diff --git a/src/Libraries/ACATCore/Utility/TimerQueue.cs b/src/Libraries/ACATCore/Utility/TimerQueue.cs index a7cce537..afbae23e 100644 --- a/src/Libraries/ACATCore/Utility/TimerQueue.cs +++ b/src/Libraries/ACATCore/Utility/TimerQueue.cs @@ -5,6 +5,7 @@ // //////////////////////////////////////////////////////////////////////////// +using Microsoft.Extensions.Logging; using System; using System.Runtime.InteropServices; @@ -18,6 +19,8 @@ namespace ACAT.Core.Utility /// public class TimerQueue : IDisposable { + private static ILogger _logger; + /// /// Windows constant /// @@ -133,7 +136,7 @@ public bool Start(IntPtr param) if (_isRunning == true) { // already running - Log.Debug("Timer is already running. returning"); + _logger?.LogDebug("Timer is already running. returning"); return true; } @@ -153,7 +156,7 @@ public bool Start(IntPtr param) else { getLastError = Marshal.GetLastWin32Error(); - Log.Debug("Error while starting timer. getLastError=" + getLastError); + _logger?.LogDebug("Error while starting timer. getLastError={GetLastError}", getLastError); } return retVal; @@ -166,7 +169,7 @@ public bool Stop() { if (_isRunning == false) { - Log.Debug("Not running. returning"); + _logger?.LogDebug("Not running. returning"); return true; } diff --git a/src/Libraries/ACATCore/Utility/VerifyDigitalSignature.cs b/src/Libraries/ACATCore/Utility/VerifyDigitalSignature.cs index 6b856930..84aff455 100644 --- a/src/Libraries/ACATCore/Utility/VerifyDigitalSignature.cs +++ b/src/Libraries/ACATCore/Utility/VerifyDigitalSignature.cs @@ -9,11 +9,13 @@ using System.ComponentModel; using System.Runtime.InteropServices; using System.Security.Cryptography.Pkcs; +using Microsoft.Extensions.Logging; namespace ACAT.Core.Utility { public class VerifyDigitalSignature { + private static ILogger _logger; #if ENABLE_DIGITAL_VERIFICATION private static string[] _dllFiles = { @@ -77,7 +79,7 @@ public static void Verify(String fileName) int formatType = 0; const int ErrCertExpired = -2146762495; - Log.Debug("Verify digital signature for " + fileName); + _logger?.LogDebug("Verify digital signature for {FileName}", fileName); if (!CryptoInterop.CryptQueryObject( CryptoInterop.CERT_QUERY_OBJECT_FILE, @@ -93,14 +95,14 @@ public static void Verify(String fileName) ref context )) { - Log.Debug((new Win32Exception(Marshal.GetLastWin32Error())).Message); + _logger?.LogDebug("Crypto query failed: {Message}", (new Win32Exception(Marshal.GetLastWin32Error())).Message); throw new Win32Exception(Marshal.GetLastWin32Error()); } int data = 0; if (!CryptoInterop.CryptMsgGetParam(msgHandle, CryptoInterop.CMSG_ENCODED_MESSAGE, 0, null, ref data)) { - Log.Debug((new Win32Exception(Marshal.GetLastWin32Error())).Message); + _logger?.LogDebug("CryptMsgGetParam failed: {Message}", (new Win32Exception(Marshal.GetLastWin32Error())).Message); throw new Win32Exception(Marshal.GetLastWin32Error()); } @@ -111,13 +113,13 @@ ref context try { signedCms.CheckSignature(false); - Log.Debug("Signature check passed"); + _logger?.LogDebug("Signature check passed"); } catch (Exception e) { if (e.HResult != ErrCertExpired) { - Log.Exception(e); + _logger?.LogError(e, "Signature check failed"); throw (e); } } diff --git a/src/Libraries/ACATCore/Utility/WebSearch.cs b/src/Libraries/ACATCore/Utility/WebSearch.cs index 846dada9..f10e19b6 100644 --- a/src/Libraries/ACATCore/Utility/WebSearch.cs +++ b/src/Libraries/ACATCore/Utility/WebSearch.cs @@ -5,6 +5,7 @@ // //////////////////////////////////////////////////////////////////////////// +using Microsoft.Extensions.Logging; using System; using System.Diagnostics; using System.Security.Permissions; @@ -20,6 +21,7 @@ namespace ACAT.Core.Utility /// public class WebSearch { + private static readonly ILogger _logger = LogManager.GetLogger(); /// /// URL to do a google search with "I'm feeling lucky" /// @@ -131,7 +133,7 @@ private Process launchURL(String url) } catch (Exception ex) { - Log.Exception("Could not launch URL using preferred browser. Trying Internet Explorer. " + ex); + _logger.LogError(ex, "Could not launch URL using preferred browser. Trying Internet Explorer"); try { @@ -139,7 +141,7 @@ private Process launchURL(String url) } catch (Exception ex1) { - Log.Exception("Could not launch URL using IE. " + ex1); + _logger.LogError(ex1, "Could not launch URL using IE"); } } diff --git a/src/Libraries/ACATCore/WidgetManagement/Layout/LayoutAttribute.cs b/src/Libraries/ACATCore/WidgetManagement/Layout/LayoutAttribute.cs index c3257c4b..12765fb8 100644 --- a/src/Libraries/ACATCore/WidgetManagement/Layout/LayoutAttribute.cs +++ b/src/Libraries/ACATCore/WidgetManagement/Layout/LayoutAttribute.cs @@ -277,7 +277,7 @@ private Widget createWidget(XmlNode node) } catch (Exception ex) { - Log.Exception(ex); + _logger?.LogError(ex, "Failed to instantiate widget: {WidgetName}, class: {WidgetClass}", widgetName, widgetClass); widget = null; } diff --git a/src/Libraries/ACATCore/WidgetManagement/Widget.cs b/src/Libraries/ACATCore/WidgetManagement/Widget.cs index c3ec6df9..a24f7387 100644 --- a/src/Libraries/ACATCore/WidgetManagement/Widget.cs +++ b/src/Libraries/ACATCore/WidgetManagement/Widget.cs @@ -851,7 +851,7 @@ public virtual bool CanAddForAnimation() } } } - //Log.Debug("WidgetName: " + Name + ", retVal : " + retVal); + _logger?.LogTrace("CanAddForAnimation: WidgetName={Name}, result={Result}", Name, retVal); return retVal; } diff --git a/src/Libraries/ACATCore/WidgetManagement/WidgetManager.cs b/src/Libraries/ACATCore/WidgetManagement/WidgetManager.cs index 73966f9c..1f1305ea 100644 --- a/src/Libraries/ACATCore/WidgetManagement/WidgetManager.cs +++ b/src/Libraries/ACATCore/WidgetManagement/WidgetManager.cs @@ -32,6 +32,7 @@ namespace ACAT.Core.WidgetManagement public class WidgetManager : IDisposable { private readonly ILogger _logger; + private static readonly ILogger _staticLogger = LoggerFactory.Create(builder => builder.AddConsole()).CreateLogger(); /// /// Holds the types of all classes in the executing assembly that @@ -130,7 +131,7 @@ public static Type GetWidgetType(String widgetTypeName) } catch (Exception ex) { - _logger.LogError(ex, "Could not find widgettype {WidgetTypeName}", widgetTypeName); + _staticLogger.LogError(ex, "Could not find widgettype {WidgetTypeName}", widgetTypeName); } return retVal; @@ -265,7 +266,7 @@ private static bool loadTypesFromAssembly(Assembly assembly) } catch (Exception ex) { - _logger.LogError(ex, ex.Message); + _staticLogger.LogError(ex, ex.Message); retVal = false; } @@ -304,7 +305,7 @@ private static void loadWidgetTypeCollection(IEnumerable extensionDirs) } else { - Log.Error("Extension directory does not exist: " + extensionDir); + _staticLogger.LogError("Extension directory does not exist: {ExtensionDir}", extensionDir); } } @@ -338,19 +339,19 @@ private static void onDllFound(String dllName) { try { - Log.Debug("Found dll " + dllName); + _staticLogger.LogDebug("Found dll {DllName}", dllName); loadTypesFromAssembly(Assembly.LoadFile(dllName)); } catch (Exception ex) { - Log.Exception("Could get types from assembly " + dllName + ". Exception : " + ex); + _staticLogger.LogError(ex, "Could get types from assembly {DllName}", dllName); if (ex is ReflectionTypeLoadException) { var typeLoadException = (ReflectionTypeLoadException)ex; var exceptions = typeLoadException.LoaderExceptions; foreach (var e in exceptions) { - Log.Debug("Loader exception: " + e); + _staticLogger.LogDebug("Loader exception: {Exception}", e); } } } diff --git a/src/Libraries/ACATExtension/Common.cs b/src/Libraries/ACATExtension/Common.cs index 65e7779a..8de8b670 100644 --- a/src/Libraries/ACATExtension/Common.cs +++ b/src/Libraries/ACATExtension/Common.cs @@ -9,6 +9,7 @@ using ACAT.Core.PanelManagement.Utils; using ACAT.Core.UserControlManagement; using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Reflection; @@ -20,6 +21,8 @@ namespace ACAT.Extension /// public static class Common { + private static readonly ILogger _logger = LoggingConfiguration.CreateLogger("ACAT.Extension.Common"); + /// /// System-wide ACAT preference settings /// @@ -33,7 +36,7 @@ public static void Init() AppPreferences.DefaultScanTimingsConfigurePanelName = "ScanTimeAdjustScanner"; AppPreferences.DefaultTryoutPanelName = "DefaultTryoutScanner"; var assembly = Assembly.GetExecutingAssembly(); - Log.Debug("Assembly name: " + assembly.FullName); + _logger.LogDebug("Assembly name: {AssemblyName}", assembly.FullName); } /// diff --git a/src/Libraries/ACATExtension/UI/AlphabetScannerCommon.cs b/src/Libraries/ACATExtension/UI/AlphabetScannerCommon.cs index e591ebf6..4cc2d83a 100644 --- a/src/Libraries/ACATExtension/UI/AlphabetScannerCommon.cs +++ b/src/Libraries/ACATExtension/UI/AlphabetScannerCommon.cs @@ -377,7 +377,7 @@ public virtual void OnWidgetActuated(WidgetActuatedEventArgs e, ref bool handled CoreGlobals.Stopwatch1.Stop(); - Log.Debug("TimeElapsed 3 : " + CoreGlobals.Stopwatch1.ElapsedMilliseconds); + _logger.LogDebug("TimeElapsed 3 : {ElapsedMs}", CoreGlobals.Stopwatch1.ElapsedMilliseconds); handled = true; } @@ -397,7 +397,7 @@ public virtual void OnWidgetActuated(WidgetActuatedEventArgs e, ref bool handled CoreGlobals.Stopwatch1.Stop(); - Log.Debug("TimeElapsed 3 : " + CoreGlobals.Stopwatch1.ElapsedMilliseconds); + _logger.LogDebug("TimeElapsed 3 : {ElapsedMs}", CoreGlobals.Stopwatch1.ElapsedMilliseconds); handled = true; } @@ -599,7 +599,7 @@ private void refreshWordPredictionsAndSetCurrentWord() if (!tryRefreshWordPredictionsAndSetCurrentWord()) { - Log.Debug("AgentContextException. Retrying refreshing word prediction"); + _logger.LogDebug("AgentContextException. Retrying refreshing word prediction"); tryRefreshWordPredictionsAndSetCurrentWord(); } diff --git a/src/Libraries/ACATExtension/UI/DialogUtils.cs b/src/Libraries/ACATExtension/UI/DialogUtils.cs index b5415bcb..b77b62d0 100644 --- a/src/Libraries/ACATExtension/UI/DialogUtils.cs +++ b/src/Libraries/ACATExtension/UI/DialogUtils.cs @@ -197,7 +197,7 @@ public static async void ShowAppLauncher() } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex, "Error launching app"); } } diff --git a/src/Libraries/ACATExtension/UI/UserControlWordPredictionCommon.cs b/src/Libraries/ACATExtension/UI/UserControlWordPredictionCommon.cs index 753c8f12..57088249 100644 --- a/src/Libraries/ACATExtension/UI/UserControlWordPredictionCommon.cs +++ b/src/Libraries/ACATExtension/UI/UserControlWordPredictionCommon.cs @@ -226,7 +226,7 @@ public virtual void OnWidgetActuated(WidgetActuatedEventArgs e, ref bool handled CoreGlobals.Stopwatch1.Stop(); - Log.Debug("TimeElapsed 3 : " + CoreGlobals.Stopwatch1.ElapsedMilliseconds); + _logger?.LogDebug("TimeElapsed 3 : {ElapsedMs}ms", CoreGlobals.Stopwatch1.ElapsedMilliseconds); handled = true; } @@ -246,7 +246,7 @@ public virtual void OnWidgetActuated(WidgetActuatedEventArgs e, ref bool handled CoreGlobals.Stopwatch1.Stop(); - Log.Debug("TimeElapsed 3 : " + CoreGlobals.Stopwatch1.ElapsedMilliseconds); + _logger?.LogDebug("TimeElapsed 3 : {ElapsedMs}ms", CoreGlobals.Stopwatch1.ElapsedMilliseconds); handled = true; } @@ -266,7 +266,7 @@ public virtual void OnWidgetActuated(WidgetActuatedEventArgs e, ref bool handled CoreGlobals.Stopwatch1.Stop(); - Log.Debug("TimeElapsed 3 : " + CoreGlobals.Stopwatch1.ElapsedMilliseconds); + _logger?.LogDebug("TimeElapsed 3 : {ElapsedMs}ms", CoreGlobals.Stopwatch1.ElapsedMilliseconds); handled = true; } @@ -526,16 +526,16 @@ private void processWordPredictionResponse(WordPredictionResponse response) } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger?.LogError(ex, "Exception processing word prediction"); } predictedWordList = predictedWordsList1; predictedLettersList = predictedLettersList1; } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger?.LogError(ex, "Exception processing word prediction"); } - Log.Debug("predictedWordList count: " + predictedWordList.Count()); + _logger?.LogDebug("predictedWordList count: {Count}", predictedWordList.Count()); // check if the current word is a possessive word. If not, we need to create // a possessive version of the word and add it as the last word @@ -554,7 +554,12 @@ private void processWordPredictionResponse(WordPredictionResponse response) } catch (InvalidAgentContextException ex) { - _logger.LogError(ex, ex.Message); + _logger?.LogError(ex, ex.Message); + } + } + } + + if (string.IsNullOrEmpty(wordAtCaret) || (charAtCaret == '\0' || charAtCaret == 0x0D || charAtCaret == 0x0A || TextUtils.IsPunctuationOrWhiteSpace(charAtCaret) || TextUtils.IsTerminatorOrWhiteSpace(charAtCaret)))