_logger;
+
private readonly String _htmlText = "\r\n\r\n \r\n \r\n \r\n \r\n " +
"\r\n" +
@@ -142,8 +145,9 @@ public enum BCISignalCheckMode
///
///
///
- public UserControlBCISignalCheck()
+ public UserControlBCISignalCheck(ILogger logger)
{
+ _logger = logger;
InitializeComponent();
buttonNext_userControlBCISignalCheck.Enabled = true;
@@ -434,7 +438,7 @@ public void ProcessDataSignalCheck(double[,] data, double[,] filteredData)
}
catch (Exception ex)
{
- Log.Exception(ex);
+ _logger.LogError(ex, "Exception in ProcessDataSignalCheck");
}
}
@@ -493,7 +497,7 @@ private void updateRailingTestResult(int chIdx, int railingResultPercentage, boo
}
catch (Exception ex)
{
- Log.Exception(ex);
+ _logger.LogError(ex, "Exception in setElectrodeCapMapColors");
}
}
@@ -512,7 +516,7 @@ public void changeSignalCheckMode(BCISignalCheckMode mode)
}
catch (Exception ex)
{
- Log.Exception(ex);
+ _logger.LogError(ex, "Exception in tabControlElectrodeQuality_SelectedIndexChanged");
}
}
@@ -563,7 +567,7 @@ private void updateSignalChart(int channelIndex, double[] samples, bool scale_pl
}
catch (Exception ex)
{
- Log.Exception(ex);
+ _logger.LogError(ex, "Exception in addChartToScreen");
}
}
@@ -621,7 +625,7 @@ private static bool AppendDataToBuffer2(double[,] data, double[,] inBuffer, int
}
catch (Exception e)
{
- Log.Exception(e.Message);
+ _logger.LogError(e, "Exception in removeColumnsFromChan: {Message}", e.Message);
}
return result;
}
@@ -770,7 +774,7 @@ public void handle125Scaling()
}
catch (Exception ex)
{
- Log.Exception(ex.Message);
+ _logger.LogError(e, "Exception in ProcessDataSignalCheck: {Message}", e.Message);
}
}
}
diff --git a/src/Extensions/BCI/Actuators/gTec_SensorUI/UserControlErrorBluetoothDisconnected.cs b/src/Extensions/BCI/Actuators/gTec_SensorUI/UserControlErrorBluetoothDisconnected.cs
index b15b5fa4..ab0f015a 100644
--- a/src/Extensions/BCI/Actuators/gTec_SensorUI/UserControlErrorBluetoothDisconnected.cs
+++ b/src/Extensions/BCI/Actuators/gTec_SensorUI/UserControlErrorBluetoothDisconnected.cs
@@ -13,6 +13,7 @@
using ACAT.Core.Utility;
using ACAT.Extensions.BCI.Actuators.EEG.EEGDataAcquisition;
using ACAT.Extensions.BCI.Actuators.EEG.EEGSettings;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -27,6 +28,8 @@ namespace ACAT.Extensions.BCI.Actuators.gTecSensorUI
///
public partial class UserControlErrorBluetoothDisconnected : UserControl
{
+ private readonly ILogger _logger;
+
// Timer to update the lists of paired / unpaired devices
private Timer _updateTimer;
@@ -36,8 +39,9 @@ public partial class UserControlErrorBluetoothDisconnected : UserControl
///
/// Constructor for user control which handles Unicorn bluetooth device connection
///
- public UserControlErrorBluetoothDisconnected()
+ public UserControlErrorBluetoothDisconnected(ILogger logger)
{
+ _logger = logger;
InitializeComponent();
// Disable Next button until something in list is selected
@@ -70,7 +74,7 @@ private void ListViewDevices_SelectedIndexChanged(object sender, EventArgs e)
{
BCIActuatorSettings.Settings.GTecDeviceName = selectedDevice;
BCIActuatorSettings.Save();
- Log.Debug("Saved BCIGtecActuatorSettings.Settings.GTecDeviceName to ACAT settings: " + BCIActuatorSettings.Settings.GTecDeviceName);
+ _logger.LogDebug("Saved BCIGtecActuatorSettings.Settings.GTecDeviceName to ACAT settings: " + BCIActuatorSettings.Settings.GTecDeviceName);
}
}
@@ -94,7 +98,7 @@ public void startStopUpdateBluetoothListTimer(bool start)
}
catch (Exception e)
{
- Log.Exception("startStopUpdateBluetoothListTimer | Exception: " + e.ToString());
+ _logger.LogError(e, "startStopUpdateBluetoothListTimer | Exception when starting: {Exception}", e.ToString());
}
}
else
@@ -112,7 +116,7 @@ public void startStopUpdateBluetoothListTimer(bool start)
}
catch (Exception e)
{
- Log.Exception("startStopUpdateBluetoothListTimer | Exception: " + e.ToString());
+ _logger.LogError(e, "startStopUpdateBluetoothListTimer | Exception: {Exception}", e.ToString());
}
}
}
@@ -143,7 +147,7 @@ private void UpdateTimer_Tick(object sender, EventArgs e)
/// Any extra params sent with bluetooth event request
public void bluetoothResultHandler(DAQ_gTecBCI.BluetoothEvent bluetoothEvent, Dictionary eventParams)
{
- Log.Debug("UserControlErrorBluetoothDisconnected | bluetoothResultHandler | bluetoothEvent: " + bluetoothEvent.ToString());
+ _logger.LogDebug("UserControlErrorBluetoothDisconnected | bluetoothResultHandler | bluetoothEvent: " + bluetoothEvent.ToString());
if (!this.IsHandleCreated || this.IsDisposed) { return; }
diff --git a/src/Extensions/BCI/Actuators/gTec_SensorUI/Utils.cs b/src/Extensions/BCI/Actuators/gTec_SensorUI/Utils.cs
index 14381b0d..db86bac5 100644
--- a/src/Extensions/BCI/Actuators/gTec_SensorUI/Utils.cs
+++ b/src/Extensions/BCI/Actuators/gTec_SensorUI/Utils.cs
@@ -1,5 +1,6 @@
using ACAT.Core.Utility;
using ACATResources;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Windows.Forms;
@@ -8,11 +9,13 @@ namespace ACAT.Extensions.BCI.Actuators.gTecSensorUI
{
internal class Utils
{
+ private static readonly ILogger _logger = LoggerFactory.GetLogger();
+
internal static void HandleHelpNavigaion(WebBrowserNavigatingEventArgs e)
{
var str = e.Url.ToString();
- Log.Debug("Url is [" + str + "]");
+ _logger.LogDebug("Url is [" + str + "]");
if (str.ToLower().Contains("blank"))
{
diff --git a/src/Extensions/BCI/Actuators/gTec_SensorUI/gTecDeviceTester.cs b/src/Extensions/BCI/Actuators/gTec_SensorUI/gTecDeviceTester.cs
index b90937da..75d56ebd 100644
--- a/src/Extensions/BCI/Actuators/gTec_SensorUI/gTecDeviceTester.cs
+++ b/src/Extensions/BCI/Actuators/gTec_SensorUI/gTecDeviceTester.cs
@@ -16,6 +16,7 @@
using ACAT.Extensions.BCI.Actuators.EEG.EEGDataAcquisition;
using ACAT.Extensions.BCI.Actuators.EEG.EEGSettings;
using ACATResources;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Threading;
@@ -29,6 +30,7 @@ namespace ACAT.Extensions.BCI.Actuators.gTecSensorUI
///
public class GTecDeviceTester
{
+ private readonly ILogger _logger;
public DAQ_gTecBCI gTecBCI = null;
///
@@ -123,8 +125,9 @@ public static bool GtecDeviceAvailable
/// Tests BCI devices - connections to the hw and data quality
/// Displays errors accordingly - After an error, starts at the beginning of the process (testing device connections)
///
- public GTecDeviceTester()
+ public GTecDeviceTester(ILogger logger)
{
+ _logger = logger;
// Do not call init function here
// Call init function after creating object of this class and linking any necessary event handler (ex: EvtBCIDeviceTestingCompleted)
@@ -136,14 +139,14 @@ public GTecDeviceTester()
///
public void initialize()
{
- Log.Debug("gTecDeviceTester | initialize");
+ _logger.LogDebug("gTecDeviceTester | initialize");
gTecBCI = (DAQ_gTecBCI)DAQFactory.CreateDAQ(DAQDeviceType.GTecBCI);
// Close main form if for some reason it's opened at this point
if (_mainForm != null && _mainForm.IsDisposed == false)
{
- Log.Debug("gTecDeviceTester | _mainForm != null && _mainForm.IsDisposed == false");
+ _logger.LogDebug("gTecDeviceTester | _mainForm != null && _mainForm.IsDisposed == false");
_mainForm.Close();
_mainForm.Dispose();
}
@@ -155,7 +158,7 @@ public void initialize()
}
catch (Exception ex)
{
- Log.Exception(ex);
+ _logger.LogError(ex, "Exception getting Testing_UseSensor setting");
}
// If flag set to exit onboarding early, then send event EvtBCIDeviceTestingCompleted and do not continue this function
@@ -217,7 +220,7 @@ public void initialize()
/// Any extra params sent with bluetooth event request
public void bluetoothResultHandler(DAQ_gTecBCI.BluetoothEvent bluetoothEvent, Dictionary eventParams)
{
- Log.Debug("gTecDeviceTester | bluetoothResultHandler | bluetoothEvent: " + bluetoothEvent.ToString() + " | _currentOnboardingUserState: " + _currentOnboardingUserState.ToString());
+ _logger.LogDebug("gTecDeviceTester | bluetoothResultHandler | bluetoothEvent: " + bluetoothEvent.ToString() + " | _currentOnboardingUserState: " + _currentOnboardingUserState.ToString());
switch (bluetoothEvent)
{
@@ -232,7 +235,7 @@ public void bluetoothResultHandler(DAQ_gTecBCI.BluetoothEvent bluetoothEvent, Di
}
catch (Exception ex)
{
- Log.Exception("gTecDeviceTester | bluetoothResultHandler | Exception: " + ex.Message);
+ _logger.LogError(ex, "gTecDeviceTester | bluetoothResultHandler | Exception: {Message}", ex.Message);
}
// We were seeing if device could be connected to from the start of the testing process
@@ -277,7 +280,7 @@ public void bluetoothResultHandler(DAQ_gTecBCI.BluetoothEvent bluetoothEvent, Di
//
public async Task startBCIDeviceTesting(int initialDelaySec = 0)
{
- Log.Debug("gTecDeviceTester | startBCIDeviceTesting | initialDelaySec: " + initialDelaySec.ToString());
+ _logger.LogDebug("gTecDeviceTester | startBCIDeviceTesting | initialDelaySec: " + initialDelaySec.ToString());
// Extra time to wait before actually starting testing process (a lot of testing functions can return immediately, so this is for user experience)
if (initialDelaySec > 0)
@@ -336,7 +339,7 @@ private void updateOnboardingStatus(OnboardingUserState state, Dictionary
private void buttonNextHandler(String buttonNextName)
{
- Log.Debug("gTecDeviceTester | buttonNextHandler | buttonNextName: " + buttonNextName);
+ _logger.LogDebug("gTecDeviceTester | buttonNextHandler | buttonNextName: " + buttonNextName);
switch (buttonNextName)
{
// Next button clicked from UserControlBluetoothDisconnected
@@ -443,14 +446,14 @@ private void buttonNextHandler(String buttonNextName)
bool userPassedLastSignalQualityCheck = BCIActuatorSettings.Settings.SignalQuality_PassedLastOverallQualityCheck;
if (userPassedLastSignalQualityCheck)
{
- Log.Debug("User passed most recent signal quality check");
+ _logger.LogDebug("User passed most recent signal quality check");
exitBCIOnboarding = true;
}
// Check if testing parameter set to ignore signal quality check result
if (BCIActuatorSettings.Settings.Testing_IgnoreSignalTestResultDuringOnboarding)
{
- Log.Debug("BCIGtecActuatorSettings.Testing_IgnoreSignalTestResultDuringOnboarding = true");
+ _logger.LogDebug("BCIGtecActuatorSettings.Testing_IgnoreSignalTestResultDuringOnboarding = true");
exitBCIOnboarding = true;
if (!userPassedLastSignalQualityCheck)
@@ -625,7 +628,7 @@ public void Exit(bool lostConnection)
///
private void _mainForm_EvtFormClosed(object sender, FormClosedEventArgs e)
{
- Log.Debug("gTecDeviceTester | _mainForm_EvtFormClosed");
+ _logger.LogDebug("gTecDeviceTester | _mainForm_EvtFormClosed");
}
///
@@ -668,7 +671,7 @@ private void _mainForm_EvtButtonExitClicked_DEBUG(object sender)
}
catch (Exception e)
{
- Log.Exception("_mainForm_EvtButtonExitClicked_DEBUG exception: " + e.ToString());
+ _logger.LogError(e, "_mainForm_EvtButtonExitClicked_DEBUG exception: {Exception}", e.ToString());
}
}
}
diff --git a/src/Extensions/BCI/Actuators/openBCI_SensorUI/OpenBCIDeviceTester.cs b/src/Extensions/BCI/Actuators/openBCI_SensorUI/OpenBCIDeviceTester.cs
index 9eeb089a..539e8e63 100644
--- a/src/Extensions/BCI/Actuators/openBCI_SensorUI/OpenBCIDeviceTester.cs
+++ b/src/Extensions/BCI/Actuators/openBCI_SensorUI/OpenBCIDeviceTester.cs
@@ -18,6 +18,7 @@
using ACAT.Extensions.BCI.Actuators.EEG.EEGSettings;
using ACAT.Extensions.BCI.Actuators.EEG.EEGUtils;
using ACATResources;
+using Microsoft.Extensions.Logging;
using System;
using System.Diagnostics;
using System.Drawing;
@@ -32,6 +33,8 @@ namespace ACAT.Extensions.BCI.Actuators.openBCISensorUI
///
public class OpenBCIDeviceTester
{
+ private readonly ILogger _logger;
+
///
/// Variables representing all the different states in testing process (state machine)
///
diff --git a/src/Extensions/BCI/Actuators/openBCI_SensorUI/UserControlBCIErrorOpticalSensor.cs b/src/Extensions/BCI/Actuators/openBCI_SensorUI/UserControlBCIErrorOpticalSensor.cs
index 79ce9ced..08dc6c4f 100644
--- a/src/Extensions/BCI/Actuators/openBCI_SensorUI/UserControlBCIErrorOpticalSensor.cs
+++ b/src/Extensions/BCI/Actuators/openBCI_SensorUI/UserControlBCIErrorOpticalSensor.cs
@@ -13,6 +13,7 @@
using ACAT.Core.Utility;
using ACAT.Extensions.BCI.Actuators.EEG.EEGSettings;
using ACATResources;
+using Microsoft.Extensions.Logging;
using System;
using System.IO;
using System.Linq;
@@ -26,6 +27,7 @@ namespace ACAT.Extensions.BCI.Actuators.openBCISensorUI
///
public partial class UserControlBCIErrorOpticalSensor : UserControl
{
+ private readonly ILogger _logger;
///
/// Unique ID for this step
///
@@ -58,8 +60,9 @@ public partial class UserControlBCIErrorOpticalSensor : UserControl
///
/// User Control Form for the output signals from sensor
///
- public UserControlBCIErrorOpticalSensor(String stepId)
+ public UserControlBCIErrorOpticalSensor(String stepId, ILogger logger = null)
{
+ _logger = logger ?? LoggerFactory.GetLogger();
InitializeComponent();
_stepId = stepId;
@@ -147,7 +150,7 @@ public void updateOpticalSensorDataPlot(double[] newData)
}
catch (Exception e)
{
- Log.Exception(e);
+ _logger.LogError(e, e.ToString());
}
}
diff --git a/src/Extensions/BCI/Actuators/openBCI_SensorUI/Utils.cs b/src/Extensions/BCI/Actuators/openBCI_SensorUI/Utils.cs
index 37fd00d3..9ab1872a 100644
--- a/src/Extensions/BCI/Actuators/openBCI_SensorUI/Utils.cs
+++ b/src/Extensions/BCI/Actuators/openBCI_SensorUI/Utils.cs
@@ -1,5 +1,6 @@
using ACAT.Core.Utility;
using ACATResources;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Windows.Forms;
@@ -8,11 +9,13 @@ namespace ACAT.Extensions.BCI.Actuators.openBCISensorUI
{
internal class Utils
{
+ private static readonly ILogger _logger = LoggerFactory.GetLogger();
+
internal static void HandleHelpNavigaion(WebBrowserNavigatingEventArgs e)
{
var str = e.Url.ToString();
- Log.Debug("Url is [" + str + "]");
+ _logger.LogDebug("Url is [" + str + "]");
if (str.ToLower().Contains("blank"))
{
diff --git a/src/Extensions/BCI/Common/AnimationSharp/AnimationSharpManagerV2.cs b/src/Extensions/BCI/Common/AnimationSharp/AnimationSharpManagerV2.cs
index fddba958..d703bedc 100644
--- a/src/Extensions/BCI/Common/AnimationSharp/AnimationSharpManagerV2.cs
+++ b/src/Extensions/BCI/Common/AnimationSharp/AnimationSharpManagerV2.cs
@@ -1,4 +1,4 @@
-////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////
//
// Copyright 2013-2019; 2023 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
@@ -19,6 +19,7 @@
using ACAT.Extensions.BCI.Common.BCIControl;
using ACATResources;
+using Microsoft.Extensions.Logging;
using SharpDX.Direct2D1;
using SharpDX.Direct3D11;
using SharpDX.DirectWrite;
@@ -40,6 +41,7 @@ namespace ACAT.Extensions.BCI.Common.AnimationSharp
///
public class AnimationSharpManagerV2
{
+ private readonly ILogger _logger;
///
/// Current active Keyboard Layout
///
@@ -575,7 +577,7 @@ public void CancelCalibration()
try
{ AbortTimers(); }
catch (Exception ex)
- { Log.Debug("BCI LOG | Error in BCI CancelCalibration(): " + ex.Message); }
+ { _logger.LogDebug("BCI LOG | Error in BCI CancelCalibration(): " + ex.Message); }
CloseSequencesLog();
_sessionMode = BCIModes.TYPING;
ChangeColorButtons(_flashingSequenceBoxList[0].ToList(), false, true, 0);
@@ -656,7 +658,7 @@ public void CreateSequencesLog(string path, string name = null)
}
catch (Exception ex)
{
- Log.Debug("BCI LOG | Exception in CreateSequencesLog() " + ex.Message);
+ _logger.LogDebug("BCI LOG | Exception in CreateSequencesLog() " + ex.Message);
}
}
@@ -683,7 +685,7 @@ public void DrawMainLayout()
}
catch (Exception es)
{
- Log.Exception("BCI LOG | Exception sharpDX in DrawMainLayout() " + es.Message);
+ _logger.LogError("BCI LOG | Exception sharpDX in DrawMainLayout() " + es.Message);
}
}
@@ -720,7 +722,7 @@ public void Init(Form form)
}
catch (Exception ex)
{
- Log.Exception("BCI LOG | Exception occurred during initialization: " + ex.Message);
+ _logger.LogError("BCI LOG | Exception occurred during initialization: " + ex.Message);
return;
}
@@ -784,7 +786,7 @@ public void OnFormClosing()
catch (Exception es)
{
AbortTimers();
- Log.Debug("BCI LOG | Exception occurred during closing SharpDX: " + es.Message);
+ _logger.LogDebug("BCI LOG | Exception occurred during closing SharpDX: " + es.Message);
}
DisposeObjects();
}
@@ -847,7 +849,7 @@ public void ResumeAfterPause()
if (SuspendAnimations)
{
_requestProbabilities = true;
- try { AbortTimers(); } catch (Exception ex) { Log.Debug("BCI LOG | Exception ResumeAfterPause: " + ex.Message); }
+ try { AbortTimers(); } catch (Exception ex) { _logger.LogDebug("BCI LOG | Exception ResumeAfterPause: " + ex.Message); }
Reset();
}
}
@@ -906,7 +908,7 @@ public void SetDataObjectsSharpDX(Dictionary, string> boxesData, L
}
catch (Exception)
{
- //Log.Exception("BCI LOG | Exception _rectProbBarsBox: " + es.Message);
+ //_logger.LogError("BCI LOG | Exception _rectProbBarsBox: " + es.Message);
}
indexBox += 1;
}
@@ -1002,14 +1004,14 @@ private async Task ActuateWidgetFromID(int id)
}
catch (Exception ex)
{
- Log.Exception("BCI LOG | Error actuating Button: " + ex.Message);
+ _logger.LogError("BCI LOG | Error actuating Button: " + ex.Message);
}
await Task.Delay(1);
}
private void ActuatorRequestEndCalibration()
{
- Log.Debug("BCI LOG | EndCalibration | Section " + _ScanningSection);
+ _logger.LogDebug("BCI LOG | EndCalibration | Section " + _ScanningSection);
CloseSequencesLog();
RequestToUpdateTextBox(AnimationManagerUtils.StatusMessageAnalyzingCalibrationData + " . .");
var bciCalibrationEnd = new BCICalibrationEnd();
@@ -1034,7 +1036,7 @@ private void ActuatorRequestEndCalibration()
}
catch (Exception es)
{
- Log.Exception("BCI LOG | Exception occurred during request to Actuator in ENDCAL: " + es.Message);
+ _logger.LogError("BCI LOG | Exception occurred during request to Actuator in ENDCAL: " + es.Message);
}
var strCalEnd = bciCalibrationEnd;
_actuator?.IoctlRequest((int)OpCodes.CalibrationEnd, strCalEnd);
@@ -1087,7 +1089,7 @@ private void ActuatorRequestEndRepetitionCalibration()
}
catch (Exception es)
{
- Log.Exception("BCI LOG | Exception occurred during request to Actuator in CAl: " + es.Message);
+ _logger.LogError("BCI LOG | Exception occurred during request to Actuator in CAl: " + es.Message);
}
var strCalRepEnd = bciCalibrationInput;
_actuator?.IoctlRequest((int)OpCodes.CalibrationEndRepetition, strCalRepEnd);
@@ -1117,7 +1119,7 @@ private void ActuatorRequestEndRepetitionTyping()
}
catch (Exception es)
{
- Log.Exception("BCI LOG | Exception occurred during request to Actuator in TYPE 3: " + es.Message);
+ _logger.LogError("BCI LOG | Exception occurred during request to Actuator in TYPE 3: " + es.Message);
}
}
else
@@ -1140,14 +1142,14 @@ private void ActuatorRequestEndRepetitionTyping()
}
catch (Exception es)
{
- Log.Exception("BCI LOG | Exception occurred during request to Actuator in TYPE 1: " + es.Message);
+ _logger.LogError("BCI LOG | Exception occurred during request to Actuator in TYPE 1: " + es.Message);
}
}
bciTypingRepetitionEnd.ScanningSection = _ScanningSection;
}
catch (Exception es)
{
- Log.Exception("BCI LOG | Exception occurred during request to Actuator in TYPE: " + es.Message);
+ _logger.LogError("BCI LOG | Exception occurred during request to Actuator in TYPE: " + es.Message);
}
var strTypRepEnd = bciTypingRepetitionEnd;
_actuator?.IoctlRequest((int)OpCodes.TypingEndRepetition, strTypRepEnd);
@@ -1160,7 +1162,7 @@ private void ActuatorRequestMarker(string data)
private void ActuatorRequestTriggerTestFinish()
{
- Log.Debug("BCI LOG | TriggerTestFinish ");
+ _logger.LogDebug("BCI LOG | TriggerTestFinish ");
_triggerTestActive = false;
Thread.Sleep(200);
_actuator?.IoctlRequest((int)OpCodes.TriggerTestStop, string.Empty);
@@ -1216,7 +1218,7 @@ private void ActuatorRequestValueProbs()
}
catch (Exception ex)
{
- Log.Exception("BCI LOG | Exception in ActuatorRequestValueProbs: " + ex.Message);
+ _logger.LogError("BCI LOG | Exception in ActuatorRequestValueProbs: " + ex.Message);
}
}
@@ -1230,7 +1232,7 @@ private void ActuatorResponseCalibrationEndRepetitionResult(object response)
}
catch (Exception ex)
{
- Log.Exception("BCI LOG | Exception in ActuatorResponseCalibrationEndRepetitionResult: " + ex.Message);
+ _logger.LogError("BCI LOG | Exception in ActuatorResponseCalibrationEndRepetitionResult: " + ex.Message);
SensorErrorState = new BCIError() { ErrorCode = BCIErrorCodes.OpticalSensorError_UnknownException, ErrorMessage = StringResources.SensorError };
AnimationManagerUtils.StatusSignal = SignalStatus.SIGNAL_KO;
}
@@ -1238,7 +1240,7 @@ private void ActuatorResponseCalibrationEndRepetitionResult(object response)
private void ActuatorResponseCalibrationResult(object response)
{
- Log.Debug("BCI LOG | CalibrationResult | AUC " + _AUC + " | Section " + _ScanningSection);
+ _logger.LogDebug("BCI LOG | CalibrationResult | AUC " + _AUC + " | Section " + _ScanningSection);
var bciCalibrationResult = response as BCICalibrationResult;
_AUC = bciCalibrationResult.AUC;
if (bciCalibrationResult.CalibrationSuccessful)//Flags to let know the timer thread once is at the final process to do either one or the other event trigger
@@ -1252,7 +1254,7 @@ private void ActuatorResponseSendParameters(object response)
{
try
{
- Log.Debug("BCI LOG | SendParameters | Section " + _ScanningSection);
+ _logger.LogDebug("BCI LOG | SendParameters | Section " + _ScanningSection);
var bciParameters = response as BCIParameters;
_DelayToGetReady = bciParameters.Scanning_DelayToGetReady;
_MinimumProgressBarsValue = (bciParameters.MinProbablityToDisplayBarOnTyping);
@@ -1290,7 +1292,7 @@ private void ActuatorResponseSendParameters(object response)
}
catch (Exception ex)
{
- Log.Exception("BCI LOG | ActuatorResponseSendParameters | Exception | " + ex.Message);
+ _logger.LogError("BCI LOG | ActuatorResponseSendParameters | Exception | " + ex.Message);
_CalibrationTargetCount = 60;
_CalibrationIterationsPerTarget = 2;
}
@@ -1298,12 +1300,12 @@ private void ActuatorResponseSendParameters(object response)
private void ActuatorResponseStartSessionResult(object response)
{
- Log.Debug("BCI LOG | StartSessionResult | Section " + _ScanningSection);
+ _logger.LogDebug("BCI LOG | StartSessionResult | Section " + _ScanningSection);
var bciSessionResult = response as BCIStartSessionResult;
SensorErrorState = bciSessionResult.Error;
CreateSequencesLog(bciSessionResult.SessionDirectory);
- Log.Debug("BCI LOG | Scanning Log created in: | Path " + bciSessionResult.SessionDirectory);
- Log.Debug("BCI LOG | bciSessionResult.Error | Status " + bciSessionResult.Error);
+ _logger.LogDebug("BCI LOG | Scanning Log created in: | Path " + bciSessionResult.SessionDirectory);
+ _logger.LogDebug("BCI LOG | bciSessionResult.Error | Status " + bciSessionResult.Error);
//_readStartSessionResult flag is for Eyes/Clsoed Calibration form that also has the start session request with this we avoid the event handler to run scanning when Eyes Form is active and here has the event subscribed active
if (_readStartSessionResult && !_triggerTestActive)
{
@@ -1323,7 +1325,7 @@ private void ActuatorResponseTriggerTestResult(object response)
{
var bciTriggerTestResult = response as BCITriggerTestResult;
CloseSequencesLog();
- Log.Debug("BCI LOG | TriggerTestResult | DutyCycleAvg " + bciTriggerTestResult.DutyCycleAvg.ToString());
+ _logger.LogDebug("BCI LOG | TriggerTestResult | DutyCycleAvg " + bciTriggerTestResult.DutyCycleAvg.ToString());
//Trigger event to call a UI message box from a higher level
_mainForm.Invoke(new MethodInvoker(delegate
{
@@ -1495,7 +1497,7 @@ private void ChangeColorButtons(List buttonIDs, bool highlightOn, bool useE
}
catch (Exception es)
{
- Log.Exception("BCI LOG | Exception sharpDX ChangeColorButtons: " + es.Message);
+ _logger.LogError("BCI LOG | Exception sharpDX ChangeColorButtons: " + es.Message);
}
}
@@ -1535,7 +1537,7 @@ private void ChangeColorButtonsSequence(List buttonIDs, SolidColorBrush col
}
catch (Exception ex)
{
- Log.Exception("BCI LOG | Exception sharpDX ChangeColorButtonsSequence: " + ex.Message);
+ _logger.LogError("BCI LOG | Exception sharpDX ChangeColorButtonsSequence: " + ex.Message);
}
}
@@ -1637,7 +1639,7 @@ private void DrawFocalPointsFor(BCIModes bCIModes)
}
catch (Exception ex)
{
- Log.Exception("BCI LOG | Exception sharpDX DrawFocalPointsFor: " + ex.Message);
+ _logger.LogError("BCI LOG | Exception sharpDX DrawFocalPointsFor: " + ex.Message);
}
}
@@ -1698,7 +1700,7 @@ private void DrawMatrix()
}
catch (Exception ex)
{
- Log.Exception("BCI LOG | Exception sharpDX in DrawMatrix: " + ex.Message);
+ _logger.LogError("BCI LOG | Exception sharpDX in DrawMatrix: " + ex.Message);
}
}
@@ -1737,7 +1739,7 @@ private void EnsureTimersAreStoped()
}
catch (Exception ex)
{
- Log.Exception("BCI LOG | Exception in EnsureTimersAreStoped: " + ex.Message);
+ _logger.LogError("BCI LOG | Exception in EnsureTimersAreStoped: " + ex.Message);
}
}
@@ -1803,7 +1805,7 @@ private ButtonsData FindButtomFromId(int id)
}
catch (Exception es)
{
- Log.Exception("BCI LOG | Exception occurred findButtomFromId: " + es.Message);
+ _logger.LogError("BCI LOG | Exception occurred findButtomFromId: " + es.Message);
return new ButtonsData();
}
}
@@ -1832,7 +1834,7 @@ private int FindIndexFromID(int id)
}
catch (Exception es)
{
- Log.Exception("BCI LOG | Exception findIndexFromID: " + es.Message);
+ _logger.LogError("BCI LOG | Exception findIndexFromID: " + es.Message);
}
}
return 0;
@@ -1948,7 +1950,7 @@ private bool PlayBoxSequences()
}
catch (Exception ex)
{
- Log.Exception("BCI LOG | Error in isBoxEmpty: " + ex.Message);
+ _logger.LogError("BCI LOG | Error in isBoxEmpty: " + ex.Message);
return true;
}
}
@@ -2134,7 +2136,7 @@ private void Reset(bool delayAfterLayoutChange = false)
}
catch (Exception er)
{
- Log.Exception("BCI LOG | Exception setDataObjectsSharpDX: " + er.Message);
+ _logger.LogError("BCI LOG | Exception setDataObjectsSharpDX: " + er.Message);
}
_UpdateButtonsStrings = true;
Thread.Sleep(250);
@@ -2174,7 +2176,7 @@ private async Task ResetWaitingDelay()
}
catch (Exception ex)
{
- Log.Exception("BCI LOG | Exception in ResetWaitingDelay: " + ex.Message);
+ _logger.LogError("BCI LOG | Exception in ResetWaitingDelay: " + ex.Message);
}
await Task.Delay(200);
DrawMainLayout();
@@ -2281,7 +2283,7 @@ private void SetValueProbabilityBars()
}
catch (Exception es)
{
- Log.Exception("BCI LOG | Exception occurred during Drawing progress bars probs: " + es.Message);
+ _logger.LogError("BCI LOG | Exception occurred during Drawing progress bars probs: " + es.Message);
}
}
if (_showProbabilityIndicator)
@@ -2296,7 +2298,7 @@ private void SetValueProbabilityBars()
}
catch (Exception es)
{
- Log.Exception("BCI LOG | Exception occurred during Drawing progress bars: " + es.Message);
+ _logger.LogError("BCI LOG | Exception occurred during Drawing progress bars: " + es.Message);
}
}
@@ -2670,9 +2672,9 @@ private void TrialTimer_Tick(object sender, MicroTimerEventArgs e)
_trialTimer.Stop();
if (SensorErrorState.ErrorCode != BCIErrorCodes.Status_Ok)//if and error was returned then it wont continue with animations
{
- Log.Debug("BCI LOG | Error entered in loop | ErrorCode: " + SensorErrorState.ErrorCode);
+ _logger.LogDebug("BCI LOG | Error entered in loop | ErrorCode: " + SensorErrorState.ErrorCode);
SoundManager.playSound(SoundManager.SoundType.CaregiverAttention);
- Log.Debug("BCI LOG | SoundManager.playSound ");
+ _logger.LogDebug("BCI LOG | SoundManager.playSound ");
/*while (true)
{
Thread.Sleep(500);
@@ -2699,7 +2701,7 @@ private void TrialTimer_Tick(object sender, MicroTimerEventArgs e)
}
catch (Exception ex)
{
- Log.Exception("BCI LOG | Error in _endCalibration: " + ex.Message);
+ _logger.LogError("BCI LOG | Error in _endCalibration: " + ex.Message);
}
}
if (_repeatCalibration)
@@ -2717,7 +2719,7 @@ private void TrialTimer_Tick(object sender, MicroTimerEventArgs e)
}
catch (Exception ex)
{
- Log.Exception("BCI LOG | Exception TrialTimer_Tick: " + ex.Message);
+ _logger.LogError("BCI LOG | Exception TrialTimer_Tick: " + ex.Message);
}
}
@@ -2769,7 +2771,7 @@ private void TriggerTestTimer_Tick(object sender, MicroTimerEventArgs e)
}
catch (Exception ex)
{
- Log.Exception("BCI LOG | Exception TriggerTestTimer_Tick: " + ex.Message);
+ _logger.LogError("BCI LOG | Exception TriggerTestTimer_Tick: " + ex.Message);
}
}
@@ -2843,7 +2845,7 @@ private async Task UpdateStringsFromButtons()
}
catch (Exception es)
{
- Log.Exception("BCI LOG | Exception occurred during updating strings from buttons: " + es.Message);
+ _logger.LogError("BCI LOG | Exception occurred during updating strings from buttons: " + es.Message);
await Task.Delay(2000);
}
}
@@ -2857,8 +2859,8 @@ private void ValidateSensorErrorState(BCIError bCIError)
if (bCIError.ErrorCode != BCIErrorCodes.Status_Ok)
{
RequestToUpdateTextBox(bCIError.ErrorMessage + " ( Error Code: " + (int)bCIError.ErrorCode + " )");
- Log.Debug("BCI LOG | ErrorCode received " + (int)bCIError.ErrorCode);
- Log.Debug("BCI LOG | ErrorMessage received " + bCIError.ErrorMessage);
+ _logger.LogDebug("BCI LOG | ErrorCode received " + (int)bCIError.ErrorCode);
+ _logger.LogDebug("BCI LOG | ErrorMessage received " + bCIError.ErrorMessage);
}
}
diff --git a/src/Extensions/BCI/Common/AnimationSharp/Utility/AnimationManagerUtils.cs b/src/Extensions/BCI/Common/AnimationSharp/Utility/AnimationManagerUtils.cs
index 63250dbb..139c08b4 100644
--- a/src/Extensions/BCI/Common/AnimationSharp/Utility/AnimationManagerUtils.cs
+++ b/src/Extensions/BCI/Common/AnimationSharp/Utility/AnimationManagerUtils.cs
@@ -1,4 +1,4 @@
-////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////
//
// Copyright 2013-2019; 2023 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
@@ -11,6 +11,7 @@
using ACAT.Core.WidgetManagement;
using ACAT.Core.WidgetManagement.Interfaces;
using ACAT.Extensions.BCI.Common.BCIControl;
+using Microsoft.Extensions.Logging;
using SharpDX.Direct2D1;
using System;
using System.Collections.Generic;
@@ -26,6 +27,7 @@ namespace ACAT.Extensions.BCI.Common.AnimationSharp.Utility
///
public class AnimationManagerUtils
{
+ private static readonly ILogger _logger = LoggerFactory.GetLogger();
///
/// String messages for BCI
///
@@ -103,7 +105,7 @@ public static List[] ExtractButtonText(List controls, string co
}
catch (Exception ex)
{
- Log.Exception(ex);
+ _logger.LogError(ex, ex.ToString());
}
configNodes = null;
return btnStringsAll;
@@ -157,7 +159,7 @@ public static List[] GetBoxWidgets(List widgets, string configFi
}
catch (Exception ex)
{
- Log.Exception(ex);
+ _logger.LogError(ex, ex.ToString());
}
configNodes = null;
return widgetsBox;
@@ -185,7 +187,7 @@ public static List[] GetBoxWidgetsList(KeyValuePair, strin
}
catch (Exception ex)
{
- Log.Exception("Error in GetBoxWidgetsList: " + ex.Message);
+ _logger.LogError("Error in GetBoxWidgetsList: " + ex.Message);
return new List[totalAmountOfBoxes];
}
return widgets;
@@ -213,7 +215,7 @@ public static List[] GetButtonDataList(KeyValuePair,
}
catch (Exception ex)
{
- Log.Exception("Error in GetButtonDataList: " + ex.Message);
+ _logger.LogError("Error in GetButtonDataList: " + ex.Message);
return new List[totalAmountOfBoxes];
}
return buttonDataList;
@@ -287,7 +289,7 @@ public static List[] GetButtonsOffsetList(KeyValuePair, strin
}
catch (Exception ex)
{
- Log.Exception("Error in GetButtonsOffsetList: " + ex.Message);
+ _logger.LogError("Error in GetButtonsOffsetList: " + ex.Message);
return new List[totalAmountOfBoxes];
}
return offsetStrings;
@@ -319,7 +321,7 @@ public static List[] GetButtonsStringsList(Dictionary, str
}
catch (Exception ex)
{
- Log.Exception("Error in GetButtonsStringsList: " + ex.Message);
+ _logger.LogError("Error in GetButtonsStringsList: " + ex.Message);
return new List[totalAmountOfBoxes];
}
return buttonsStringsList;
@@ -406,7 +408,7 @@ public static List[] GetControlsBtns(KeyValuePair[totalAmountOfBoxes];
flashingSequenceList = new List[totalAmountOfBoxes];
return new List[totalAmountOfBoxes];
@@ -449,7 +451,7 @@ public static List[] GetControlsButtons(List cont
}
catch (Exception ex)
{
- Log.Exception(ex);
+ _logger.LogError(ex, ex.ToString());
}
configNodes = null;
return ctrlBtnsAll;
@@ -486,7 +488,7 @@ public static List[] GetFlashingSequenceIDBoxList(List[] widgetsDat
}
catch (Exception ex)
{
- Log.Exception("Error in GetFlashingSequenceIDBoxList: " + ex.Message);
+ _logger.LogError("Error in GetFlashingSequenceIDBoxList: " + ex.Message);
return new List[totalAmountOfBoxes];
}
return flashingSequenceIDBoxList;
@@ -524,7 +526,7 @@ public static Dictionary GetLettersProbs(List
}
catch (Exception es)
{
- Log.Exception("Exception geting values probs " + es);
+ _logger.LogError("Exception geting values probs " + es);
}
return nextProbs;
}
@@ -579,7 +581,7 @@ public static Dictionary GetLettersProbs(List controls, boo
}
catch (Exception ex)
{
- Log.Exception("Exception in getLettersProbs: " + ex.Message.ToString());
+ _logger.LogError("Exception in getLettersProbs: " + ex.Message.ToString());
return _ = new Dictionary();
}
return nextProbs;
@@ -642,7 +644,7 @@ public static List[] GetMatrixButtons(List controls, Rende
}
catch (Exception ex)
{
- Log.Exception(ex);
+ _logger.LogError(ex, ex.ToString());
}
configNodes = null;
return matrixButtonList;
@@ -685,7 +687,7 @@ public static List[] GetOffset(List widgets, string configFilePath,
}
catch (Exception ex)
{
- Log.Exception(ex);
+ _logger.LogError(ex, ex.ToString());
}
configNodes = null;
return offsets;
@@ -770,7 +772,7 @@ public static List[] GetSequences(List controls, string configFi
}
catch (Exception ex)
{
- Log.Exception(ex);
+ _logger.LogError(ex, ex.ToString());
}
configNodes = null;
return flashingSeqAll;
@@ -838,7 +840,7 @@ public static Dictionary GetWordsProbs(List c
}
catch (Exception es)
{
- Log.Exception("Exception geting values probs " + es);
+ _logger.LogError("Exception geting values probs " + es);
}
return nextProbs;
}
diff --git a/src/Extensions/BCI/Common/AnimationSharp/Utility/BCIUtils.cs b/src/Extensions/BCI/Common/AnimationSharp/Utility/BCIUtils.cs
index 7f2bbddf..8d3379ca 100644
--- a/src/Extensions/BCI/Common/AnimationSharp/Utility/BCIUtils.cs
+++ b/src/Extensions/BCI/Common/AnimationSharp/Utility/BCIUtils.cs
@@ -7,6 +7,7 @@
using ACAT.Core.Utility;
using ACAT.Extensions.BCI.Common.BCIControl;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -16,6 +17,14 @@ namespace ACAT.Extensions.BCI.Common.AnimationSharp.Utility
{
public class BCIUtils
{
+ private readonly ILogger _logger;
+ private readonly ILogger _logger;
+
+ public BCIUtils(ILogger logger = null)
+ {
+ _logger = logger ?? LoggerFactory.GetLogger();
+ }
+
///
/// Array of ID to be used as targe for calibration
///
@@ -94,7 +103,7 @@ public string GetEntryLogStr(BCIModes bCIModes, BCIScanSections bCIScanSections,
}
catch (Exception es)
{
- Log.Exception("Error no highlight log saved: " + es);
+ _logger.LogError(es, "Error no highlight log saved: " + es);
}
return sb.ToString();
}
diff --git a/src/Extensions/BCI/Common/AnimationSharp/Utility/CachedLogBCI.cs b/src/Extensions/BCI/Common/AnimationSharp/Utility/CachedLogBCI.cs
index 68d9a381..56bd830a 100644
--- a/src/Extensions/BCI/Common/AnimationSharp/Utility/CachedLogBCI.cs
+++ b/src/Extensions/BCI/Common/AnimationSharp/Utility/CachedLogBCI.cs
@@ -6,6 +6,7 @@
////////////////////////////////////////////////////////////////////////////
using ACAT.Core.Utility;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.IO;
@@ -18,6 +19,7 @@ namespace ACAT.Extensions.BCI.Common.AnimationSharp.Utility
///
public class CachedLogBCI
{
+ private readonly ILogger _logger;
///
/// Full path to the log file
///
@@ -35,8 +37,9 @@ public class CachedLogBCI
///
private readonly string LogFileName;
- public CachedLogBCI(string baseFileName, string baseDirPath = null)
+ public CachedLogBCI(string baseFileName, string baseDirPath = null, ILogger logger = null)
{
+ _logger = logger ?? LoggerFactory.GetLogger();
if (!string.IsNullOrEmpty(baseFileName))
{
LogFileName = baseFileName + ".csv";
@@ -98,7 +101,7 @@ private void Save(string logFilePath, StreamWriter streamWriter)
}
catch (Exception ex)
{
- Log.Exception(ex.ToString());
+ _logger.LogError(ex, ex.ToString());
}
finally
{
diff --git a/src/Extensions/BCI/Common/AnimationSharp/Utility/SharpDXUtils.cs b/src/Extensions/BCI/Common/AnimationSharp/Utility/SharpDXUtils.cs
index 12ec26be..7ed4ff2f 100644
--- a/src/Extensions/BCI/Common/AnimationSharp/Utility/SharpDXUtils.cs
+++ b/src/Extensions/BCI/Common/AnimationSharp/Utility/SharpDXUtils.cs
@@ -1,4 +1,4 @@
-////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////
//
// Copyright 2013-2019; 2023 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
@@ -9,6 +9,7 @@
using ACAT.Core.WidgetManagement;
using ACAT.Core.WidgetManagement.Interfaces;
using ACAT.Extensions.BCI.Common.BCIControl;
+using Microsoft.Extensions.Logging;
using SharpDX.Direct2D1;
using SharpDX.DirectWrite;
using SharpDX.Mathematics.Interop;
@@ -23,6 +24,7 @@ namespace ACAT.Extensions.BCI.Common.AnimationSharp.Utility
{
public class SharpDXUtils
{
+ private static readonly ILogger _logger = LoggerFactory.GetLogger();
///
/// Get the border color from the Theme xml file
///
@@ -100,7 +102,7 @@ public static List[] GetListButtonTextFormat(KeyValuePair[totalAmountOfBoxes];
}
return buttonTextFormatList;
@@ -144,7 +146,7 @@ public static List[] GetRecButtons(List controls, string
}
catch (Exception ex)
{
- Log.Exception(ex);
+ _logger.LogError(ex, ex.ToString());
}
configNodes = null;
return rectBtns;
@@ -188,7 +190,7 @@ public static Dictionary[] GetRecProbabilityBars(List GetRecProbabilityBarsBox(List[] GetRecRoundButtons(List controls
}
catch (Exception ex)
{
- Log.Exception(ex);
+ _logger.LogError(ex, ex.ToString());
}
configNodes = null;
return rectBtns;
@@ -312,7 +314,7 @@ public static List[] GetRectanglesButtonsList(KeyValuePair[totalAmountOfBoxes];
}
return rectanglesButtonsList;
@@ -340,7 +342,7 @@ public static List[] GetRectanglesButtonsRoundList(KeyValuePai
}
catch (Exception ex)
{
- Log.Exception("Error in GetRectanglesButtonsRoundList: " + ex.Message);
+ _logger.LogError("Error in GetRectanglesButtonsRoundList: " + ex.Message);
return new List[totalAmountOfBoxes];
}
return rectanglesButtonsRoundList;
@@ -386,7 +388,7 @@ public static RawRectangleF GetRectanglesCRG(Dictionary, string> b
}
catch (Exception ex)
{
- Log.Exception("Error in GetRectanglesCRG: " + ex.Message);
+ _logger.LogError("Error in GetRectanglesCRG: " + ex.Message);
return rectangleExtraButtonCRG;
}
return rectangleExtraButtonCRG;
@@ -418,7 +420,7 @@ public static RawRectangleF GetRectanglesTriggerBox(Dictionary, st
}
catch (Exception ex)
{
- Log.Exception("Error in GetRectanglesTriggerBox: " + ex.Message);
+ _logger.LogError("Error in GetRectanglesTriggerBox: " + ex.Message);
return rectangleExtraButton;
}
return rectangleExtraButton;
@@ -488,7 +490,7 @@ public static List[] GetTextFormat(List widgets, string conf
}
catch (Exception ex)
{
- Log.Exception(ex);
+ _logger.LogError(ex, ex.ToString());
}
configNodes = null;
return textFormats;
@@ -511,7 +513,7 @@ public static TextFormat GetTextFormatCRG(List widgets, SharpDX.DirectWr
}
catch (Exception ex)
{
- Log.Exception(ex);
+ _logger.LogError(ex, ex.ToString());
textFormatCRG = GetDefaultButtonTextFormat(directWriteFactory, TextAlignment.Center);
}
return textFormatCRG;
diff --git a/src/Extensions/BCI/Common/BCIInterfaceUtilities/CalibrationEyesSettingsForm.cs b/src/Extensions/BCI/Common/BCIInterfaceUtilities/CalibrationEyesSettingsForm.cs
index 80c4fe79..fd8b6127 100644
--- a/src/Extensions/BCI/Common/BCIInterfaceUtilities/CalibrationEyesSettingsForm.cs
+++ b/src/Extensions/BCI/Common/BCIInterfaceUtilities/CalibrationEyesSettingsForm.cs
@@ -10,6 +10,7 @@
using ACAT.Core.Utility;
using ACAT.Extensions.BCI.Common.BCIControl;
using ACATResources;
+using Microsoft.Extensions.Logging;
using System;
using System.Text.RegularExpressions;
using System.Threading;
@@ -32,6 +33,11 @@ public partial class CalibrationEyesSettingsForm : Form
public ResultParams ResultParameters = new();
+ ///
+ /// Logger instance
+ ///
+ private readonly ILogger _logger;
+
///
/// Main object of the actuator
///
@@ -59,8 +65,9 @@ public partial class CalibrationEyesSettingsForm : Form
#endregion Properties
- public CalibrationEyesSettingsForm()
+ public CalibrationEyesSettingsForm(ILogger logger)
{
+ _logger = logger ?? throw new ArgumentNullException(nameof(logger));
InitializeComponent();
this.WindowState = FormWindowState.Maximized;
Screen primaryScreen = Screen.PrimaryScreen;
@@ -181,7 +188,7 @@ private void textBoxInterval_TextChanged(object sender, EventArgs e)
}
catch (Exception ex)
{
- Log.Exception(ex.ToString());
+ _logger.LogError(ex, "Error parsing interval value");
_TempInterval = 5000;
textBoxInterval.Text = _TempInterval.ToString();
}
@@ -204,7 +211,7 @@ private void textBoxReps_TextChanged(object sender, EventArgs e)
}
catch (Exception ex)
{
- Log.Exception(ex.ToString());
+ _logger.LogError(ex, "Error parsing repetitions value");
_TempMaxRepetitions = 10;
textBoxReps.Text = _TempMaxRepetitions.ToString();
}
@@ -250,7 +257,7 @@ private void OnFormClosing()
}
catch (Exception ex)
{
- Log.Exception("Error in EyesSettingsForm: " + ex.Message);
+ _logger.LogError(ex, "Error in EyesSettingsForm");
}
if (_bciActuator != null)
{
@@ -295,7 +302,7 @@ private bool TextChangedInput(TextBox textBox)
}
catch (Exception ex)
{
- Log.Exception(ex.ToString());
+ _logger.LogError(ex, "Error in TextChangedInput");
}
return inputReplace;
}
diff --git a/src/Extensions/BCI/Common/BCIInterfaceUtilities/ConfirmBoxCalibrationModes.cs b/src/Extensions/BCI/Common/BCIInterfaceUtilities/ConfirmBoxCalibrationModes.cs
index cea5f029..6f913e18 100644
--- a/src/Extensions/BCI/Common/BCIInterfaceUtilities/ConfirmBoxCalibrationModes.cs
+++ b/src/Extensions/BCI/Common/BCIInterfaceUtilities/ConfirmBoxCalibrationModes.cs
@@ -11,6 +11,7 @@
using ACAT.Core.WidgetManagement;
using ACAT.Extensions.BCI.Common.BCIControl;
using ACATResources;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Drawing;
@@ -28,6 +29,11 @@ namespace ACAT.Extensions.BCI.Common.BCIInterfaceUtilities
public partial class ConfirmBoxCalibrationModes : Form
{
#region Properties
+ ///
+ /// Logger instance
+ ///
+ private readonly ILogger _logger;
+
///
/// Main object of the actuator
///
@@ -73,8 +79,9 @@ public partial class ConfirmBoxCalibrationModes : Form
///
/// Confirm Box with multiple results
///
- public ConfirmBoxCalibrationModes()
+ public ConfirmBoxCalibrationModes(ILogger logger)
{
+ _logger = logger ?? throw new ArgumentNullException(nameof(logger));
InitializeComponent();
Load += ConfirmBoxCalibrationModes_Load;
@@ -140,7 +147,7 @@ private void ButtonBeginACAT_Click(object sender, EventArgs e)
private void ButtonCalibrate_Click(object sender, EventArgs e)
{
- Log.Debug("BCI LOG | Mode Selected: " + _scanSectionsSelected);
+ _logger.LogDebug("BCI LOG | Mode Selected: {ScanSection}", _scanSectionsSelected);
_ = new BCISimpleParameters();
try
{
@@ -149,7 +156,7 @@ private void ButtonCalibrate_Click(object sender, EventArgs e)
switch (scannerRoundedButtonControl.Name)
{
case var _ when scannerRoundedButtonControl.Name.Contains("Box"):
- Log.Debug("BCI LOG | Calibrate Button Selected: " + BCIScanSections.Box);
+ _logger.LogDebug("BCI LOG | Calibrate Button Selected: {Section}", BCIScanSections.Box);
if (_scanSectionsSelected == BCIScanSections.Box)
parameters = GetCalibrationParameters();
else
@@ -158,7 +165,7 @@ private void ButtonCalibrate_Click(object sender, EventArgs e)
break;
case var _ when scannerRoundedButtonControl.Name.Contains("Sentence"):
- Log.Debug("BCI LOG | Calibrate Button Selected " + BCIScanSections.Sentence);
+ _logger.LogDebug("BCI LOG | Calibrate Button Selected {Section}", BCIScanSections.Sentence);
if (_scanSectionsSelected == BCIScanSections.Sentence)
parameters = GetCalibrationParameters();
else
@@ -167,7 +174,7 @@ private void ButtonCalibrate_Click(object sender, EventArgs e)
break;
case var _ when scannerRoundedButtonControl.Name.Contains("KeyboardL"):
- Log.Debug("BCI LOG | Calibrate Button Selected " + BCIScanSections.KeyboardL);
+ _logger.LogDebug("BCI LOG | Calibrate Button Selected {Section}", BCIScanSections.KeyboardL);
if (_scanSectionsSelected == BCIScanSections.KeyboardL)
parameters = GetCalibrationParameters();
else
@@ -176,7 +183,7 @@ private void ButtonCalibrate_Click(object sender, EventArgs e)
break;
case var _ when scannerRoundedButtonControl.Name.Contains("Word"):
- Log.Debug("BCI LOG | Calibrate Button Selected " + BCIScanSections.Word);
+ _logger.LogDebug("BCI LOG | Calibrate Button Selected {Section}", BCIScanSections.Word);
if (_scanSectionsSelected == BCIScanSections.Word)
parameters = GetCalibrationParameters();
else
@@ -185,7 +192,7 @@ private void ButtonCalibrate_Click(object sender, EventArgs e)
break;
case var _ when scannerRoundedButtonControl.Name.Contains("KeyboardR"):
- Log.Debug("BCI LOG | Calibrate Button Selected " + BCIScanSections.KeyboardR);
+ _logger.LogDebug("BCI LOG | Calibrate Button Selected {Section}", BCIScanSections.KeyboardR);
if (_scanSectionsSelected == BCIScanSections.KeyboardR)
parameters = GetCalibrationParameters();
else
@@ -197,7 +204,7 @@ private void ButtonCalibrate_Click(object sender, EventArgs e)
}
catch (Exception ex)
{
- Log.Exception("BCI LOG | Error ButtonCalibrate_Click " + ex.Message);
+ _logger.LogError(ex, "BCI LOG | Error ButtonCalibrate_Click");
}
}
@@ -284,7 +291,7 @@ private void ButtonInfoModes_MouseEnter(object sender, EventArgs e)
private void ButtonInfoModes_MouseLeave(object sender, EventArgs e)
{
- try { customToolTip?.HideToolTip(); } catch (Exception ex) { Log.Debug("Error ButtonInfoModes_MouseLeave: " + ex.Message); }
+ try { customToolTip?.HideToolTip(); } catch (Exception ex) { _logger.LogDebug(ex, "Error ButtonInfoModes_MouseLeave"); }
}
private void ButtonInfoParameters_MouseEnter(object sender, EventArgs e)
@@ -350,7 +357,7 @@ private void ButtonOpc_Click(object sender, EventArgs e)
}
catch (Exception ex)
{
- Log.Exception("BCI LOG | Error ButtonOpc_Click " + ex.Message);
+ _logger.LogError(ex, "BCI LOG | Error ButtonOpc_Click");
}
}
@@ -512,7 +519,7 @@ private void DisplayCalibrationHelp()
}
catch (Exception ex)
{
- Log.Exception("BCI LOG | Exception DisplayCalibrationHelp " + ex.Message);
+ _logger.LogError(ex, "BCI LOG | Exception DisplayCalibrationHelp");
}
}
@@ -544,7 +551,7 @@ private BCISimpleParameters GetCalibrationParametersDefault(BCIScanSections bCIS
}
catch (Exception ex)
{
- Log.Exception("BCI LOG | Error GetCalibrationParametersDefault | " + ex.Message.ToString());
+ _logger.LogError(ex, "BCI LOG | Error GetCalibrationParametersDefault");
}
return bciSimpleParameters;
}
@@ -673,7 +680,7 @@ private void ProcessCalibrationStatusResult()
}
catch (Exception ex)
{
- Log.Exception("BCI LOG | Error ProcessCalibrationStatusResult | " + ex.Message.ToString());
+ _logger.LogError(ex, "BCI LOG | Error ProcessCalibrationStatusResult");
}
}
@@ -843,7 +850,7 @@ private void ValidateSliderValues(ColorSlider.ColorSlider colorSlider, Label lab
{
colorSlider.Value = colorSlider.Minimum;
label.Text = colorSlider.Minimum.ToString();
- Log.Debug("BCI LOG | ValidateSliderValues | " + ex.Message.ToString());
+ _logger.LogDebug(ex, "BCI LOG | ValidateSliderValues");
}
}
@@ -857,7 +864,7 @@ private void WebBrowser_Navigating(object sender, WebBrowserNavigatingEventArgs
{
var str = e.Url.ToString();
- Log.Debug("Url is [" + str + "]");
+ _logger.LogDebug("Url is [{Url}]", str);
if (str.ToLower().Contains("blank"))
{
diff --git a/src/Extensions/BCI/Common/BCIInterfaceUtilities/ConfirmBoxTriggerBoxSettings.cs b/src/Extensions/BCI/Common/BCIInterfaceUtilities/ConfirmBoxTriggerBoxSettings.cs
index 28449145..ea79754b 100644
--- a/src/Extensions/BCI/Common/BCIInterfaceUtilities/ConfirmBoxTriggerBoxSettings.cs
+++ b/src/Extensions/BCI/Common/BCIInterfaceUtilities/ConfirmBoxTriggerBoxSettings.cs
@@ -11,6 +11,7 @@
using ACAT.Core.WidgetManagement;
using ACAT.Extensions.BCI.Common.BCIControl;
using ACATResources;
+using Microsoft.Extensions.Logging;
using System;
using System.Drawing;
using System.Windows.Forms;
@@ -26,6 +27,7 @@ namespace ACAT.Extensions.BCI.Common.BCIInterfaceUtilities
"Application window used as a configuration UI for trigger test")]
public partial class ConfirmBoxTriggerBoxSettings : Form
{
+ private readonly ILogger _logger;
///
/// Main object of the actuator
///
@@ -56,8 +58,9 @@ public partial class ConfirmBoxTriggerBoxSettings : Form
///
/// Confirm Box with multiple results
///
- public ConfirmBoxTriggerBoxSettings()
+ public ConfirmBoxTriggerBoxSettings(ILogger logger = null)
{
+ _logger = logger ?? LoggerFactory.GetLogger();
InitializeComponent();
label1.Text = StringResources.CalibrationIsEssential;
Load += ConfirmBox_Load;
@@ -104,7 +107,7 @@ private void ButtonStartTriggerTest_Click(object sender, EventArgs e)
}
catch (Exception ex)
{
- Log.Exception("Error ButtonStartTriggerTest_Click: " + ex.Message);
+ _logger.LogError(ex, "Error ButtonStartTriggerTest_Click: " + ex.Message);
OptionResult = new Tuple(BCIMenuOptions.Options.TriggerTest, GetTriggerTestParameters());
Close();
}
@@ -163,7 +166,7 @@ private void ButtonInfoModes_MouseEnter(object sender, EventArgs e)
private void ButtonInfoModes_MouseLeave(object sender, EventArgs e)
{
- try { customToolTip?.HideToolTip(); } catch (Exception ex) { Log.Debug("Error ButtonInfoModes_MouseLeave: " + ex.Message); }
+ try { customToolTip?.HideToolTip(); } catch (Exception ex) { _logger.LogDebug("Error ButtonInfoModes_MouseLeave: " + ex.Message); }
}
private void ButtonInfoParameters_MouseEnter(object sender, EventArgs e)
@@ -195,7 +198,7 @@ private void ButtonOpcTriggerTest_Click(object sender, EventArgs e)
}
catch (Exception ex)
{
- Log.Exception("Error ButtonOpc_Click: " + ex.Message);
+ _logger.LogError(ex, "Error ButtonOpc_Click: " + ex.Message);
}
}
diff --git a/src/Extensions/BCI/Common/BCIInterfaceUtilities/OtherTestForm.cs b/src/Extensions/BCI/Common/BCIInterfaceUtilities/OtherTestForm.cs
index 85f48a5c..cb0fcf88 100644
--- a/src/Extensions/BCI/Common/BCIInterfaceUtilities/OtherTestForm.cs
+++ b/src/Extensions/BCI/Common/BCIInterfaceUtilities/OtherTestForm.cs
@@ -9,6 +9,7 @@
using ACAT.Core.WidgetManagement;
using ACAT.Extensions.BCI.Common.BCIControl;
using ACATResources;
+using Microsoft.Extensions.Logging;
using System;
using System.Drawing;
using System.Windows.Forms;
@@ -25,6 +26,7 @@ namespace ACAT.Extensions.BCI.Common.BCIInterfaceUtilities
"Application window used to display other test for BCI")]
public partial class OtherTestForm : Form
{
+ private readonly ILogger _logger;
///
/// Custom Tooltip object
///
@@ -37,8 +39,9 @@ public partial class OtherTestForm : Form
///
/// Confirm Box with multiple results
///
- public OtherTestForm()
+ public OtherTestForm(ILogger logger = null)
{
+ _logger = logger ?? LoggerFactory.GetLogger();
InitializeComponent();
Load += ConfirmBox_Load;
}
@@ -97,22 +100,22 @@ private void ButtonOpc_Click(object sender, EventArgs e)
switch (scannerRoundedButtonControl.Name)
{
case var _ when scannerRoundedButtonControl.Name.Contains("ReMapCalibrations"):
- Log.Debug("BCI LOG | AdvancedOptions | ButtonClick: ReMapCalibrations");
+ _logger.LogDebug("BCI LOG | AdvancedOptions | ButtonClick: ReMapCalibrations");
Options = BCIMenuOptions.Options.RemapCalibrations;
break;
case var _ when scannerRoundedButtonControl.Name.Contains("TriggerCheck"):
- Log.Debug("BCI LOG | AdvancedOptions | ButtonClick: TriggerCheck");
+ _logger.LogDebug("BCI LOG | AdvancedOptions | ButtonClick: TriggerCheck");
Options = BCIMenuOptions.Options.TriggerTest;
break;
case var _ when scannerRoundedButtonControl.Name.Contains("SignalCheck"):
- Log.Debug("BCI LOG | AdvancedOptions | ButtonClick: SignalCheck");
+ _logger.LogDebug("BCI LOG | AdvancedOptions | ButtonClick: SignalCheck");
Options = BCIMenuOptions.Options.SignalCheck;
break;
case var _ when scannerRoundedButtonControl.Name.Contains("EyesOpenClose"):
- Log.Debug("BCI LOG | AdvancedOptions | ButtonClick: EyesOpenClose");
+ _logger.LogDebug("BCI LOG | AdvancedOptions | ButtonClick: EyesOpenClose");
Options = BCIMenuOptions.Options.EyesCalibration;
break;
}
@@ -121,7 +124,7 @@ private void ButtonOpc_Click(object sender, EventArgs e)
}
catch (Exception ex)
{
- Log.Exception("BCI LOG | Error ButtonCalibrate_Click: " + ex.Message);
+ _logger.LogError(ex, "BCI LOG | Error ButtonCalibrate_Click: " + ex.Message);
Close();
}
}
diff --git a/src/Extensions/BCI/Common/BCIInterfaceUtilities/RemapCalibrationForm.cs b/src/Extensions/BCI/Common/BCIInterfaceUtilities/RemapCalibrationForm.cs
index abd84190..6dfd39ad 100644
--- a/src/Extensions/BCI/Common/BCIInterfaceUtilities/RemapCalibrationForm.cs
+++ b/src/Extensions/BCI/Common/BCIInterfaceUtilities/RemapCalibrationForm.cs
@@ -10,6 +10,7 @@
using ACAT.Core.Utility;
using ACAT.Extensions.BCI.Common.BCIControl;
using ACATResources;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Windows.Forms;
@@ -25,6 +26,11 @@ namespace ACAT.Extensions.BCI.Common.BCIInterfaceUtilities
"Application window used to display the remap of calibrations")]
public partial class RemapCalibrationForm : Form
{
+ ///
+ /// Logger instance
+ ///
+ private readonly ILogger _logger;
+
///
/// Main object of the actuator
///
@@ -55,8 +61,9 @@ public partial class RemapCalibrationForm : Form
///
/// Confirm Box with multiple results
///
- public RemapCalibrationForm()
+ public RemapCalibrationForm(ILogger logger)
{
+ _logger = logger ?? throw new ArgumentNullException(nameof(logger));
InitializeComponent();
Load += ConfirmBox_Load;
@@ -96,7 +103,7 @@ private void AddItemsToComboBox(ComboBox comboBox, List bCICl
}
catch (Exception ex)
{
- Log.Exception("Error AddItemsToComboBox: " + ex.Message);
+ _logger.LogError(ex, "Error AddItemsToComboBox");
}
}
@@ -127,7 +134,7 @@ private void ButtonDone_Click(object sender, EventArgs e)
var strBCICalibrationUpdatedMappings = GetMappingsValues();
_bciActuator?.IoctlRequest((int)OpCodes.SendUpdatedMappings, strBCICalibrationUpdatedMappings);
OptionResult = CheckIfComboBoxValuesChanged();
- Log.Debug("BCI LOG | Mappings change: " + OptionResult);
+ _logger.LogDebug("BCI LOG | Mappings change: {MappingsChanged}", OptionResult);
Close();
}
@@ -195,7 +202,7 @@ private BCICalibrationUpdatedMappings GetMappingsValues()
}
catch (Exception ex)
{
- Log.Exception("Error SaveMappingsValues: " + ex.Message);
+ _logger.LogError(ex, "Error SaveMappingsValues");
}
return bCICalibrationUpdatedMappings;
}
@@ -273,7 +280,7 @@ private void ProcessMapOptionsAnswer()
}
catch (Exception ex)
{
- Log.Exception("BCI LOG | Error ProcessMapOptionsAnswer: " + ex.Message);
+ _logger.LogError(ex, "BCI LOG | Error ProcessMapOptionsAnswer");
}
}
@@ -326,7 +333,7 @@ private void SetDefaultItemInComboBox(ComboBox comboBox, BCIScanSections bCIScan
}
catch (Exception ex)
{
- Log.Exception("BCI LOG | Error SetDefaultItemInComboBox: " + ex.Message);
+ _logger.LogError(ex, "BCI LOG | Error SetDefaultItemInComboBox");
}
}
@@ -340,7 +347,7 @@ private void WebBrowserDesc_Navigating(object sender, WebBrowserNavigatingEventA
{
var str = e.Url.ToString();
- Log.Debug("Url is [" + str + "]");
+ _logger.LogDebug("Url is [{Url}]", str);
if (str.ToLower().Contains("blank"))
{
diff --git a/src/Extensions/Default/Actuators/CameraActuator/CameraActuator.cs b/src/Extensions/Default/Actuators/CameraActuator/CameraActuator.cs
index 5c6f055f..2146f3c3 100644
--- a/src/Extensions/Default/Actuators/CameraActuator/CameraActuator.cs
+++ b/src/Extensions/Default/Actuators/CameraActuator/CameraActuator.cs
@@ -22,6 +22,7 @@
using ACAT.Core.Utility;
using ACAT.Core.Utility.TypeLoader;
using ACATResources;
+using Microsoft.Extensions.Logging;
using System;
using System.Linq;
using System.Runtime.ExceptionServices;
@@ -40,6 +41,8 @@ namespace ACAT.Extensions.Actuators.CameraActuator
"Actuator which uses a webcam to detect facial gestures and trigger ACAT")]
internal class CameraActuator : ActuatorBase, ISupportsPreferences, IPluginExtension
{
+ private readonly ILogger _logger;
+
///
/// The settings object for this actuator
///
diff --git a/src/Extensions/Default/Actuators/CameraActuator/CameraActuatorSwitch.cs b/src/Extensions/Default/Actuators/CameraActuator/CameraActuatorSwitch.cs
index 67e3228f..32372dc6 100644
--- a/src/Extensions/Default/Actuators/CameraActuator/CameraActuatorSwitch.cs
+++ b/src/Extensions/Default/Actuators/CameraActuator/CameraActuatorSwitch.cs
@@ -24,6 +24,7 @@
using ACAT.Core.ActuatorManagement;
using ACAT.Core.ActuatorManagement.Interfaces;
using ACAT.Core.Utility;
+using Microsoft.Extensions.Logging;
namespace ACAT.Extensions.Actuators.CameraActuator
{
@@ -34,11 +35,14 @@ public class CameraActuatorSwitch : ActuatorSwitchBase
///
private bool _disposed;
+ private readonly ILogger _logger;
+
///
/// Initializes a new instance of the class
///
- public CameraActuatorSwitch()
+ public CameraActuatorSwitch(ILogger logger = null)
{
+ _logger = logger;
}
///
@@ -46,9 +50,10 @@ public CameraActuatorSwitch()
/// members over from switchObj
///
/// Switch object to clone
- public CameraActuatorSwitch(IActuatorSwitch switchObj)
+ public CameraActuatorSwitch(IActuatorSwitch switchObj, ILogger logger = null)
: base(switchObj)
{
+ _logger = logger;
}
///
@@ -61,7 +66,7 @@ protected override void Dispose(bool disposing)
{
try
{
- Log.Verbose();
+ _logger?.LogTrace("Disposing CameraActuatorSwitch");
if (disposing)
{
diff --git a/src/Extensions/Default/Actuators/CameraActuator/ConfigureActuatorForm.cs b/src/Extensions/Default/Actuators/CameraActuator/ConfigureActuatorForm.cs
index 41ba274b..baf65862 100644
--- a/src/Extensions/Default/Actuators/CameraActuator/ConfigureActuatorForm.cs
+++ b/src/Extensions/Default/Actuators/CameraActuator/ConfigureActuatorForm.cs
@@ -15,6 +15,7 @@
using ACAT.Core.PanelManagement.Utils;
using ACAT.Core.Utility;
using ACATResources;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Drawing;
@@ -47,6 +48,7 @@ public partial class ConfigureActuatorForm : Form
private readonly Color _buttonBackColor;
private bool _gestureDetectedAtleastOnce = false;
private readonly CameraActuator _cameraActuator;
+ private readonly ILogger _logger;
private int _gestureCount = 0;
private Mode _mode = Mode.SelectCamera;
private SampleImageForm _sampleImageForm = null;
@@ -56,13 +58,14 @@ public partial class ConfigureActuatorForm : Form
private WebcamGestureSelectUserControl _webcamGestureSelectUserControl;
private WebcamGestureSettingsUserControl _webcamGestureSettingsUserControl;
- internal ConfigureActuatorForm(CameraActuator cameraActuator)
+ internal ConfigureActuatorForm(CameraActuator cameraActuator, ILogger logger)
{
InitializeComponent();
_buttonBackColor = buttonDone.BackColor;
_cameraActuator = cameraActuator;
+ _logger = logger;
Load += ConfigureActuatorForm_Load;
Shown += ConfigureActuatorForm_Shown;
@@ -100,7 +103,7 @@ private void _textTimer_Tick(object sender, EventArgs e)
private void _timer_Tick(object sender, EventArgs e)
{
- Log.Debug("_cameraActuator.CameraSensorRunning: " + _cameraActuator.CameraSensorRunning);
+ _logger.LogDebug("_cameraActuator.CameraSensorRunning: {CameraSensorRunning}", _cameraActuator.CameraSensorRunning);
if (_cameraActuator.CameraSensorRunning)
{
@@ -109,19 +112,19 @@ private void _timer_Tick(object sender, EventArgs e)
setLabelPromptDefaultText();
- Log.Debug("Camera sensor is is running. Calling _videoWindowFinder.Start()");
+ _logger.LogDebug("Camera sensor is is running. Calling _videoWindowFinder.Start()");
_videoWindowFinder.Start();
}
}
private void _videoWindowFinder_EvtVideoWindowDisplayed(IntPtr handle)
{
- Log.Verbose();
+ _logger.LogDebug("Video window displayed");
try
{
- Log.Debug("Docking calibration window");
+ _logger.LogDebug("Docking calibration window");
_videoWindowFinder.DockVideoWindow(this);
@@ -213,9 +216,9 @@ private void buttonDone_Click(object sender, EventArgs e)
_videoWindowFinder.EvtVideoWindowDisplayed -= _videoWindowFinder_EvtVideoWindowDisplayed;
_videoWindowFinder.EvtVideoWindowFindStart -= _videoWindowFinder_EvtVideoWindowFindStart;
- Log.Debug("Calling dockvideo dispose");
+ _logger.LogDebug("Calling dockvideo dispose");
_videoWindowFinder.Dispose();
- Log.Debug("Returned from dockvideo dispose");
+ _logger.LogDebug("Returned from dockvideo dispose");
}
CameraSensor.hideVideoWindow();
@@ -315,7 +318,7 @@ private void CameraActuator_EvtChangeCameraStart(String camera)
}
catch (Exception ex)
{
- Log.Exception(ex.ToString());
+ _logger.LogError(ex, "Exception in CameraActuator_EvtChangeCameraStart");
}
}
@@ -341,7 +344,7 @@ private void ConfigureActuatorForm_Load(object sender, EventArgs e)
{
Left = Top = 0;
- Log.Debug("ENtered ConfigureActuatorForm_Load");
+ _logger.LogDebug("Entered ConfigureActuatorForm_Load");
Resize += CalibrateForm_Resize;
diff --git a/src/Extensions/Default/Actuators/CameraActuator/VideoWindowFinder.cs b/src/Extensions/Default/Actuators/CameraActuator/VideoWindowFinder.cs
index 15bd0075..c90188ed 100644
--- a/src/Extensions/Default/Actuators/CameraActuator/VideoWindowFinder.cs
+++ b/src/Extensions/Default/Actuators/CameraActuator/VideoWindowFinder.cs
@@ -12,6 +12,7 @@
////////////////////////////////////////////////////////////////////////////
using ACAT.Core.Utility;
+using Microsoft.Extensions.Logging;
using System;
using System.Threading;
using System.Windows.Forms;
@@ -28,6 +29,7 @@ public class VideoWindowFinder : IDisposable
///
private bool _disposed;
+ private readonly ILogger _logger;
private Thread _thread;
public delegate void VideoWindowDisplayedDelegate(IntPtr handle);
@@ -36,6 +38,11 @@ public class VideoWindowFinder : IDisposable
public event EventHandler EvtVideoWindowFindStart;
+ public VideoWindowFinder(ILogger logger)
+ {
+ _logger = logger;
+ }
+
///
/// Disposes resources
///
@@ -83,7 +90,7 @@ private void dispose(bool disposing)
{
try
{
- Log.Verbose();
+ _logger.LogDebug("Disposing VideoWindowFinder");
if (disposing)
{
@@ -106,7 +113,7 @@ private void dispose(bool disposing)
// Release the native unmanaged resources
- Log.Debug("Exiting dispose");
+ _logger.LogDebug("Exiting dispose");
_disposed = true;
}
finally
diff --git a/src/Extensions/Default/Actuators/CameraActuator/WebcamGestureSelectUserControl.cs b/src/Extensions/Default/Actuators/CameraActuator/WebcamGestureSelectUserControl.cs
index d73ac19f..3230c574 100644
--- a/src/Extensions/Default/Actuators/CameraActuator/WebcamGestureSelectUserControl.cs
+++ b/src/Extensions/Default/Actuators/CameraActuator/WebcamGestureSelectUserControl.cs
@@ -15,6 +15,7 @@
using ACAT.Core.ActuatorManagement.Interfaces;
using ACAT.Core.Utility;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Drawing;
@@ -29,6 +30,7 @@ public partial class WebcamGestureSelectUserControl : UserControl
private readonly Dictionary _dict = new();
private IEnumerable _installedCameras;
private readonly CameraActuator _cameraActuator;
+ private readonly ILogger _logger;
private int bothIndex = -1;
private int cameraIndex = -1;
@@ -37,11 +39,12 @@ public partial class WebcamGestureSelectUserControl : UserControl
private int erIndex = -1;
- internal WebcamGestureSelectUserControl(CameraActuator cameraActuator)
+ internal WebcamGestureSelectUserControl(CameraActuator cameraActuator, ILogger logger)
{
InitializeComponent();
_buttonBackColor = buttonRecalibrate.BackColor;
_cameraActuator = cameraActuator;
+ _logger = logger;
}
public delegate void GestureSelected(bool cheekTwitch, bool eyebrowRaise);
@@ -115,7 +118,7 @@ private void DropdownCameraSelect_SelectedIndexChanged(object sender, EventArgs
{
var camera = dropdownCameraSelect.SelectedItem as String;
- Log.Debug("calling changeCamera to : " + camera);
+ _logger.LogDebug("calling changeCamera to {Camera}", camera);
if (dropdownCameraSelect.Items.Count > 1 && dropdownCameraSelect.SelectedIndex != cameraIndex)
{
diff --git a/src/Extensions/Default/AppAgents/TalkApplicationScannerAgent/TalkApplicationScannerAgent.cs b/src/Extensions/Default/AppAgents/TalkApplicationScannerAgent/TalkApplicationScannerAgent.cs
index 8db4a3da..bc285394 100644
--- a/src/Extensions/Default/AppAgents/TalkApplicationScannerAgent/TalkApplicationScannerAgent.cs
+++ b/src/Extensions/Default/AppAgents/TalkApplicationScannerAgent/TalkApplicationScannerAgent.cs
@@ -13,6 +13,7 @@
using ACAT.Core.AgentManagement;
using ACAT.Core.AgentManagement.TextControlAgents;
using ACAT.Core.Utility;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -26,6 +27,16 @@ namespace ACAT.Extensions.AppAgents.TalkApplicationScannerAgent
"Manages interactions with the Talk Window with Embedded Scanner")]
internal class TalkApplicationScannerAgent : AgentBase
{
+ ///
+ /// Logger instance
+ ///
+ private readonly ILogger _logger;
+
+ ///
+ /// Logger factory for creating loggers
+ ///
+ private readonly ILoggerFactory _loggerFactory;
+
///
/// The text control agent responsbile for handling
/// editing and caret movement functions
@@ -42,6 +53,16 @@ internal class TalkApplicationScannerAgent : AgentBase
///
private Control textBoxControl;
+ ///
+ /// Initializes a new instance of the TalkApplicationScannerAgent class
+ ///
+ public TalkApplicationScannerAgent(ILogger logger, ILoggerFactory loggerFactory)
+ {
+ _logger = logger ?? throw new ArgumentNullException(nameof(logger));
+ _loggerFactory = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory));
+ }
+ private Control textBoxControl;
+
///
/// Gets the list of process supported by this agent
///
@@ -102,25 +123,25 @@ public override void OnContextMenuRequest(WindowActivityMonitorInfo monitorInfo)
/// set to true if handled
public override void OnFocusChanged(WindowActivityMonitorInfo monitorInfo, ref bool handled)
{
- Log.Verbose();
+ _logger.LogTrace("OnFocusChanged");
_windowHandle = monitorInfo.FgHwnd;
- Log.Debug("window handle: " + _windowHandle);
+ _logger.LogDebug("window handle: {WindowHandle}", _windowHandle);
if (monitorInfo.IsNewFocusedElement || monitorInfo.IsNewWindow)
{
var automationElement = getTalkTextWinAutomationElement();
if (automationElement != null)
{
- Log.Debug("found automationelement for the text box");
+ _logger.LogDebug("found automationelement for the text box");
disposeTextInterface();
createTalkWindowTextInterface(monitorInfo.FgHwnd, automationElement);
}
else
{
- Log.Error("DID NOT find automationelement for the text box");
+ _logger.LogError("DID NOT find automationelement for the text box");
textBoxControl = null;
}
}
@@ -168,7 +189,8 @@ private void createTalkWindowTextInterface(IntPtr handle, AutomationElement auto
bool handled = false;
//_textInterface = new EditTextControlAgent(handle, automationElement, ref handled);
- _textInterface = new TalkApplicationTextControlAgent(textBoxControl, handle, automationElement, ref handled);
+ var textControlLogger = _loggerFactory.CreateLogger();
+ _textInterface = new TalkApplicationTextControlAgent(textControlLogger, textBoxControl, handle, automationElement, ref handled);
_textInterface.EvtTextChanged += _textInterface_EvtTextChanged;
setTextInterface(_textInterface);
@@ -182,7 +204,7 @@ private void disposeTextInterface()
{
if (_textInterface != null)
{
- Log.Debug("Disposing old text interface");
+ _logger.LogDebug("Disposing old text interface");
_textInterface.EvtTextChanged -= _textInterface_EvtTextChanged;
_textInterface.Dispose();
_textInterface = null;
diff --git a/src/Extensions/Default/AppAgents/TalkApplicationScannerAgent/TalkApplicationTextControlAgent.cs b/src/Extensions/Default/AppAgents/TalkApplicationScannerAgent/TalkApplicationTextControlAgent.cs
index efd12f6f..bad84823 100644
--- a/src/Extensions/Default/AppAgents/TalkApplicationScannerAgent/TalkApplicationTextControlAgent.cs
+++ b/src/Extensions/Default/AppAgents/TalkApplicationScannerAgent/TalkApplicationTextControlAgent.cs
@@ -13,6 +13,7 @@
using ACAT.Core.AgentManagement;
using ACAT.Core.AgentManagement.TextControlAgents;
using ACAT.Core.Utility;
+using Microsoft.Extensions.Logging;
using System;
using System.Text;
using System.Windows.Automation;
@@ -22,11 +23,13 @@ namespace ACAT.Extensions.AppAgents.TalkApplicationScannerAgent
{
internal class TalkApplicationTextControlAgent : EditTextControlAgent
{
+ private readonly ILogger _logger;
private readonly Control _textControl;
- public TalkApplicationTextControlAgent(Control textControl, IntPtr handle, AutomationElement editControlElement, ref bool handled) :
+ public TalkApplicationTextControlAgent(ILogger logger, Control textControl, IntPtr handle, AutomationElement editControlElement, ref bool handled) :
base(handle, editControlElement, ref handled)
{
+ _logger = logger ?? throw new ArgumentNullException(nameof(logger));
_textControl = textControl;
}
@@ -64,7 +67,7 @@ public override void Insert(int offset, string word)
}
catch (Exception ex)
{
- Log.Exception(ex);
+ _logger.LogError(ex, "Error in Insert method");
}
finally
{
@@ -74,7 +77,7 @@ public override void Insert(int offset, string word)
public override void Replace(int offset, int count, String word)
{
- Log.Debug("HARRIS offset = " + offset + " count " + count + " word " + word);
+ _logger.LogDebug("HARRIS offset = {Offset} count {Count} word {Word}", offset, count, word);
try
{
@@ -114,7 +117,7 @@ public override void Replace(int offset, int count, String word)
}
catch (Exception ex)
{
- Log.Exception(ex);
+ _logger.LogError(ex, "Error in Replace method");
}
finally
{
diff --git a/src/Extensions/Default/FunctionalAgents/LaunchAppAgent/LaunchAppAgent.cs b/src/Extensions/Default/FunctionalAgents/LaunchAppAgent/LaunchAppAgent.cs
index 19c1a20a..3af60ecd 100644
--- a/src/Extensions/Default/FunctionalAgents/LaunchAppAgent/LaunchAppAgent.cs
+++ b/src/Extensions/Default/FunctionalAgents/LaunchAppAgent/LaunchAppAgent.cs
@@ -26,6 +26,7 @@
using ACAT.Core.Utility;
using ACAT.Extension.UI;
using ACAT.Extensions.UI.UserControls.Toolbars;
+using Microsoft.Extensions.Logging;
using System;
using System.Diagnostics;
using System.Threading;
@@ -63,6 +64,8 @@ internal class LaunchAppAgent : FunctionalAgentBase
///
private const string SettingsFileName = "LaunchAppSettings.xml";
+ private readonly ILogger _logger;
+
///
/// The usercontrol that displays the list of applications
///
@@ -86,8 +89,9 @@ internal class LaunchAppAgent : FunctionalAgentBase
///
/// Initializes a new instance of the class.
///
- public LaunchAppAgent()
+ public LaunchAppAgent(ILogger logger)
{
+ _logger = logger;
LaunchAppSettings.PreferencesFilePath = UserManager.GetFullPath(SettingsFileName);
Settings = LaunchAppSettings.Load();
}
@@ -99,7 +103,7 @@ public override bool Activate()
if (_launchAppScanner == null)
{
- Log.Error("Could not create LaunchAppScanner");
+ _logger.LogError("Could not create LaunchAppScanner");
return false;
}
@@ -192,11 +196,11 @@ public override void OnFocusChanged(WindowActivityMonitorInfo monitorInfo, ref b
{
if (IsClosing)
{
- Log.Debug("IsClosing is true. Will not handle the focus change");
+ _logger.LogDebug("IsClosing is true. Will not handle the focus change");
return;
}
- Log.Debug("OnFocus: " + monitorInfo);
+ _logger.LogDebug("OnFocus: {MonitorInfo}", monitorInfo);
base.OnFocusChanged(monitorInfo, ref handled);
@@ -379,7 +383,7 @@ public bool launchProcess(AppInfo info)
}
catch (Exception ex)
{
- Log.Exception(ex.ToString());
+ _logger.LogError(ex, "{Exception}", ex.ToString());
retVal = false;
}
@@ -452,7 +456,7 @@ private void waitForProcessAndActivate(Process process)
}
catch (Exception ex)
{
- Log.Debug(ex.ToString());
+ _logger.LogDebug("{Exception}", ex.ToString());
}
}
diff --git a/src/Extensions/Default/FunctionalAgents/SwitchWindowsAgent/SwitchWindowsAgent.cs b/src/Extensions/Default/FunctionalAgents/SwitchWindowsAgent/SwitchWindowsAgent.cs
index bb5ddbd8..927c2438 100644
--- a/src/Extensions/Default/FunctionalAgents/SwitchWindowsAgent/SwitchWindowsAgent.cs
+++ b/src/Extensions/Default/FunctionalAgents/SwitchWindowsAgent/SwitchWindowsAgent.cs
@@ -22,6 +22,7 @@
using ACAT.Core.AgentManagement;
using ACAT.Core.PanelManagement;
using ACAT.Core.Utility;
+using Microsoft.Extensions.Logging;
using System;
using System.Windows.Automation;
using System.Windows.Forms;
@@ -49,6 +50,8 @@ internal class SwitchWindowsAgent : FunctionalAgentBase
///
private static SwitchWindowsScanner _switchWindowsScanner;
+ private readonly ILogger _logger;
+
///
/// Meta data for window selected
///
@@ -57,8 +60,9 @@ internal class SwitchWindowsAgent : FunctionalAgentBase
///
/// Initializes a new instance of the class.
///
- public SwitchWindowsAgent()
+ public SwitchWindowsAgent(ILogger logger)
{
+ _logger = logger;
Name = ClassDescriptorAttribute.GetDescriptor(GetType()).Name;
}
@@ -131,11 +135,11 @@ public override void OnFocusChanged(WindowActivityMonitorInfo monitorInfo, ref b
{
if (IsClosing)
{
- Log.Debug("IsClosing is true. Will not handle the focus change");
+ _logger.LogDebug("IsClosing is true. Will not handle the focus change");
return;
}
- Log.Debug("OnFocus: " + monitorInfo);
+ _logger.LogDebug("OnFocus: {MonitorInfo}", monitorInfo);
base.OnFocusChanged(monitorInfo, ref handled);
diff --git a/src/Extensions/Default/FunctionalAgents/SwitchWindowsAgent/SwitchWindowsScanner.cs b/src/Extensions/Default/FunctionalAgents/SwitchWindowsAgent/SwitchWindowsScanner.cs
index 8152c610..b5d82058 100644
--- a/src/Extensions/Default/FunctionalAgents/SwitchWindowsAgent/SwitchWindowsScanner.cs
+++ b/src/Extensions/Default/FunctionalAgents/SwitchWindowsAgent/SwitchWindowsScanner.cs
@@ -25,6 +25,7 @@
using ACAT.Core.Utility;
using ACAT.Core.WidgetManagement;
using ACAT.Core.Widgets;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Drawing;
@@ -48,7 +49,7 @@ namespace ACAT.Extensions.FunctionalAgents.SwitchWindowsAgent
"SwitchWindowsScanner",
"Switch Windows Scanner")]
public partial class SwitchWindowsScanner : GenericScannerForm
- {
+ { private readonly ILogger _logger;
///
/// Enables invoking methods and properties in this form
///
diff --git a/src/Extensions/Default/TTSEngines/SAPIEngine/SAPIEngine.cs b/src/Extensions/Default/TTSEngines/SAPIEngine/SAPIEngine.cs
index aeeaf93c..d0d7ec9a 100644
--- a/src/Extensions/Default/TTSEngines/SAPIEngine/SAPIEngine.cs
+++ b/src/Extensions/Default/TTSEngines/SAPIEngine/SAPIEngine.cs
@@ -17,6 +17,7 @@
using ACAT.Core.TTSManagement.Interfaces;
using ACAT.Core.UserManagement;
using ACAT.Core.Utility;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections;
using System.Collections.Generic;
@@ -65,6 +66,8 @@ public class SAPIEngine : ExtensionInvoker, ITTSEngine, ISupportsPreferences
///
private bool _disposed;
+ private readonly ILogger _logger;
+
///
/// Is speech muted?
///
@@ -93,8 +96,9 @@ public class SAPIEngine : ExtensionInvoker, ITTSEngine, ISupportsPreferences
///
/// Initializes a new instance of the class.
///
- public SAPIEngine()
+ public SAPIEngine(ILogger logger)
{
+ _logger = logger;
SAPISettings.PreferencesFilePath = UserManager.GetFullPath(SettingsFileName);
SAPISettings = SAPISettings.Load();
UseAlternatePronunciations = SAPISettings.UseAlternatePronunciations;
@@ -281,10 +285,8 @@ public bool Init(CultureInfo ci)
foreach (InstalledVoice iv in ins)
{
- Log.Debug("Found installed voice: " + iv.VoiceInfo.Name +
- "Gender " + iv.VoiceInfo.Gender +
- ", age: " + iv.VoiceInfo.Age +
- ", culture: " + iv.VoiceInfo.Culture.Name);
+ _logger.LogDebug("Found installed voice: {VoiceName} Gender {Gender}, age: {Age}, culture: {Culture}",
+ iv.VoiceInfo.Name, iv.VoiceInfo.Gender, iv.VoiceInfo.Age, iv.VoiceInfo.Culture.Name);
}
loadPronunciations(ci);
@@ -433,20 +435,20 @@ public virtual bool ShowPreferencesDialog()
/// true on success
public bool Speak(String text)
{
- Log.Debug("Entering...");
+ _logger.LogDebug("Entering...");
try
{
if (!IsMuted())
{
text = autoAppendPunctuation(replaceWithAltPronunciations(text));
- Log.Debug("Speaking text");
+ _logger.LogDebug("Speaking text");
Synthesizer.SpeakAsync(text);
}
}
catch (Exception ex)
{
- Log.Exception("Exception caught! ex=" + ex.Message);
+ _logger.LogError(ex, "Exception caught! ex={Message}", ex.Message);
}
return true;
@@ -471,7 +473,7 @@ public bool SpeakAsync(String text, out int bookmark)
{
var promptBuilder = new PromptBuilder();
text = autoAppendPunctuation(replaceWithAltPronunciations(text));
- Log.Debug("Speaking text");
+ _logger.LogDebug("Speaking text");
promptBuilder.AppendText(autoAppendPunctuation(text));
promptBuilder.AppendBookmark(bookmark.ToString());
@@ -481,7 +483,7 @@ public bool SpeakAsync(String text, out int bookmark)
}
catch (Exception ex)
{
- Log.Exception(ex.ToString());
+ _logger.LogError(ex, "{Exception}", ex.ToString());
retVal = false;
}
@@ -496,7 +498,7 @@ public bool SpeakAsync(String text, out int bookmark)
/// true on success
public bool SpeakSsml(String ssml, String text, String ttsPlaceHolderString)
{
- Log.Debug("Entering...");
+ _logger.LogDebug("Entering...");
try
{
@@ -505,13 +507,13 @@ public bool SpeakSsml(String ssml, String text, String ttsPlaceHolderString)
text = autoAppendPunctuation(replaceWithAltPronunciations(text));
ssml = ssml.Replace(ttsPlaceHolderString, text);
- Log.Debug("Speaking text");
+ _logger.LogDebug("Speaking text");
Synthesizer.SpeakSsmlAsync(ssml);
}
}
catch (Exception ex)
{
- Log.Exception("Exception caught! ex=" + ex.Message);
+ _logger.LogError(ex, "Exception caught! ex={Message}", ex.Message);
}
return true;
@@ -544,7 +546,7 @@ public bool SpeakSsmlAsync(String ssml, String text, String ttsPlaceHolderString
text = autoAppendPunctuation(replaceWithAltPronunciations(text));
ssml = ssml.Replace(ttsPlaceHolderString, text);
- Log.Debug("Speaking text");
+ _logger.LogDebug("Speaking text");
TTSPrompt prompt = new(ssml, SynthesisTextFormat.Ssml)
{
@@ -552,7 +554,7 @@ public bool SpeakSsmlAsync(String ssml, String text, String ttsPlaceHolderString
};
Synthesizer.SpeakAsync(prompt);
- Log.Debug("Returned from speakasync");
+ _logger.LogDebug("Returned from speakasync");
}
else
{
@@ -561,7 +563,7 @@ public bool SpeakSsmlAsync(String ssml, String text, String ttsPlaceHolderString
}
catch (Exception ex)
{
- Log.Exception(ex.ToString());
+ _logger.LogError(ex, "{Exception}", ex.ToString());
retVal = false;
}
@@ -618,7 +620,7 @@ protected virtual void Dispose(bool disposing)
// Check to see if Dispose has already been called.
if (!_disposed)
{
- Log.Verbose();
+ _logger.LogTrace("Disposing SAPIEngine");
if (disposing)
{
@@ -679,7 +681,7 @@ private bool loadPronunciations(CultureInfo ci)
_pronunciations = new Pronunciations();
- Log.Debug("Loading pronunciations. Filename is " + SAPISettings.PronunciationsFile);
+ _logger.LogDebug("Loading pronunciations. Filename is {PronunciationsFile}", SAPISettings.PronunciationsFile);
return _pronunciations.Load(ci, SAPISettings.PronunciationsFile);
}
@@ -735,7 +737,7 @@ private void setSpeechSynthSettings()
}
catch (Exception ex)
{
- Log.Exception("Error setting TTS settings " + ex);
+ _logger.LogError(ex, "Error setting TTS settings {Exception}", ex);
}
}
@@ -754,7 +756,7 @@ private void speechSynthesizer_BookmarkReached(object sender, BookmarkReachedEve
}
catch (Exception ex)
{
- Log.Exception("Invalid bookmark " + e.Bookmark + ", exception: " + ex);
+ _logger.LogError(ex, "Invalid bookmark {Bookmark}, exception: {Exception}", e.Bookmark, ex);
}
}
diff --git a/src/Extensions/Default/TTSEngines/TTSClient/TTSClient.cs b/src/Extensions/Default/TTSEngines/TTSClient/TTSClient.cs
index e95fd4c9..c2e4f0c4 100644
--- a/src/Extensions/Default/TTSEngines/TTSClient/TTSClient.cs
+++ b/src/Extensions/Default/TTSEngines/TTSClient/TTSClient.cs
@@ -17,6 +17,7 @@
using ACAT.Core.TTSManagement.Interfaces;
using ACAT.Core.UserManagement;
using ACAT.Core.Utility;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Globalization;
@@ -74,6 +75,8 @@ public class TTSClient : ExtensionInvoker, ITTSEngine, ISupportsPreferences
///
private bool _disposed;
+ private readonly ILogger _logger;
+
///
/// Is speech muted?
///
@@ -114,8 +117,9 @@ public class TTSClient : ExtensionInvoker, ITTSEngine, ISupportsPreferences
///
/// Initializes a new instance of the class.
///
- public TTSClient()
+ public TTSClient(ILogger logger)
{
+ _logger = logger;
TTSClientSettings.PreferencesFilePath = UserManager.GetFullPath(SettingsFileName);
Settings = TTSClientSettings.Load();
UseAlternatePronunciations = Settings.UseAlternatePronunciations;
@@ -412,7 +416,7 @@ public virtual bool ShowPreferencesDialog()
/// true on success
public bool Speak(String text)
{
- Log.Debug("Entering...text=" + text);
+ _logger.LogDebug("Entering...text={Text}", text);
try
{
@@ -423,7 +427,7 @@ public bool Speak(String text)
}
catch (Exception ex)
{
- Log.Exception("Exception caught! ex=" + ex.Message);
+ _logger.LogError(ex, "Exception caught! ex={Message}", ex.Message);
}
return true;
@@ -451,7 +455,7 @@ public bool SpeakAsync(String text, out int bookmark)
}
catch (Exception ex)
{
- Log.Exception(ex.ToString());
+ _logger.LogError(ex, "{Exception}", ex.ToString());
retVal = false;
}
@@ -467,7 +471,7 @@ public bool SpeakAsync(String text, out int bookmark)
/// true on success
public bool SpeakSsml(String ssml, String text, String placeHolder)
{
- Log.Debug("Entering...text=" + ssml);
+ _logger.LogDebug("Entering...text={Ssml}", ssml);
try
{
@@ -476,15 +480,15 @@ public bool SpeakSsml(String ssml, String text, String placeHolder)
text = autoAppendPunctuation(replaceWithAltPronunciations(text));
ssml = ssml.Replace(placeHolder, text);
- Log.Debug("Speaking text:" + text);
- Log.Debug("ssml:" + ssml);
+ _logger.LogDebug("Speaking text:{Text}", text);
+ _logger.LogDebug("ssml:{Ssml}", ssml);
sendSsml(ssml);
}
}
catch (Exception ex)
{
- Log.Exception("Exception caught! ex=" + ex.Message);
+ _logger.LogError(ex, "Exception caught! ex={Message}", ex.Message);
}
return true;
@@ -510,15 +514,15 @@ public bool SpeakSsmlAsync(String ssml, String text, String placeHolder, out int
text = autoAppendPunctuation(replaceWithAltPronunciations(text));
ssml = ssml.Replace(placeHolder, text);
- Log.Debug("Speaking text:" + text);
- Log.Debug("ssml:" + ssml);
+ _logger.LogDebug("Speaking text:{Text}", text);
+ _logger.LogDebug("ssml:{Ssml}", ssml);
sendSsml(ssml);
}
}
catch (Exception ex)
{
- Log.Exception(ex.ToString());
+ _logger.LogError(ex, "{Exception}", ex.ToString());
retVal = false;
}
@@ -570,7 +574,7 @@ protected virtual void Dispose(bool disposing)
// Check to see if Dispose has already been called.
if (!_disposed)
{
- Log.Verbose();
+ _logger.LogTrace("Disposing TTSClient");
if (disposing)
{
@@ -624,8 +628,8 @@ private String getTempFileName(String extension)
}
catch (Exception ex)
{
- Log.Exception("Could not create temp directory for TTSClient. " + ex);
- path = ".\\";
+ _logger.LogError(ex, "Could not create temp directory for TTSClient. {Exception}", ex);
+ path = ".\\\
}
path = path + "\\TTS_" + Guid.NewGuid() + extension;
@@ -647,7 +651,7 @@ private bool loadPronunciations(CultureInfo ci)
_pronunciations = new Pronunciations();
- Log.Debug("Loading pronunciations. Filename is " + Settings.PronunciationsFile);
+ _logger.LogDebug("Loading pronunciations. Filename is {PronunciationsFile}", Settings.PronunciationsFile);
return _pronunciations.Load(ci, Settings.PronunciationsFile);
}
@@ -809,7 +813,7 @@ private bool writeToFile(String fileName, String text)
}
catch (Exception ex)
{
- Log.Exception("Error writing to temp file " + fileName + ". Exception: " + ex);
+ _logger.LogError(ex, "Error writing to temp file {FileName}. Exception: {Exception}", fileName, ex);
return false;
}
diff --git a/src/Extensions/Default/TTSEngines/TTSClient/TransportHttp.cs b/src/Extensions/Default/TTSEngines/TTSClient/TransportHttp.cs
index a1234c4b..7b433a49 100644
--- a/src/Extensions/Default/TTSEngines/TTSClient/TransportHttp.cs
+++ b/src/Extensions/Default/TTSEngines/TTSClient/TransportHttp.cs
@@ -12,6 +12,7 @@
////////////////////////////////////////////////////////////////////////////
using ACAT.Core.Utility;
+using Microsoft.Extensions.Logging;
using System;
using System.Net.Http;
using System.Text;
@@ -21,6 +22,13 @@ namespace ACAT.Extensions.TTSEngines.TTSClient
[Serializable]
public class TransportHttp : ITTSTransport
{
+ private readonly ILogger _logger;
+
+ public TransportHttp(ILogger logger)
+ {
+ _logger = logger;
+ }
+
public bool Send(String data, TTSFormat format)
{
if (format == TTSFormat.None)
@@ -49,7 +57,7 @@ private async void sendHttp(String data, TTSFormat format)
}
catch (Exception ex)
{
- Log.Exception("*** Could not send TTS request over http to " + Url + ". Exception: " + ex);
+ _logger.LogError(ex, "*** Could not send TTS request over http to {Url}. Exception: {Exception}", Url, ex);
}
}
}
diff --git a/src/Extensions/Default/WordPredictors/ConvAssist/ConvAssistUtils.cs b/src/Extensions/Default/WordPredictors/ConvAssist/ConvAssistUtils.cs
index a57d50c3..1f715f07 100644
--- a/src/Extensions/Default/WordPredictors/ConvAssist/ConvAssistUtils.cs
+++ b/src/Extensions/Default/WordPredictors/ConvAssist/ConvAssistUtils.cs
@@ -12,6 +12,7 @@
using ACAT.Core.Utility;
using ACAT.Extension;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Globalization;
@@ -129,7 +130,8 @@ public static List> ToList(List predictions
}
catch (Exception es)
{
- Log.Exception("ConvAssist Predict " + es);
+ // Log exception but continue - return empty list
+ // Note: Static method cannot use injected logger
}
return newList;
}
diff --git a/src/Extensions/Default/WordPredictors/ConvAssist/ConvAssistWordPredictor.cs b/src/Extensions/Default/WordPredictors/ConvAssist/ConvAssistWordPredictor.cs
index 88841837..8fee7da0 100644
--- a/src/Extensions/Default/WordPredictors/ConvAssist/ConvAssistWordPredictor.cs
+++ b/src/Extensions/Default/WordPredictors/ConvAssist/ConvAssistWordPredictor.cs
@@ -19,6 +19,7 @@
using ACAT.Core.WordPredictorManagement.Interfaces;
using ACAT.Extensions.WordPredictors.ConvAssist.MessageTypes;
using ACATResources;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
@@ -79,6 +80,8 @@ public class ConvAssistWordPredictor : ConvAssistWordPredictorBase
///
internal static Settings settings;
+ private readonly ILogger _logger;
+
private readonly WordPredictionsRequestHandler _wordPredictionsRequestHandler;
///
@@ -92,8 +95,9 @@ public class ConvAssistWordPredictor : ConvAssistWordPredictorBase
///
/// Initializes and instance of the class
///
- public ConvAssistWordPredictor()
+ public ConvAssistWordPredictor(ILogger logger)
{
+ _logger = logger;
Settings.PreferencesFilePath = getUserRelativePath(CultureInfo.CurrentCulture.TwoLetterISOLanguageName, SettingsFileName, true);
settings = Settings.Load();
@@ -171,7 +175,7 @@ public override bool Init(CultureInfo ci)
//So, we don't need to start it here
string path = Path.Combine(FileUtils.ACATPath, ConvAssistAppFolder, ConvAssistAppName);
- Log.Info("ConvAssist path: " + path);
+ _logger.LogInformation("ConvAssist path: {Path}", path);
Process[] runningProcesses = Process.GetProcessesByName(ConvAssistName);
if (runningProcesses.Length == 0)
@@ -194,7 +198,7 @@ public override bool Init(CultureInfo ci)
}
}
#endif
- Log.Info("ConvAssist process started. Starting Named Pipe.");
+ _logger.LogInformation("ConvAssist process started. Starting Named Pipe.");
// Now start the named pipe server and wait for the client to connect
string convAssistSettings = Path.Combine(UserManager.CurrentUserDir, CultureInfo.CurrentUICulture.TwoLetterISOLanguageName, "WordPredictors", "ConvAssist", "Settings");
@@ -305,7 +309,7 @@ protected override bool learn(String text, WordPredictorMessageTypes requestType
}
catch (Exception ex)
{
- Log.Exception(ex);
+ _logger.LogError(ex, "Exception in Init");
}
return result;
@@ -334,7 +338,7 @@ private void Close(bool waitOnCompletion = true)
/// A list of predicted words
private WordPredictionResponse ProcessPredictionRequest(WordPredictionRequest request)
{
- Log.Debug("Predict for: " + request.PrevWords + " " + request.CurrentWord);
+ _logger.LogDebug("Predict for: {PrevWords} {CurrentWord}", request.PrevWords, request.CurrentWord);
WordPredictionResponse response = null;
try
@@ -358,7 +362,7 @@ private WordPredictionResponse ProcessPredictionRequest(WordPredictionRequest re
}
catch (Exception ex)
{
- Log.Exception("ConvAssist Exception " + ex);
+ _logger.LogError(ex, "ConvAssist Exception {Exception}", ex);
response = new WordPredictionResponse(request, new List(), false);
}
diff --git a/src/Extensions/Default/WordPredictors/ConvAssist/NamedPipeServerConvAssist.cs b/src/Extensions/Default/WordPredictors/ConvAssist/NamedPipeServerConvAssist.cs
index 542d55bc..01198444 100644
--- a/src/Extensions/Default/WordPredictors/ConvAssist/NamedPipeServerConvAssist.cs
+++ b/src/Extensions/Default/WordPredictors/ConvAssist/NamedPipeServerConvAssist.cs
@@ -18,6 +18,7 @@
using ACAT.Core.WordPredictorManagement.Interfaces;
using ACAT.Extension;
using ACAT.Extensions.WordPredictors.ConvAssist.MessageTypes;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Globalization;
@@ -64,6 +65,8 @@ public class NamedPipeServerConvAssist : IDisposable
///
private readonly object _syncObj = new();
+ private readonly ILogger _logger;
+
///
/// Path to the INI files
///
@@ -94,8 +97,11 @@ public class NamedPipeServerConvAssist : IDisposable
///
/// Name of the pipe
/// What direction?
- public NamedPipeServerConvAssist(string pipeName, PipeDirection pipeDirection, string path)
+ /// Path to files
+ /// Logger instance
+ public NamedPipeServerConvAssist(string pipeName, PipeDirection pipeDirection, string path, ILogger logger)
{
+ _logger = logger ?? throw new ArgumentNullException(nameof(logger));
this.PipeName = pipeName;
this.PipeDirection = pipeDirection;
this._pathToFiles = path;
@@ -138,7 +144,7 @@ public bool ClosePipeServer()
}
catch (Exception ex)
{
- Log.Exception("ConvAssist ClosePipe Error:" + ex.Message);
+ _logger.LogError(ex, "ConvAssist ClosePipe Error:{Message}", ex.Message);
return false;
}
clientConected = false;
@@ -159,7 +165,7 @@ public bool CreatePipeServer(bool send_params = false)
}
catch (Exception ex)
{
- Log.Exception("Exception in createPipeServer: " + ex);
+ _logger.LogError(ex, "Exception in createPipeServer: {Exception}", ex);
}
return success;
@@ -200,7 +206,7 @@ public bool NotifyAppEvent(EventTypes eventType)
}
catch (Exception ex)
{
- Log.Exception("ConvAssist AppEvent: " + ex.Message);
+ _logger.LogError(ex, "ConvAssist AppEvent: {Message}", ex.Message);
}
return true;
}
@@ -239,7 +245,7 @@ public async Task SendParams()
}
catch (Exception ex)
{
- Log.Exception("Error in param enable log: " + ex);
+ _logger.LogError(ex, "Error in param enable log: {Exception}", ex);
}
}
@@ -305,7 +311,7 @@ public async Task StartNamedPipeServer(CancellationToken token, bool send_
}
catch (TimeoutException)
{
- Log.Exception("ConvAssist StartNamedPiperServer Timeout");
+ _logger.LogError("ConvAssist StartNamedPiperServer Timeout");
}
}
@@ -325,12 +331,12 @@ public async Task StartNamedPipeServer(CancellationToken token, bool send_
catch (TimeoutException ex)
{
success = false;
- Log.Exception(ex);
+ _logger.LogError(ex, "TimeoutException in SendParams");
}
catch (Exception ex)
{
success = false;
- Log.Exception(ex);
+ _logger.LogError(ex, "Exception in SendParams");
}
}
@@ -434,7 +440,7 @@ public void Write(string value)
catch (Exception ex)
{
- Log.Exception("ConvAssist Write Error: " + ex.Message);
+ _logger.LogError(ex, "ConvAssist Write Error: {Message}", ex.Message);
}
}
@@ -451,7 +457,7 @@ public async Task WriteAsync(string value, int msDelay)
byte[] payload = Encoding.UTF8.GetBytes(value);
- Log.Debug("Payload hex: " + BitConverter.ToString(payload));
+ _logger.LogDebug("Payload hex: {Payload}", BitConverter.ToString(payload));
byte[] lengthPrefix = BitConverter.GetBytes(payload.Length);
@@ -523,7 +529,7 @@ public string WriteSync(string value, int msDelay)
string message = string.Empty;
try
{
- Log.Debug("ConvAssist WriteSync Lock on");
+ _logger.LogDebug("ConvAssist WriteSync Lock on");
lock (_writeSyncObj)
{
TaskFinished = false;
@@ -563,9 +569,9 @@ public string WriteSync(string value, int msDelay)
}
catch (Exception ex)
{
- Log.Exception("ConvAssist WriteSync " + ex);
+ _logger.LogError(ex, "ConvAssist WriteSync {Exception}", ex);
}
- Log.Debug("ConvAssist WriteSync Lock off");
+ _logger.LogDebug("ConvAssist WriteSync Lock off");
return message;
}
@@ -575,7 +581,7 @@ public string WriteSync(string value, int msDelay)
///
private void OnConnection(IAsyncResult ar)
{
- Log.Debug("ConvAssist Establish connection");
+ _logger.LogDebug("ConvAssist Establish connection");
NumClientsConnected++;
clientConected = true;
var pipeServerState = (PipeServerStateConvAssist)ar.AsyncState;
@@ -608,7 +614,7 @@ private void PipeServer_EvtClientConnected()
private void PipeServer_EvtClientDisconnected()
{
- Log.Debug("ConvAssist PipeServer_EvtClientDisconnected");
+ _logger.LogDebug("ConvAssist PipeServer_EvtClientDisconnected");
EvtClientDisconnected?.Invoke(null, new EventArgs());
clientConected = false;
clientAnswerParameters = false;
@@ -706,7 +712,7 @@ private void WriteCallback(IAsyncResult iar)
}
catch (Exception ex)
{
- Log.Exception("ConvAssist Error in writeCallback: " + ex.Message);
+ _logger.LogError(ex, "ConvAssist Error in writeCallback: {Message}", ex.Message);
}
}
}
diff --git a/src/Extensions/Default/WordPredictors/ConvAssist/SentencePredictionsRequestHandler.cs b/src/Extensions/Default/WordPredictors/ConvAssist/SentencePredictionsRequestHandler.cs
index e31a8739..e5a2dfeb 100644
--- a/src/Extensions/Default/WordPredictors/ConvAssist/SentencePredictionsRequestHandler.cs
+++ b/src/Extensions/Default/WordPredictors/ConvAssist/SentencePredictionsRequestHandler.cs
@@ -15,6 +15,7 @@
using ACAT.Core.WordPredictorManagement;
using ACAT.Core.WordPredictorManagement.Interfaces;
using ACAT.Extensions.WordPredictors.ConvAssist.MessageTypes;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -29,10 +30,12 @@ internal class SentencePredictionsRequestHandler
private string _prevPrevWords = null;
private List _prevSentencePredictionResults = new();
private readonly ConvAssistWordPredictor _wordPredictor;
+ private readonly ILogger _logger;
- public SentencePredictionsRequestHandler(ConvAssistWordPredictor wordPredictor)
+ public SentencePredictionsRequestHandler(ConvAssistWordPredictor wordPredictor, ILogger logger)
{
_wordPredictor = wordPredictor;
+ _logger = logger;
}
///
@@ -56,7 +59,7 @@ public WordPredictionResponse ProcessPredictionRequest(WordPredictionRequest req
WordPredictionResponse response;
try
{
- Log.Debug("_prevMode: " + _prevMode + ", currentMode: " + _wordPredictor.GetMode());
+ _logger.LogDebug("_prevMode: {PrevMode}, currentMode: {CurrentMode}", _prevMode, _wordPredictor.GetMode());
if (_prevMode != _wordPredictor.GetMode() ||
_prevPrevWords == null ||
_prevCurrentWord == null ||
@@ -93,7 +96,7 @@ public WordPredictionResponse ProcessPredictionRequest(WordPredictionRequest req
{
predictedSentences = _wordPredictor.SendMessageConvAssistSentencePrediction(preceedingWords.ToString(),
request.WordPredictionMode);
- Log.Debug("ConvAssist sentences response: " + predictedSentences);
+ _logger.LogDebug("ConvAssist sentences response: {PredictedSentences}", predictedSentences);
}
else
{
@@ -130,13 +133,13 @@ public WordPredictionResponse ProcessPredictionRequest(WordPredictionRequest req
}
else
{
- Log.Debug("Nothing changed. returning previous");
+ _logger.LogDebug("Nothing changed. returning previous");
response = new WordPredictionResponse(request, _prevSentencePredictionResults, true);
}
}
catch (Exception ex)
{
- Log.Exception("ConvAssist Predict Exception " + ex);
+ _logger.LogError(ex, "ConvAssist Predict Exception");
_prevSentencePredictionResults = new List();
response = new WordPredictionResponse(request, new List(), false);
@@ -205,7 +208,7 @@ private List ProcessSentencesPredictions(string predictions, string curr
}
catch (Exception sentencesLetters)
{
- Log.Exception("ConvAssist Predict sentencesLetters " + sentencesLetters);
+ _logger.LogError(sentencesLetters, "ConvAssist Predict sentencesLetters");
}
return retVal;
}
diff --git a/src/Extensions/Default/WordPredictors/ConvAssist/WordPredictionsRequestHandler.cs b/src/Extensions/Default/WordPredictors/ConvAssist/WordPredictionsRequestHandler.cs
index 1f618739..f8815425 100644
--- a/src/Extensions/Default/WordPredictors/ConvAssist/WordPredictionsRequestHandler.cs
+++ b/src/Extensions/Default/WordPredictors/ConvAssist/WordPredictionsRequestHandler.cs
@@ -15,6 +15,7 @@
using ACAT.Core.WordPredictorManagement;
using ACAT.Core.WordPredictorManagement.Interfaces;
using ACAT.Extensions.WordPredictors.ConvAssist.MessageTypes;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Globalization;
@@ -51,9 +52,12 @@ internal class WordPredictionsRequestHandler
///
private readonly ConvAssistWordPredictor WordPredictor;
- public WordPredictionsRequestHandler(ConvAssistWordPredictor wordPredictor)
+ private readonly ILogger _logger;
+
+ public WordPredictionsRequestHandler(ConvAssistWordPredictor wordPredictor, ILogger logger)
{
WordPredictor = wordPredictor;
+ _logger = logger;
}
///
@@ -67,7 +71,7 @@ public WordPredictionsRequestHandler(ConvAssistWordPredictor wordPredictor)
/// A list of predicted words
public WordPredictionResponse ProcessPredictionRequest(WordPredictionRequest request)
{
- Log.Debug("Predict for: " + request.PrevWords + " " + request.CurrentWord);
+ _logger.LogDebug("Predict for: {PrevWords} {CurrentWord}", request.PrevWords, request.CurrentWord);
StringBuilder preceedingWords = new();
if (request.PredictionType != PredictionTypes.Words)
@@ -105,13 +109,13 @@ public WordPredictionResponse ProcessPredictionRequest(WordPredictionRequest req
List result;
try
{
- Log.Debug("ConvAssist Mode: " + request.WordPredictionMode);
+ _logger.LogDebug("ConvAssist Mode: {WordPredictionMode}", request.WordPredictionMode);
string predictedWords = String.Empty;
predictedWords = WordPredictor.SendMessageConvAssistWordPrediction(preceedingWords.ToString(), request.WordPredictionMode);
- Log.Debug("ConvAssist Words response: " + predictedWords);
+ _logger.LogDebug("ConvAssist Words response: {PredictedWords}", predictedWords);
try
{
@@ -129,7 +133,7 @@ public WordPredictionResponse ProcessPredictionRequest(WordPredictionRequest req
PrevWordPredictionResults = result;
}
- Log.Debug("Entered prediction" + prevWords + " " + currentWord);
+ _logger.LogDebug("Entered prediction {PrevWords} {CurrentWord}", prevWords, currentWord);
response = new WordPredictionResponse(request, result, true);
}
@@ -140,7 +144,7 @@ public WordPredictionResponse ProcessPredictionRequest(WordPredictionRequest req
}
catch (Exception ex)
{
- Log.Exception("ConvAssist Predict Exception " + ex);
+ _logger.LogError(ex, "ConvAssist Predict Exception");
response = new WordPredictionResponse(request, new List(), false);
}
finally
@@ -230,7 +234,7 @@ private List ProcessWordPredictions(ConvAssistWordPredictor wordPredicto
}
catch (Exception words)
{
- Log.Exception("ConvAssist Predict Words " + words);
+ _logger.LogError(words, "ConvAssist Predict Words");
}
// Keyword to split between predictions
retVal.Add("&LETTERS");
@@ -258,7 +262,7 @@ private List ProcessWordPredictions(ConvAssistWordPredictor wordPredicto
}
catch (Exception letters)
{
- Log.Exception("ConvAssist Predict letters " + letters);
+ _logger.LogError(letters, "ConvAssist Predict letters");
}
return retVal;
}
diff --git a/src/Libraries/ACATCore/AbbreviationsManagement/Abbreviation.cs b/src/Libraries/ACATCore/AbbreviationsManagement/Abbreviation.cs
index b0d7c9df..82ea4dca 100644
--- a/src/Libraries/ACATCore/AbbreviationsManagement/Abbreviation.cs
+++ b/src/Libraries/ACATCore/AbbreviationsManagement/Abbreviation.cs
@@ -15,6 +15,7 @@
////////////////////////////////////////////////////////////////////////////
using ACAT.Core.Utility;
+using Microsoft.Extensions.Logging;
using System;
using System.Text.RegularExpressions;
@@ -22,6 +23,8 @@ namespace ACAT.Core.AbbreviationsManagement
{
public class Abbreviation : IDisposable
{
+ private readonly ILogger _logger;
+
///
/// Has this object been disposed
///
@@ -33,8 +36,9 @@ public class Abbreviation : IDisposable
/// abbreviation
/// abbreviation expansion
/// mode of expansion - speech or text
- public Abbreviation(String mnemonic, String expansion, String mode)
+ public Abbreviation(String mnemonic, String expansion, String mode, ILogger logger = null)
{
+ _logger = logger;
Mode = Convert(mode);
init(mnemonic, expansion, Mode);
}
@@ -45,8 +49,9 @@ public Abbreviation(String mnemonic, String expansion, String mode)
/// abbreviation
/// abbreviation expansion
/// mode of expansion - speech or text
- public Abbreviation(String mnemonic, String expansion, AbbreviationMode mode)
+ public Abbreviation(String mnemonic, String expansion, AbbreviationMode mode, ILogger logger = null)
{
+ _logger = logger;
init(mnemonic, expansion, mode);
}
@@ -90,7 +95,7 @@ public static AbbreviationMode Convert(String mode)
}
catch (Exception ex)
{
- Log.Exception(ex);
+ _logger?.LogError(ex, "Exception converting abbreviation mode");
}
return retVal;
diff --git a/src/Libraries/ACATCore/AbbreviationsManagement/Abbreviations.cs b/src/Libraries/ACATCore/AbbreviationsManagement/Abbreviations.cs
index 3d8d39ac..d2e5e13e 100644
--- a/src/Libraries/ACATCore/AbbreviationsManagement/Abbreviations.cs
+++ b/src/Libraries/ACATCore/AbbreviationsManagement/Abbreviations.cs
@@ -14,6 +14,7 @@
using ACAT.Core.UserManagement;
using ACAT.Core.Utility;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.IO;
@@ -24,6 +25,8 @@ namespace ACAT.Core.AbbreviationsManagement
{
public class Abbreviations : IDisposable
{
+ private readonly ILogger _logger;
+
///
/// Name of the abbreviations file
///
@@ -54,6 +57,14 @@ public class Abbreviations : IDisposable
///
private bool _disposed;
+ ///
+ /// Constructor
+ ///
+ public Abbreviations(ILogger logger = null)
+ {
+ _logger = logger;
+ }
+
///
/// Gets the sorted list of abbreviations
///
@@ -168,7 +179,7 @@ public bool Load(String abbreviationsFile = null)
}
catch (Exception ex)
{
- Log.Exception("Error processing abbreviations file " + abbreviationsFile + ". Exception: " + ex);
+ _logger?.LogError(ex, "Error processing abbreviations file {AbbreviationsFile}", abbreviationsFile);
retVal = false;
}
diff --git a/src/Libraries/ACATCore/AbbreviationsManagement/AbbreviationsManager.cs b/src/Libraries/ACATCore/AbbreviationsManagement/AbbreviationsManager.cs
index 67b2382e..2a2c9a41 100644
--- a/src/Libraries/ACATCore/AbbreviationsManagement/AbbreviationsManager.cs
+++ b/src/Libraries/ACATCore/AbbreviationsManagement/AbbreviationsManager.cs
@@ -15,12 +15,15 @@
using ACAT.Core.PanelManagement;
using ACAT.Core.PanelManagement.Common;
using ACAT.Core.Utility;
+using Microsoft.Extensions.Logging;
using System;
namespace ACAT.Core.AbbreviationsManagement
{
public class AbbreviationsManager : IDisposable
{
+ private readonly ILogger _logger;
+
///
/// Static singleton instance
///
@@ -34,8 +37,9 @@ public class AbbreviationsManager : IDisposable
///
/// Initializes a new instance of the class.
///
- private AbbreviationsManager()
+ private AbbreviationsManager(ILogger logger = null)
{
+ _logger = logger;
Context.EvtCultureChanged += Context_EvtCultureChanged;
}
diff --git a/src/Libraries/ACATCore/ActuatorManagement/ActuatorBase.cs b/src/Libraries/ACATCore/ActuatorManagement/ActuatorBase.cs
index 064b9667..011834fc 100644
--- a/src/Libraries/ACATCore/ActuatorManagement/ActuatorBase.cs
+++ b/src/Libraries/ACATCore/ActuatorManagement/ActuatorBase.cs
@@ -23,6 +23,7 @@
using ACAT.Core.PanelManagement.Interfaces;
using ACAT.Core.PreferencesManagement.Interfaces;
using ACAT.Core.Utility;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
@@ -38,6 +39,8 @@ namespace ACAT.Core.ActuatorManagement
///
public abstract class ActuatorBase : IActuator
{
+ private readonly ILogger _logger;
+
///
/// Used to invoke methods/properties in the actuator
///
@@ -57,8 +60,9 @@ public abstract class ActuatorBase : IActuator
///
/// Initializes a new instance of the ActuatorBase class
///
- protected ActuatorBase()
+ protected ActuatorBase(ILogger logger = null)
{
+ _logger = logger;
Enabled = false;
_switches = new Dictionary();
actuatorState = State.Stopped;
diff --git a/src/Libraries/ACATCore/ActuatorManagement/ActuatorEx.cs b/src/Libraries/ACATCore/ActuatorManagement/ActuatorEx.cs
index 24bdf582..91ceda9c 100644
--- a/src/Libraries/ACATCore/ActuatorManagement/ActuatorEx.cs
+++ b/src/Libraries/ACATCore/ActuatorManagement/ActuatorEx.cs
@@ -18,6 +18,7 @@
using ACAT.Core.ActuatorManagement.Interfaces;
using ACAT.Core.Utility;
+using Microsoft.Extensions.Logging;
using System;
using System.ComponentModel;
using System.Threading;
@@ -36,6 +37,8 @@ namespace ACAT.Core.ActuatorManagement
///
internal class ActuatorEx
{
+ private readonly ILogger _logger;
+
///
/// The inner acutator object
///
@@ -79,8 +82,9 @@ internal class ActuatorEx
/// Initializes an instance of the class
///
/// The inner actuator object
- public ActuatorEx(IActuator src)
+ public ActuatorEx(IActuator src, ILogger logger = null)
{
+ _logger = logger;
SourceActuator = src;
}
diff --git a/src/Libraries/ACATCore/ActuatorManagement/ActuatorManager.cs b/src/Libraries/ACATCore/ActuatorManagement/ActuatorManager.cs
index 60f23987..a3a223df 100644
--- a/src/Libraries/ACATCore/ActuatorManagement/ActuatorManager.cs
+++ b/src/Libraries/ACATCore/ActuatorManagement/ActuatorManager.cs
@@ -26,6 +26,7 @@
using ACAT.Core.PreferencesManagement;
using ACAT.Core.UserManagement;
using ACAT.Core.Utility;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -45,6 +46,8 @@ namespace ACAT.Core.ActuatorManagement
///
public class ActuatorManager : IDisposable
{
+ private readonly ILogger _logger;
+
///
/// The base directory under which all the actuator Dll's are
/// located.
@@ -118,9 +121,10 @@ public class ActuatorManager : IDisposable
///
/// Prevents a default instance of ActuatorManager class from being created
///
- //private ActuatorManager()
- //{
- // _activeSwitches = new Dictionary();
+ private ActuatorManager(ILogger logger = null)
+ {
+ _logger = logger;
+ _activeSwitches = new Dictionary();
// _nonActuateSwitches = new Dictionary();
// _syncObjectSwitches = new object();
//}
diff --git a/src/Libraries/ACATCore/ActuatorManagement/ActuatorSwitchBase.cs b/src/Libraries/ACATCore/ActuatorManagement/ActuatorSwitchBase.cs
index 888cf9eb..2419f73e 100644
--- a/src/Libraries/ACATCore/ActuatorManagement/ActuatorSwitchBase.cs
+++ b/src/Libraries/ACATCore/ActuatorManagement/ActuatorSwitchBase.cs
@@ -16,6 +16,7 @@
using ACAT.Core.ActuatorManagement.Interfaces;
using ACAT.Core.ActuatorManagement.Settings;
using ACAT.Core.Utility;
+using Microsoft.Extensions.Logging;
using System;
using System.Diagnostics;
using System.IO;
@@ -31,6 +32,8 @@ namespace ACAT.Core.ActuatorManagement
///
public class ActuatorSwitchBase : IActuatorSwitch
{
+ private readonly ILogger _logger;
+
///
/// The command verb to be used for a switch that
/// is used for selection
@@ -72,8 +75,9 @@ public class ActuatorSwitchBase : IActuatorSwitch
///
/// Initializes the Switch object
///
- public ActuatorSwitchBase()
+ public ActuatorSwitchBase(ILogger logger = null)
{
+ _logger = logger;
_isActive = false;
Name = String.Empty;
Source = String.Empty;
@@ -85,8 +89,9 @@ public ActuatorSwitchBase()
/// Initializes the switch object from the passed switch object
///
/// Source switch object
- public ActuatorSwitchBase(IActuatorSwitch switchObj)
+ public ActuatorSwitchBase(IActuatorSwitch switchObj, ILogger logger = null)
{
+ _logger = logger;
Name = switchObj.Name;
Description = switchObj.Description;
Source = switchObj.Source;
diff --git a/src/Libraries/ACATCore/ActuatorManagement/Actuators.cs b/src/Libraries/ACATCore/ActuatorManagement/Actuators.cs
index ea939f81..77b92f5a 100644
--- a/src/Libraries/ACATCore/ActuatorManagement/Actuators.cs
+++ b/src/Libraries/ACATCore/ActuatorManagement/Actuators.cs
@@ -6,6 +6,7 @@
using ACAT.Core.ActuatorManagement.Settings;
using ACAT.Core.Utility;
using ACAT.Core.Utility.TypeLoader;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.IO;
@@ -22,6 +23,8 @@ namespace ACAT.Core.ActuatorManagement
///
public class Actuators : IDisposable
{
+ private readonly ILogger _logger;
+
///
/// If one of the dll found has an error with the certificate
///
@@ -52,8 +55,9 @@ public class Actuators : IDisposable
///
/// Initializes the Actuator object
///
- public Actuators()
+ public Actuators(ILogger logger = null)
{
+ _logger = logger;
//_actuatorsTypeCache = new Dictionary();
_actuatorsEx = new List();
_actuators = new List();
diff --git a/src/Libraries/ACATCore/ActuatorManagement/BaseActuators/KeyboardSwitch.cs b/src/Libraries/ACATCore/ActuatorManagement/BaseActuators/KeyboardSwitch.cs
index d421a2b2..26227ca0 100644
--- a/src/Libraries/ACATCore/ActuatorManagement/BaseActuators/KeyboardSwitch.cs
+++ b/src/Libraries/ACATCore/ActuatorManagement/BaseActuators/KeyboardSwitch.cs
@@ -16,6 +16,7 @@
using ACAT.Core.ActuatorManagement.Interfaces;
using ACAT.Core.ActuatorManagement.Settings;
using ACAT.Core.Utility;
+using Microsoft.Extensions.Logging;
namespace ACAT.Core.ActuatorManagement.BaseActuators
{
@@ -27,6 +28,11 @@ namespace ACAT.Core.ActuatorManagement.BaseActuators
///
internal class KeyboardSwitch : ActuatorSwitchBase
{
+ ///
+ /// Logger instance for this class
+ ///
+ private readonly ILogger _logger;
+
///
/// Has this object been disposed?
///
@@ -35,17 +41,19 @@ internal class KeyboardSwitch : ActuatorSwitchBase
///
/// Initializes the keyboardswitch object
///
- public KeyboardSwitch()
+ public KeyboardSwitch(ILogger logger)
{
+ _logger = logger;
}
///
/// Initialize the keyboard actuator object
///
///
- public KeyboardSwitch(IActuatorSwitch switchObj)
+ public KeyboardSwitch(IActuatorSwitch switchObj, ILogger logger)
: base(switchObj)
{
+ _logger = logger;
}
///
@@ -82,7 +90,7 @@ protected override void Dispose(bool disposing)
{
try
{
- Log.Verbose();
+ _logger.LogTrace("Disposing KeyboardSwitch");
if (disposing)
{
diff --git a/src/Libraries/ACATCore/ActuatorManagement/UI/SwitchCommandMapForm.cs b/src/Libraries/ACATCore/ActuatorManagement/UI/SwitchCommandMapForm.cs
index 6bbebe46..31748d97 100644
--- a/src/Libraries/ACATCore/ActuatorManagement/UI/SwitchCommandMapForm.cs
+++ b/src/Libraries/ACATCore/ActuatorManagement/UI/SwitchCommandMapForm.cs
@@ -14,6 +14,7 @@
using ACAT.Core.PanelManagement;
using ACAT.Core.Utility;
using ACATResources;
+using Microsoft.Extensions.Logging;
using System;
using System.Windows.Forms;
@@ -21,6 +22,11 @@ namespace ACAT.Core.ActuatorManagement
{
public partial class SwitchCommandMapForm : Form
{
+ ///
+ /// Logger instance for this class
+ ///
+ private readonly ILogger _logger;
+
///
/// Aspect ratio of form at design time
///
@@ -36,8 +42,9 @@ public partial class SwitchCommandMapForm : Form
///
private bool _wrapText = true;
- public SwitchCommandMapForm()
+ public SwitchCommandMapForm(ILogger logger)
{
+ _logger = logger;
InitializeComponent();
SelectedCommand = String.Empty;
@@ -123,7 +130,7 @@ private void refreshDataGridView()
{
if (CommandManager.Instance?.AppCommandTable?.CmdDescriptors == null)
{
- Log.Debug("CommandManager or AppCommandTable not initialized");
+ _logger.LogDebug("CommandManager or AppCommandTable not initialized");
return;
}
diff --git a/src/Libraries/ACATCore/ActuatorManagement/WinsockActuators/WinsockClientActuator/WinsockClientActuatorBase.cs b/src/Libraries/ACATCore/ActuatorManagement/WinsockActuators/WinsockClientActuator/WinsockClientActuatorBase.cs
index 2b80b9a0..1498ce6e 100644
--- a/src/Libraries/ACATCore/ActuatorManagement/WinsockActuators/WinsockClientActuator/WinsockClientActuatorBase.cs
+++ b/src/Libraries/ACATCore/ActuatorManagement/WinsockActuators/WinsockClientActuator/WinsockClientActuatorBase.cs
@@ -18,6 +18,7 @@
using ACAT.Core.ActuatorManagement.Interfaces;
using ACAT.Core.Utility;
+using Microsoft.Extensions.Logging;
using System;
using System.Text;
using System.Threading;
@@ -36,6 +37,11 @@ namespace ACAT.Core.ActuatorManagement.WinsockActuators.WinsockClientActuator
///
public class WinsockClientActuatorBase : ActuatorBase
{
+ ///
+ /// Logger instance for this class
+ ///
+ private readonly ILogger _logger;
+
///
/// Socket client class that handles the client connection
///
@@ -70,8 +76,9 @@ public class WinsockClientActuatorBase : ActuatorBase
///
/// Initializes a new instance of the class.
///
- public WinsockClientActuatorBase()
+ public WinsockClientActuatorBase(ILogger logger)
{
+ _logger = logger;
socketClient = null;
}
@@ -150,7 +157,7 @@ protected override void Dispose(bool disposing)
{
try
{
- Log.Verbose();
+ _logger.LogTrace("Disposing WinsockClientActuatorBase");
_quitConnect = true;
_evtConnectRetry.Set();
@@ -191,7 +198,7 @@ protected virtual void onConnected(System.Net.IPAddress address)
protected virtual void onDataReceived(System.Net.IPAddress address, byte[] data)
{
string strData = Encoding.ASCII.GetString(data, 0, data.Length);
- Log.Debug("Received data: " + strData);
+ _logger.LogDebug("Received data: {Data}", strData);
// parse the string, find the switch that causes the trigger
IActuatorSwitch switchObj = WinsockCommon.parseAndGetSwitch(strData, Switches, CreateSwitch);
@@ -225,7 +232,7 @@ protected int Send(string msg)
}
catch (Exception ex)
{
- Log.Exception(ex);
+ _logger.LogError(ex, "Error sending message");
}
return -1;
}
@@ -259,7 +266,7 @@ protected void triggerEvent(IActuatorSwitch switchObj)
/// Tcp/ip server address
private void _socketClient_OnClientConnected(System.Net.IPAddress address)
{
- Log.Debug("Connected to" + address);
+ _logger.LogDebug("Connected to {Address}", address);
onConnected(address);
}
@@ -269,7 +276,7 @@ private void _socketClient_OnClientConnected(System.Net.IPAddress address)
/// Address of the tcp/ip server
private void _socketClient_OnClientConnectionClosed(System.Net.IPAddress addr)
{
- Log.Debug("Disconnected from " + addr);
+ _logger.LogDebug("Disconnected from {Address}", addr);
closeClientSocket(socketClient);
socketClient = null;
_evtConnectRetry.Set();
@@ -312,19 +319,19 @@ private void connectProc()
{
try
{
- Log.Debug("Trying to connecting to tcp/ip server");
+ _logger.LogDebug("Trying to connecting to tcp/ip server");
socketClient ??= createSocketClient();
if (socketClient != null)
{
if (!socketClient.Connect())
{
- Log.Debug("Tcp/ip server not detected. Will retry...");
+ _logger.LogDebug("Tcp/ip server not detected. Will retry...");
Thread.Sleep(waitInterval);
}
else
{
- Log.Debug("Successfully connected to tcp/ip server");
+ _logger.LogDebug("Successfully connected to tcp/ip server");
_evtConnectRetry.WaitOne();
_evtConnectRetry.Reset();
}
@@ -336,11 +343,11 @@ private void connectProc()
}
catch (Exception ex)
{
- Log.Exception("Error connecting to server " + ex);
+ _logger.LogError(ex, "Error connecting to server");
}
}
- Log.Debug("Thread exited");
+ _logger.LogDebug("Thread exited");
}
///
diff --git a/src/Libraries/ACATCore/ActuatorManagement/WinsockActuators/WinsockCommon.cs b/src/Libraries/ACATCore/ActuatorManagement/WinsockActuators/WinsockCommon.cs
index 308f81d2..eb5709e3 100644
--- a/src/Libraries/ACATCore/ActuatorManagement/WinsockActuators/WinsockCommon.cs
+++ b/src/Libraries/ACATCore/ActuatorManagement/WinsockActuators/WinsockCommon.cs
@@ -15,6 +15,7 @@
using ACAT.Core.ActuatorManagement.Interfaces;
using ACAT.Core.Utility;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
@@ -28,6 +29,13 @@ namespace ACAT.Core.ActuatorManagement.WinsockActuators
///
internal class WinsockCommon
{
+ private static ILogger _logger;
+
+ public static void SetLogger(ILogger logger)
+ {
+ _logger = logger;
+ }
+
public delegate IActuatorSwitch CreateSwitchDelegate(IActuatorSwitch s);
///
@@ -45,8 +53,7 @@ public static SwitchAction getSwitchAction(string action)
}
catch (Exception e)
{
- Log.Warn("Image switch, invalid action specified " + action);
- Log.Exception(e);
+ _logger?.LogWarning(e, "Image switch, invalid action specified {Action}", action);
}
return retVal;
@@ -154,7 +161,7 @@ public static long parseLong(string val)
}
catch (Exception e)
{
- Log.Exception(e);
+ _logger?.LogError(e, "Error parsing long value {Value}", val);
}
return retVal;
@@ -178,7 +185,7 @@ private static IActuatorSwitch getSwitchForGesture(
var imageSwitch = switchObj;
if (string.Compare(imageSwitch.Source, gesture, true) == 0)
{
- Log.Debug("Found switch object " + switchObj.Name + " for gesture" + gesture);
+ _logger?.LogDebug("Found switch object {SwitchName} for gesture {Gesture}", switchObj.Name, gesture);
return createSwitchDel(switchObj);
}
}
diff --git a/src/Libraries/ACATCore/ActuatorManagement/WinsockActuators/WinsockServerActuator/ClientConnHandler.cs b/src/Libraries/ACATCore/ActuatorManagement/WinsockActuators/WinsockServerActuator/ClientConnHandler.cs
index 6728784f..93587031 100644
--- a/src/Libraries/ACATCore/ActuatorManagement/WinsockActuators/WinsockServerActuator/ClientConnHandler.cs
+++ b/src/Libraries/ACATCore/ActuatorManagement/WinsockActuators/WinsockServerActuator/ClientConnHandler.cs
@@ -13,6 +13,7 @@
////////////////////////////////////////////////////////////////////////////
using ACAT.Core.Utility;
+using Microsoft.Extensions.Logging;
using System;
using System.IO;
using System.Net;
@@ -28,6 +29,7 @@ namespace ACAT.Core.ActuatorManagement.WinsockActuators.WinsockServerActuator
///
internal class ClientConnHandler : IDisposable
{
+ private readonly ILogger _logger;
public ConnectionStatus ClientConnectionStatus = ConnectionStatus.Disconnected;
public string ID = string.Empty;
public Thread WorkerThread;
@@ -45,8 +47,9 @@ internal class ClientConnHandler : IDisposable
/// Initializes a instance of the class
///
/// The TcpClient connection that is connected to a client.
- public ClientConnHandler(TcpClient client)
+ public ClientConnHandler(TcpClient client, ILogger logger)
{
+ _logger = logger;
tcpClient = client;
clientStream = tcpClient.GetStream();
ID = Guid.NewGuid().ToString();
@@ -58,7 +61,7 @@ public ClientConnHandler(TcpClient client)
}
catch (Exception ex)
{
- Log.Exception(ex);
+ _logger.LogError(ex, "Error getting remote endpoint");
}
OnClientMsgReceived += ClientConnHandler_OnClientMsgReceived;
@@ -166,7 +169,7 @@ public bool SendToClient(byte[] message, int count)
}
catch (Exception e)
{
- Log.Exception(e);
+ _logger.LogError(e, "Error sending to client");
return false;
}
}
@@ -190,12 +193,12 @@ public void WorkerThreadMethod()
{
// blocks until a client sends a message
bytesRead = clientStream.Read(message, 0, ReadBufferSize);
- Log.Debug("Returned from read. Bytes read: " + bytesRead);
+ _logger.LogDebug("Returned from read. Bytes read: {BytesRead}", bytesRead);
}
catch (Exception e)
{
// Probably a socket exception.
- Log.Error("SERVER: ClientConnHandler, exception reading stream " + e.StackTrace);
+ _logger.LogError(e, "SERVER: ClientConnHandler, exception reading stream");
break;
}
@@ -206,10 +209,10 @@ public void WorkerThreadMethod()
}
// Data has been received, let's process it.
- Log.Debug("Calling OnClientMsgReceived");
+ _logger.LogDebug("Calling OnClientMsgReceived");
OnClientMsgReceived?.Invoke(message, bytesRead);
- Log.Debug("Returned from OnClientMsgReceived");
+ _logger.LogDebug("Returned from OnClientMsgReceived");
}
// Out of the WorkerThreadMethod loop... time to close stuff down.
@@ -271,7 +274,7 @@ private void ClientConnHandler_OnClientMsgReceived(byte[] message, int count)
/// Length of the data
private void HandleClientMessage(byte[] messageFromClient, int count)
{
- Log.Debug("Received " + count + " bytes");
+ _logger.LogDebug("Received {Count} bytes", count);
lock (_lockObj)
{
int offset = 0;
@@ -291,9 +294,9 @@ private void HandleClientMessage(byte[] messageFromClient, int count)
Data = _memoryStream.ToArray()
};
- Log.Debug(string.Format("Entire packet received. Calling threadpool for data received"));
+ _logger.LogDebug("Entire packet received. Calling threadpool for data received");
ThreadPool.QueueUserWorkItem(Worker, item);
- Log.Debug(string.Format("Returned from QueueUserWorkItem"));
+ _logger.LogDebug("Returned from QueueUserWorkItem");
_memoryStream = new MemoryStream();
}
@@ -324,7 +327,7 @@ private void SocketServer_OnServerShutdown()
}
catch (Exception ex)
{
- Log.Exception(ex);
+ _logger.LogError(ex, "Error aborting worker thread");
}
}
diff --git a/src/Libraries/ACATCore/AgentManagement/AgentBase.cs b/src/Libraries/ACATCore/AgentManagement/AgentBase.cs
index c430f257..bd5d0eb9 100644
--- a/src/Libraries/ACATCore/AgentManagement/AgentBase.cs
+++ b/src/Libraries/ACATCore/AgentManagement/AgentBase.cs
@@ -11,6 +11,7 @@
using ACAT.Core.PanelManagement.Common;
using ACAT.Core.PreferencesManagement.Interfaces;
using ACAT.Core.Utility;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -25,6 +26,11 @@ namespace ACAT.Core.AgentManagement
///
public abstract class AgentBase : IApplicationAgent
{
+ ///
+ /// Logger instance for this class
+ ///
+ private readonly ILogger _logger;
+
///
/// Used to invoke methods/properties in the agent
///
@@ -58,8 +64,9 @@ public abstract class AgentBase : IApplicationAgent
///
/// Initializes a new instance of the class.
///
- protected AgentBase()
+ protected AgentBase(ILogger logger)
{
+ _logger = logger;
_name = Descriptor.Name;
_invoker = new ExtensionInvoker(this);
}
@@ -399,11 +406,11 @@ protected void setTextInterface(TextControlAgentBase textInterface = null)
{
if (_textInterface != null)
{
- Log.Debug("Disposing " + _textInterface.GetType().Name);
+ _logger.LogDebug("Disposing {TextInterfaceType}", _textInterface.GetType().Name);
_textInterface.Dispose();
}
- Log.Debug("Setting textinterface to " + ((textInterface != null) ? textInterface.GetType().Name : "null"));
+ _logger.LogDebug("Setting textinterface to {TextInterfaceType}", ((textInterface != null) ? textInterface.GetType().Name : "null"));
_textInterface = textInterface ?? _nullTextInterface;
AgentManager.Instance.TextControlAgent = _textInterface;
diff --git a/src/Libraries/ACATCore/AgentManagement/AgentUtils.cs b/src/Libraries/ACATCore/AgentManagement/AgentUtils.cs
index cb053243..b4f608b8 100644
--- a/src/Libraries/ACATCore/AgentManagement/AgentUtils.cs
+++ b/src/Libraries/ACATCore/AgentManagement/AgentUtils.cs
@@ -6,6 +6,7 @@
////////////////////////////////////////////////////////////////////////////
using ACAT.Core.Utility;
+using Microsoft.Extensions.Logging;
using System;
using System.Windows.Automation;
using System.Windows.Forms;
@@ -17,6 +18,12 @@ namespace ACAT.Core.AgentManagement
///
public class AgentUtils
{
+ private static ILogger _logger;
+
+ public static void SetLogger(ILogger logger)
+ {
+ _logger = logger;
+ }
///
/// Finds a descendent of the focused element that has the specified
/// className, controlType and automationID
@@ -75,8 +82,8 @@ public static AutomationElement GetElementOrAncestorByAutomationId(AutomationEle
while (parent != null)
{
- Log.Debug("parent.ClassName: " + parent.Current.ClassName + ", parent.ControlType: " +
- parent.Current.ControlType.ProgrammaticName + ", parent.AutoId: " + parent.Current.AutomationId);
+ _logger?.LogDebug("parent.ClassName: {ClassName}, parent.ControlType: {ControlType}, parent.AutoId: {AutoId}",
+ parent.Current.ClassName, parent.Current.ControlType.ProgrammaticName, parent.Current.AutomationId);
if (String.Compare(parent.Current.ClassName, className, true) == 0 &&
String.Compare(parent.Current.ControlType.ProgrammaticName, controlType, true) == 0 &&
@@ -147,7 +154,8 @@ public static void InsertTextIntoElement(AutomationElement element, string value
{
if (!element.Current.IsEnabled || !element.Current.IsKeyboardFocusable)
{
- Log.Debug("Control not enabled or keyboard focusable. AutomationID " + element.Current.AutomationId);
+ _logger?.LogDebug("Control not enabled or keyboard focusable. AutomationID {AutomationId}",
+ element.Current.AutomationId);
return;
}
@@ -164,7 +172,7 @@ public static void InsertTextIntoElement(AutomationElement element, string value
}
catch (Exception ex)
{
- Log.Exception(ex.ToString());
+ _logger?.LogError(ex, "Error inserting text into element");
}
}
diff --git a/src/Libraries/ACATCore/AgentManagement/GenericAppAgentBase.cs b/src/Libraries/ACATCore/AgentManagement/GenericAppAgentBase.cs
index 2ba5b78b..b6df6013 100644
--- a/src/Libraries/ACATCore/AgentManagement/GenericAppAgentBase.cs
+++ b/src/Libraries/ACATCore/AgentManagement/GenericAppAgentBase.cs
@@ -7,6 +7,7 @@
using ACAT.Core.AgentManagement.TextControlAgents;
using ACAT.Core.Utility;
+using Microsoft.Extensions.Logging;
using System;
using System.Windows.Automation;
@@ -46,7 +47,7 @@ public abstract class GenericAppAgentBase : AgentBase
/// was this handled?
public override void OnFocusChanged(WindowActivityMonitorInfo monitorInfo, ref bool handled)
{
- Log.Verbose();
+ _logger.LogTrace("OnFocusChanged");
disposeAndCreateTextInterface(monitorInfo);
triggerTextChanged(appTextInterface);
@@ -77,7 +78,7 @@ protected virtual TextControlAgentBase createEditControlTextInterface(
AutomationElement focusedElement,
ref bool handled)
{
- Log.Verbose();
+ _logger.LogTrace("createEditControlTextInterface");
return new EditTextControlAgent(handleMain, focusedElement, ref handled);
}
@@ -114,10 +115,10 @@ protected override void OnDispose()
/// event arg
private void _textInterface_EvtTextChanged(object sender, TextChangedEventArgs e)
{
- Log.Verbose();
+ _logger.LogTrace("_textInterface_EvtTextChanged");
if (e.TextInterface != null)
{
- Log.Debug("Calling triggertextchanged");
+ _logger.LogDebug("Calling triggertextchanged");
triggerTextChanged(e.TextInterface);
}
}
@@ -134,7 +135,7 @@ private TextControlAgentBase createEditControlTextInterface(
AutomationElement focusedElement)
{
bool handled = false;
- Log.Debug("base.createEditControlTextInterface()");
+ _logger.LogDebug("base.createEditControlTextInterface()");
var textInterface = createEditControlTextInterface(handleMain, focusedElement, ref handled);
if (handled)
{
diff --git a/src/Libraries/ACATCore/AgentManagement/Keyboard.cs b/src/Libraries/ACATCore/AgentManagement/Keyboard.cs
index b9780bf9..debd8194 100644
--- a/src/Libraries/ACATCore/AgentManagement/Keyboard.cs
+++ b/src/Libraries/ACATCore/AgentManagement/Keyboard.cs
@@ -7,6 +7,7 @@
using ACAT.Core.AgentManagement.Interfaces;
using ACAT.Core.Utility;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -21,6 +22,11 @@ namespace ACAT.Core.AgentManagement
///
public class Keyboard : IKeyboard
{
+ ///
+ /// Logger instance for this class
+ ///
+ private readonly ILogger _logger;
+
///
/// Windows keyboard layout
///
@@ -37,6 +43,11 @@ private enum Flags
KEYEVENTF_KEYUP = 0x0002
}
+ public Keyboard(ILogger logger)
+ {
+ _logger = logger;
+ }
+
///
/// Disposes resources
///
@@ -56,7 +67,7 @@ public void Dispose()
/// modifier key
public void ExtendedKeyDown(Keys key)
{
- Log.Debug(key.ToString());
+ _logger.LogDebug("ExtendedKeyDown: {Key}", key.ToString());
User32Interop.keybd_event((byte)key, 0xAA, 0, UIntPtr.Zero);
}
@@ -67,7 +78,7 @@ public void ExtendedKeyDown(Keys key)
/// modifier key
public void ExtendedKeyUp(Keys key)
{
- Log.Debug(key.ToString());
+ _logger.LogDebug("ExtendedKeyUp: {Key}", key.ToString());
User32Interop.keybd_event((byte)key, 0xAA, (uint)Flags.KEYEVENTF_KEYUP, UIntPtr.Zero);
}
@@ -361,11 +372,11 @@ private bool shiftNeeded(char c)
Log.Debug("virtualKey for [" + c + "] is " + virtualKey);
if ((virtualKey & 0x100) == 0x100)
{
- Log.Debug("Shift needs to be pressed for [" + c + "]");
+ _logger.LogDebug("Shift needs to be pressed for [{Char}]", c);
return true;
}
- Log.Debug("Shift does not need to be pressed for [" + c + "]");
+ _logger.LogDebug("Shift does not need to be pressed for [{Char}]", c);
return false;
}
diff --git a/src/Libraries/ACATCore/Audit/AuditLog.cs b/src/Libraries/ACATCore/Audit/AuditLog.cs
index f8dcf464..7eb8258f 100644
--- a/src/Libraries/ACATCore/Audit/AuditLog.cs
+++ b/src/Libraries/ACATCore/Audit/AuditLog.cs
@@ -6,6 +6,7 @@
////////////////////////////////////////////////////////////////////////////
using ACAT.Core.Utility;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.IO;
@@ -20,6 +21,8 @@ namespace ACAT.Core.Audit
///
public class AuditLog
{
+ private static ILogger _logger;
+
///
/// Full path to the log file
///
@@ -59,6 +62,8 @@ public class AuditLog
///
static AuditLog()
{
+ _logger = LoggerFactory.Create(builder => builder.AddConsole()).CreateLogger();
+
string logFileFolder = FileUtils.GetLogsDir();
loadFilters();
@@ -67,7 +72,7 @@ static AuditLog()
{
if (!Directory.Exists(logFileFolder))
{
- Log.Debug("Creating log directory.");
+ _logger.LogDebug("Creating log directory.");
Directory.CreateDirectory(logFileFolder);
}
}
@@ -89,7 +94,7 @@ static AuditLog()
LogFileFullPath = Path.Combine(logFileFolder, Path.GetFileNameWithoutExtension(LogFileName) + CoreGlobals.LogFileSuffix + Path.GetExtension(LogFileName));
- Log.Debug("LogFileFullPath=" + LogFileFullPath);
+ _logger.LogDebug("LogFileFullPath=" + LogFileFullPath);
/*
objMutex = new Mutex(false, MutexName);
diff --git a/src/Libraries/ACATCore/PanelManagement/Common/ScannerCommon.cs b/src/Libraries/ACATCore/PanelManagement/Common/ScannerCommon.cs
index 47234d8b..314506a3 100644
--- a/src/Libraries/ACATCore/PanelManagement/Common/ScannerCommon.cs
+++ b/src/Libraries/ACATCore/PanelManagement/Common/ScannerCommon.cs
@@ -20,6 +20,7 @@
using ACAT.Core.WidgetManagement.Interfaces;
using ACAT.Core.WidgetManagement.Layout;
using ACAT.Core.Widgets;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Drawing;
@@ -62,6 +63,11 @@ public class ScannerCommon : IDisposable, IPanelCommon
///
private readonly SyncLock _syncLock;
+ ///
+ /// Logger instance
+ ///
+ private readonly ILogger _logger;
+
///
/// The animation manager object. Manages all animations
///
@@ -137,8 +143,9 @@ public class ScannerCommon : IDisposable, IPanelCommon
/// Initializes a new instance of the class
///
/// The scanner Form object
- public ScannerCommon(IScannerPanel iScannerPanel)
+ public ScannerCommon(IScannerPanel iScannerPanel, ILogger logger = null)
{
+ _logger = logger;
ScannerForm = iScannerPanel.Form;
StartupArg = null;
@@ -432,7 +439,7 @@ public void HideScanner()
///
public bool Initialize(StartupArg startupArg)
{
- Log.Debug("Entered from Initialize");
+ _logger?.LogDebug("Entered from Initialize");
Context.AppPanelManager.EvtPanelPreShow += AppPanelManager_EvtPanelPreShow;
@@ -501,7 +508,7 @@ public bool Initialize(StartupArg startupArg)
Context.AppPanelManager.EvtCalibrationStartNotify += AppPanelManager_EvtCalibrationStartNotify;
Context.AppPanelManager.EvtCalibrationEndNotify += AppPanelManager_EvtCalibrationEndNotify;
- Log.Debug("Returning from Initialize " + retVal);
+ _logger?.LogDebug("Returning from Initialize {RetVal}", retVal);
return retVal;
}
@@ -543,7 +550,7 @@ public void OnClosing()
}
catch (Exception ex)
{
- Log.Exception(ex);
+ _logger?.LogError(ex, "Exception in OnClosing");
}
}
@@ -586,29 +593,29 @@ public void OnFormClosing(FormClosingEventArgs e)
CoreGlobals.AppPreferences.EvtPreferencesChanged -= AppPreferences_EvtPreferencesChanged;
- Log.Debug(ScannerForm.Name + ", _syncObj.Status: " + _syncLock.Status + ", hashcode: " + _syncLock.GetHashCode());
+ _logger?.LogDebug("{FormName}, _syncObj.Status: {Status}, hashcode: {HashCode}", ScannerForm.Name, _syncLock.Status, _syncLock.GetHashCode());
if (_syncLock.Status != SyncLock.StatusValues.None)
{
- Log.Debug(ScannerForm.Name + ", _syncObj.Status: " + _syncLock.Status + ", form already closed. returning");
+ _logger?.LogDebug("{FormName}, _syncObj.Status: {Status}, form already closed. returning", ScannerForm.Name, _syncLock.Status);
return;
}
- Log.Debug(ScannerForm.Name + ", _syncObj.Status: " + _syncLock.Status + ", Will continue closing");
+ _logger?.LogDebug("{FormName}, _syncObj.Status: {Status}, Will continue closing", ScannerForm.Name, _syncLock.Status);
- Log.Debug("Setting _syncLock.Status to CLOSING " + ScannerForm.Name);
+ _logger?.LogDebug("Setting _syncLock.Status to CLOSING {FormName}", ScannerForm.Name);
_syncLock.Status = SyncLock.StatusValues.Closing;
if (_animationManager != null)
{
- Log.Verbose("Before animationmangoer.stop");
+ _logger?.LogTrace("Before animationmangoer.stop");
_animationManager.Stop();
- Log.Verbose("After animationmangoer.stop");
+ _logger?.LogTrace("After animationmangoer.stop");
}
- Log.Verbose("Unsubscribe to EvtHeartbeat for " + ScannerForm.Name);
+ _logger?.LogTrace("Unsubscribe to EvtHeartbeat for {FormName}", ScannerForm.Name);
WindowActivityMonitor.EvtWindowMonitorHeartbeat -= WindowActivityMonitor_EvtWindowMonitorHeartbeat;
- Log.Verbose("Unsubscribe to EvtHeartbeat DONE for " + ScannerForm.Name);
+ _logger?.LogTrace("Unsubscribe to EvtHeartbeat DONE for {FormName}", ScannerForm.Name);
PositionSizeController.OnClosing();
@@ -619,7 +626,7 @@ public void OnFormClosing(FormClosingEventArgs e)
Context.AppPanelManager.EvtCalibrationStartNotify -= AppPanelManager_EvtCalibrationStartNotify;
Context.AppPanelManager.EvtCalibrationEndNotify -= AppPanelManager_EvtCalibrationEndNotify;
- Log.Debug("Exiting FormClosing for " + ScannerForm.Name);
+ _logger?.LogDebug("Exiting FormClosing for {FormName}", ScannerForm.Name);
}
///
diff --git a/src/Libraries/ACATCore/PanelManagement/Common/TextController.cs b/src/Libraries/ACATCore/PanelManagement/Common/TextController.cs
index 7beb9837..603a16b7 100644
--- a/src/Libraries/ACATCore/PanelManagement/Common/TextController.cs
+++ b/src/Libraries/ACATCore/PanelManagement/Common/TextController.cs
@@ -9,6 +9,7 @@
using ACAT.Core.AgentManagement;
using ACAT.Core.PanelManagement.Interfaces;
using ACAT.Core.Utility;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections;
using System.Linq;
@@ -50,11 +51,17 @@ public class TextController : ITextController
///
private static LastAction _lastAction = LastAction.Unknown;
+ ///
+ /// Logger instance
+ ///
+ private readonly ILogger _logger;
+
///
/// Initializes a new instance of the class.
///
- internal TextController()
+ internal TextController(ILogger logger = null)
{
+ _logger = logger;
}
///
@@ -101,7 +108,7 @@ public void AutoCompleteWord(string wordSelected)
}
bool isCapitalizedWordToReplace = false;
- Log.Debug("Entered AutoCompleteWord");
+ _logger?.LogDebug("Entered AutoCompleteWord");
try
{
using AgentContext context = Context.AppAgentMgr.ActiveContext();
@@ -116,19 +123,19 @@ public void AutoCompleteWord(string wordSelected)
_autocompleteStartOffset = -1;
context.TextAgent().GetPrevWordOffsetAutoComplete(out int offset, out int count);
- Log.Debug("PrevWord offset: " + offset + ", count: " + count);
+ _logger?.LogDebug("PrevWord offset: {Offset}, count: {Count}", offset, count);
CoreGlobals.Stopwatch4.Stop();
- Log.Debug("AutoComplete TimeElapsed 1: " + CoreGlobals.Stopwatch4.ElapsedMilliseconds);
+ _logger?.LogDebug("AutoComplete TimeElapsed 1: {ElapsedMilliseconds}", CoreGlobals.Stopwatch4.ElapsedMilliseconds);
CoreGlobals.Stopwatch4.Reset();
CoreGlobals.Stopwatch4.Start();
// check if we are just completing the current word or inserting a new word
bool checkInsert = context.TextAgent().CheckInsertOrReplaceWord(out int insertOrReplaceOffset, out string wordToReplace);
- Log.Debug("checkInsert: " + checkInsert + ", insertorreplaceoffset: " + insertOrReplaceOffset +
- ", caret: " + caretPos + ", caretPos-delprev: " + (caretPos - count));
- Log.Debug("wordtoReplace: " + wordToReplace);
+ _logger?.LogDebug("checkInsert: {CheckInsert}, insertorreplaceoffset: {Offset}, caret: {Caret}, caretPos-delprev: {CaretMinusCount}",
+ checkInsert, insertOrReplaceOffset, caretPos, caretPos - count);
+ _logger?.LogDebug("wordtoReplace: {WordToReplace}", wordToReplace);
_autoCompletePartialWord = wordToReplace;
@@ -139,12 +146,12 @@ public void AutoCompleteWord(string wordSelected)
}
CoreGlobals.Stopwatch4.Stop();
- Log.Debug("AutoComplete TimeElapsed 2: " + CoreGlobals.Stopwatch4.ElapsedMilliseconds);
+ _logger?.LogDebug("AutoComplete TimeElapsed 2: {ElapsedMilliseconds}", CoreGlobals.Stopwatch4.ElapsedMilliseconds);
CoreGlobals.Stopwatch4.Reset();
CoreGlobals.Stopwatch4.Start();
- Log.Debug("checkInsert: " + checkInsert + ". inserRepOff: " + insertOrReplaceOffset +
- ". wordTORep: " + wordToReplace);
+ _logger?.LogDebug("checkInsert: {CheckInsert}. inserRepOff: {Offset}. wordTORep: {Word}",
+ checkInsert, insertOrReplaceOffset, wordToReplace);
if (KeyStateTracker.IsStickyShiftOn())
{
@@ -158,7 +165,7 @@ public void AutoCompleteWord(string wordSelected)
if (checkInsert)
{
- Log.Debug("Inserting [" + wordSelected + "] at offset " + insertOrReplaceOffset);
+ _logger?.LogDebug("Inserting [{WordSelected}] at offset {Offset}", wordSelected, insertOrReplaceOffset);
CoreGlobals.Stopwatch5.Reset();
CoreGlobals.Stopwatch5.Start();
@@ -166,7 +173,7 @@ public void AutoCompleteWord(string wordSelected)
context.TextAgent().Insert(insertOrReplaceOffset, wordSelected);
CoreGlobals.Stopwatch5.Stop();
- Log.Debug("AutoComplete Insert operation TimeElapsed: " + CoreGlobals.Stopwatch5.ElapsedMilliseconds);
+ _logger?.LogDebug("AutoComplete Insert operation TimeElapsed: {ElapsedMilliseconds}", CoreGlobals.Stopwatch5.ElapsedMilliseconds);
}
else
{
@@ -183,14 +190,14 @@ public void AutoCompleteWord(string wordSelected)
wordSelected = capitalizeWord(wordSelected);
}
- Log.Debug("Replacing word at offset " + insertOrReplaceOffset + ". Length: " +
- wordToReplaceLength + ". with [" + wordSelected + "]");
+ _logger?.LogDebug("Replacing word at offset {Offset}. Length: {Length}. with [{Word}]",
+ insertOrReplaceOffset, wordToReplaceLength, wordSelected);
context.TextAgent().Replace(insertOrReplaceOffset, wordToReplaceLength, wordSelected);
}
CoreGlobals.Stopwatch4.Stop();
- Log.Debug("AutoComplete TimeElapsed 3: " + CoreGlobals.Stopwatch4.ElapsedMilliseconds);
+ _logger?.LogDebug("AutoComplete TimeElapsed 3: {ElapsedMilliseconds}", CoreGlobals.Stopwatch4.ElapsedMilliseconds);
CoreGlobals.Stopwatch4.Reset();
CoreGlobals.Stopwatch4.Start();
@@ -201,30 +208,30 @@ public void AutoCompleteWord(string wordSelected)
postAutoCompleteWord();
_autoCompleteCaretPos = context.TextAgent().GetCaretPos();
- Log.Debug("_autocompleteCursorPos is " + _autoCompleteCaretPos);
+ _logger?.LogDebug("_autocompleteCursorPos is {CaretPos}", _autoCompleteCaretPos);
CoreGlobals.Stopwatch4.Stop();
- Log.Debug("AutoComplete TimeElapsed 4: " + CoreGlobals.Stopwatch4.ElapsedMilliseconds);
+ _logger?.LogDebug("AutoComplete TimeElapsed 4: {ElapsedMilliseconds}", CoreGlobals.Stopwatch4.ElapsedMilliseconds);
}
catch (InvalidAgentContextException iace)
{
- Log.Exception("Agent Context is invalid " + iace);
+ _logger?.LogError(iace, "Agent Context is invalid");
}
catch (Exception ex)
{
- Log.Exception(ex.ToString());
+ _logger?.LogError(ex, "Exception in AutoCompleteWord");
}
finally
{
uint threadId = Kernel32Interop.GetCurrentThreadId();
- Log.Debug("Calling TextChangedNotifications.Release AFTER Autocompeting word");
+ _logger?.LogDebug("Calling TextChangedNotifications.Release AFTER Autocompeting word");
Context.AppAgentMgr.TextChangedNotifications.Release();
- Log.Debug("Returned from TextChangedNotifications.Release AFTER Autocompeting word " + threadId);
+ _logger?.LogDebug("Returned from TextChangedNotifications.Release AFTER Autocompeting word {ThreadId}", threadId);
}
- Log.Debug("Exited AutoCompleteWord");
+ _logger?.LogDebug("Exited AutoCompleteWord");
}
///
@@ -251,12 +258,12 @@ public Abbreviation CheckAndReplaceAbbreviation(ref bool handled)
if (CoreGlobals.AppPreferences.ExpandAbbreviationsOnSeparator &&
!TextUtils.IsTerminatorOrWhiteSpace(charAtCaret))
{
- Log.Debug("no sentence terminator or white space here. returning");
+ _logger?.LogDebug("no sentence terminator or white space here. returning");
return null;
}
int startPos = context.TextAgent().GetPreviousWordAtCaret(out string word);
- Log.Debug("Prev word: " + word);
+ _logger?.LogDebug("Prev word: {Word}", word);
if (string.IsNullOrEmpty(word))
{
return null;
@@ -274,9 +281,9 @@ public Abbreviation CheckAndReplaceAbbreviation(ref bool handled)
string stringToCaret = context.TextAgent().GetStringToCaret(startPos);
- Log.Debug("String to caret from startPos " + startPos + ": [" + stringToCaret + "]");
+ _logger?.LogDebug("String to caret from startPos {StartPos}: [{StringToCaret}]", startPos, stringToCaret);
replacement = stringToCaret.Replace(word, replacement);
- Log.Debug("After replacement, replacement : [" + replacement + "]");
+ _logger?.LogDebug("After replacement, replacement : [{Replacement}]", replacement);
if (isFirstWord)
{
diff --git a/src/Libraries/ACATCore/PanelManagement/PanelManager.cs b/src/Libraries/ACATCore/PanelManagement/PanelManager.cs
index cff9540f..18315835 100644
--- a/src/Libraries/ACATCore/PanelManagement/PanelManager.cs
+++ b/src/Libraries/ACATCore/PanelManagement/PanelManager.cs
@@ -10,6 +10,7 @@
using ACAT.Core.PanelManagement.PanelConfig;
using ACAT.Core.UserControlManagement;
using ACAT.Core.Utility;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
@@ -64,6 +65,11 @@ public class PanelManager : IDisposable
///
private static PanelManager _instance;
+ ///
+ /// Logger instance
+ ///
+ private readonly ILogger _logger;
+
///
/// Represents the stack of panels
///
@@ -82,8 +88,9 @@ public class PanelManager : IDisposable
///
/// Initializes an instance of the PanelManager
///
- public PanelManager()
+ public PanelManager(ILogger logger = null)
{
+ _logger = logger;
Context.AppAgentMgr.EvtPanelRequest += AppAgent_EvtPanelRequest;
Context.AppAgentMgr.EvtFocusChanged += AppAgent_EvtFocusChanged;
Context.EvtCultureChanged += Context_EvtCultureChanged;
@@ -247,7 +254,7 @@ public void CloseCurrentForm()
///
public void CloseCurrentPanel()
{
- Log.Verbose();
+ _logger?.LogTrace("CloseCurrentPanel");
if (_stack.Count > 0)
{
@@ -563,7 +570,7 @@ protected virtual void Dispose(bool disposing)
// Check to see if Dispose has already been called.
if (!_disposed)
{
- Log.Verbose();
+ _logger?.LogTrace("Dispose");
Context.EvtCultureChanged -= Context_EvtCultureChanged;
@@ -584,7 +591,7 @@ private void AppActuatorManager_EvtCalibrationEndNotify(object sender, EventArgs
{
_actuatorCalibrationInProgress = false;
- Log.Debug("Resuming WindowActivityMonitor");
+ _logger?.LogDebug("Resuming WindowActivityMonitor");
WindowActivityMonitor.Resume();
@@ -606,7 +613,7 @@ private void AppActuatorManager_EvtCalibrationStartNotify(ActuatorManagement.Cal
{
_actuatorCalibrationInProgress = true;
- Log.Debug("Pausing WindowActivityMonitor");
+ _logger?.LogDebug("Pausing WindowActivityMonitor");
WindowActivityMonitor.Pause();
@@ -730,7 +737,7 @@ private void ScannerCommon_EvtScannerShow(object sender, ScannerShowEventArg arg
/// event args
private void SystemEvents_DisplaySettingsChanged(object sender, EventArgs e)
{
- Log.Debug("Display Resolution changed. Working area is " + Screen.PrimaryScreen.WorkingArea);
+ _logger?.LogDebug("Display Resolution changed. Working area is {WorkingArea}", Screen.PrimaryScreen.WorkingArea);
EvtDisplaySettingsChanged?.Invoke(sender, e);
}
diff --git a/src/Libraries/ACATCore/PanelManagement/PanelStack.cs b/src/Libraries/ACATCore/PanelManagement/PanelStack.cs
index 3b4055c4..2930b5f6 100644
--- a/src/Libraries/ACATCore/PanelManagement/PanelStack.cs
+++ b/src/Libraries/ACATCore/PanelManagement/PanelStack.cs
@@ -10,6 +10,7 @@
using ACAT.Core.PanelManagement.Interfaces;
using ACAT.Core.PanelManagement.PanelConfig;
using ACAT.Core.Utility;
+using Microsoft.Extensions.Logging;
using System;
using System.Linq;
using System.Windows.Automation;
@@ -28,6 +29,11 @@ public class PanelStack
{
private static bool _appCloseNotifed;
+ ///
+ /// Logger instance
+ ///
+ private readonly ILogger _logger;
+
///
/// The currently active and visible scanner form.
///
@@ -45,8 +51,9 @@ public class PanelStack
///
/// Initializes an instance of the class
///
- public PanelStack()
+ public PanelStack(ILogger logger = null)
{
+ _logger = logger;
PreShowPanel = null;
PreShowPanelDisplayMode = DisplayModeTypes.None;
}
@@ -101,7 +108,7 @@ public DisplayModeTypes PanelDisplayMode
public void AppAgent_EvtPanelRequest(object sender, PanelRequestEventArgs args)
{
- Log.Debug($"Panel Request: {args}");
+ _logger?.LogDebug("Panel Request: {Args}", args);
if (_currentForm != null)
{
@@ -109,7 +116,7 @@ public void AppAgent_EvtPanelRequest(object sender, PanelRequestEventArgs args)
if (!args.UseCurrentScreenAsParent && IsModalBlocked(_currentForm, args.TargetPanel as IPanel))
{
- Log.Warn("Model dialog open; request denied.");
+ _logger?.LogWarning("Model dialog open; request denied.");
return;
}
}
@@ -128,14 +135,14 @@ public void AppAgent_EvtPanelRequest(object sender, PanelRequestEventArgs args)
private void LogCurrentFormState()
{
- Log.Verbose($"_currentForm: {_currentForm.Name}, Modal={_currentForm.Modal}");
+ _logger?.LogTrace("_currentForm: {FormName}, Modal={Modal}", _currentForm.Name, _currentForm.Modal);
if (_currentForm.Owner != null)
{
- Log.Verbose($"Owner: {_currentForm.Owner.Name}, Modal={_currentForm.Owner.Modal}");
+ _logger?.LogTrace("Owner: {OwnerName}, Modal={Modal}", _currentForm.Owner.Name, _currentForm.Owner.Modal);
}
else
{
- Log.Verbose("_currentForm.Owner is null");
+ _logger?.LogTrace("_currentForm.Owner is null");
}
}
@@ -165,7 +172,7 @@ private void HandleNewWindowRequest(PanelRequestEventArgs args, string requested
if (currentScanner != null && PanelConfigMap.AreEqual(currentScanner.PanelClass, requestedPanelClass) && _currentPanel.Owner == null)
{
- Log.Debug("Current panel is already {0}, showing it", requestedPanelClass);
+ _logger?.LogDebug("Current panel is already {PanelClass}, showing it", requestedPanelClass);
if (_currentPanel is MenuPanelBase menu)
menu.SetTitle(args.Title);
@@ -184,7 +191,7 @@ private void HandleExistingWindowRequest(PanelRequestEventArgs args, string requ
IScannerPanel currentScanner = _currentPanel as IScannerPanel;
if (currentScanner == null)
{
- Log.Debug("_currentPanel is null. Returning.");
+ _logger?.LogDebug("_currentPanel is null. Returning.");
return;
}
@@ -201,20 +208,20 @@ private void HandleExistingWindowRequest(PanelRequestEventArgs args, string requ
private void SwapPanel(PanelRequestEventArgs args, string requestedPanelClass)
{
- Log.Debug("Swapping panel to {0}", requestedPanelClass);
+ _logger?.LogDebug("Swapping panel to {PanelClass}", requestedPanelClass);
Form newPanelForm = PanelManager.Instance.CreatePanel(requestedPanelClass, args.Title ) as Form;
if (newPanelForm == null)
{
//MessageBox.Show($"Invalid form requested: {requestedPanelClass}");
- Log.Error($"Invalid form requested: {requestedPanelClass}");
+ _logger?.LogError("Invalid form requested: {PanelClass}", requestedPanelClass);
return;
}
if (args.UseCurrentScreenAsParent && _currentForm != null)
{
newPanelForm.Owner = _currentForm;
- Log.Debug("Parent override enabled; new panel Owner set to _currentForm");
+ _logger?.LogDebug("Parent override enabled; new panel Owner set to _currentForm");
}
Show(null, newPanelForm as IPanel);
diff --git a/src/Libraries/ACATCore/SpellCheckManagement/SpellCheckManager.cs b/src/Libraries/ACATCore/SpellCheckManagement/SpellCheckManager.cs
index 5edb940f..fd9cb53b 100644
--- a/src/Libraries/ACATCore/SpellCheckManagement/SpellCheckManager.cs
+++ b/src/Libraries/ACATCore/SpellCheckManagement/SpellCheckManager.cs
@@ -9,6 +9,7 @@
using ACAT.Core.PanelManagement.Common;
using ACAT.Core.SpellCheckManagement.Interfaces;
using ACAT.Core.Utility;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Globalization;
@@ -37,6 +38,11 @@ public class SpellCheckManager : IDisposable
///
private static readonly SpellCheckManager _instance = new();
+ ///
+ /// Logger instance
+ ///
+ private readonly ILogger _logger;
+
///
/// The active word predictor
///
@@ -55,8 +61,9 @@ public class SpellCheckManager : IDisposable
///
/// Initializes a new instance of the class.
///
- private SpellCheckManager()
+ private SpellCheckManager(ILogger logger = null)
{
+ _logger = logger;
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.AssemblyResolve += currentDomain_AssemblyResolve;
diff --git a/src/Libraries/ACATCore/SpellCheckManagement/SpellCheckers.cs b/src/Libraries/ACATCore/SpellCheckManagement/SpellCheckers.cs
index c21b6ef8..c87d4bb3 100644
--- a/src/Libraries/ACATCore/SpellCheckManagement/SpellCheckers.cs
+++ b/src/Libraries/ACATCore/SpellCheckManagement/SpellCheckers.cs
@@ -9,6 +9,7 @@
using ACAT.Core.SpellCheckManagement.Interfaces;
using ACAT.Core.UserManagement;
using ACAT.Core.Utility;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Globalization;
@@ -35,6 +36,11 @@ public class SpellCheckers : IDisposable
///
private static ISpellChecker _nullSpellChecker = null;
+ ///
+ /// Logger instance
+ ///
+ private readonly ILogger _logger;
+
///
/// The object that holds the preferred spellcheckers
///
@@ -63,8 +69,9 @@ public class SpellCheckers : IDisposable
///
/// Initializes an instance of the class
///
- public SpellCheckers()
+ public SpellCheckers(ILogger logger = null)
{
+ _logger = logger;
_spellCheckersTypeCache = new Dictionary>();
PreferredSpellCheckers.FilePath = UserManager.GetFullPath(PreferredConfigFile);
@@ -298,11 +305,11 @@ internal void Add(Guid guid, String language, Type type)
{
if (_spellCheckersTypeCache.ContainsKey(guid))
{
- Log.Debug("SpellChecker " + type.FullName + ", guid " + guid + " is already added");
+ _logger?.LogDebug("SpellChecker {TypeName}, guid {Guid} is already added", type.FullName, guid);
return;
}
- Log.Debug("Adding SpellChecker " + type.FullName + ", guid " + guid + " to cache");
+ _logger?.LogDebug("Adding SpellChecker {TypeName}, guid {Guid} to cache", type.FullName, guid);
_spellCheckersTypeCache.Add(guid, new Tuple(language, type));
}
diff --git a/src/Libraries/ACATCore/TTSManagement/TTSEngines.cs b/src/Libraries/ACATCore/TTSManagement/TTSEngines.cs
index 8b43441c..4fa413b1 100644
--- a/src/Libraries/ACATCore/TTSManagement/TTSEngines.cs
+++ b/src/Libraries/ACATCore/TTSManagement/TTSEngines.cs
@@ -8,6 +8,7 @@
using ACAT.Core.UserManagement;
using ACAT.Core.Utility;
using ACAT.Core.Extensions;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Globalization;
@@ -38,6 +39,11 @@ public class TTSEngines : IDisposable
///
private static ITTSEngine _nullTTSEngine = null;
+ ///
+ /// Logger instance
+ ///
+ private readonly ILogger _logger;
+
///
/// Table mapping the GUID and culture to the TTSEngine type
///
@@ -68,8 +74,9 @@ public class TTSEngines : IDisposable
///
/// Initializes a new instance of the class
///
- public TTSEngines()
+ public TTSEngines(ILogger logger = null)
{
+ _logger = logger;
_ttsEnginesTypeCache = new Dictionary>();
PreferredTTSEngines.FilePath = UserManager.GetFullPath(PreferredConfigFile);
@@ -328,11 +335,11 @@ internal void Add(Guid guid, String language, Type type)
{
if (_ttsEnginesTypeCache.ContainsKey(guid))
{
- Log.Debug("TTS Engine" + type.FullName + ", guid " + guid + " is already added");
+ _logger?.LogDebug("TTS Engine {TypeName}, guid {Guid} is already added", type.FullName, guid);
return;
}
- Log.Debug("Adding TTS Engine " + type.FullName + ", guid " + guid + " to cache");
+ _logger?.LogDebug("Adding TTS Engine {TypeName}, guid {Guid} to cache", type.FullName, guid);
_ttsEnginesTypeCache.Add(guid, new Tuple(language, type));
}
diff --git a/src/Libraries/ACATCore/TTSManagement/TTSManager.cs b/src/Libraries/ACATCore/TTSManagement/TTSManager.cs
index 92be58c7..9d0dd08d 100644
--- a/src/Libraries/ACATCore/TTSManagement/TTSManager.cs
+++ b/src/Libraries/ACATCore/TTSManagement/TTSManager.cs
@@ -11,6 +11,7 @@
using ACAT.Core.PreferencesManagement;
using ACAT.Core.TTSManagement.Interfaces;
using ACAT.Core.Utility;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Globalization;
@@ -55,6 +56,11 @@ public class TTSManager : IDisposable
///
private static readonly TTSManager _instance = new();
+ ///
+ /// Logger instance
+ ///
+ private readonly ILogger _logger;
+
///
/// Has this object been disposed
///
@@ -68,8 +74,9 @@ public class TTSManager : IDisposable
///
/// Initializes the singleton instance of the class
///
- private TTSManager()
+ private TTSManager(ILogger logger = null)
{
+ _logger = logger;
ActiveEngine = TTSEngines.NullTTSEngine;
Context.EvtCultureChanged += Context_EvtCultureChanged;
}
diff --git a/src/Libraries/ACATCore/UserControlManagement/UserControlCommon.cs b/src/Libraries/ACATCore/UserControlManagement/UserControlCommon.cs
index 33d120cc..7282fe45 100644
--- a/src/Libraries/ACATCore/UserControlManagement/UserControlCommon.cs
+++ b/src/Libraries/ACATCore/UserControlManagement/UserControlCommon.cs
@@ -14,6 +14,7 @@
using ACAT.Core.WidgetManagement;
using ACAT.Core.WidgetManagement.Interfaces;
using ACAT.Core.Widgets;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
@@ -24,8 +25,11 @@ namespace ACAT.Core.UserControlManagement
{
public class UserControlCommon : IUserControlCommon, IDisposable
{
- public UserControlCommon(IUserControl userControl, UserControlConfigMapEntry mapEntry, IScannerPanel iScannerPanel)
+ private readonly ILogger _logger;
+
+ public UserControlCommon(IUserControl userControl, UserControlConfigMapEntry mapEntry, IScannerPanel iScannerPanel, ILogger logger)
{
+ _logger = logger;
ScannerForm = iScannerPanel.Form;
this.mapEntry = mapEntry;
ScannerPanel = iScannerPanel;
@@ -92,7 +96,7 @@ public void Dispose()
public bool Initialize()
{
- Log.Debug("Entered from Initialize");
+ _logger.LogDebug("Entered from Initialize");
bool retVal = initWidgetManager(mapEntry);
@@ -101,7 +105,7 @@ public bool Initialize()
retVal = initAnimationManager(mapEntry);
}
- Log.Debug("Returning from Initialize " + retVal);
+ _logger.LogDebug("Returning from Initialize {RetVal}", retVal);
WindowActivityMonitor.EvtWindowMonitorHeartbeat += WindowActivityMonitorEvtWindowMonitorHeartbeat;
@@ -123,7 +127,7 @@ public void OnClosing()
}
catch (Exception ex)
{
- Log.Exception(ex);
+ _logger.LogError(ex, "Exception in OnClosing");
}
}
@@ -145,31 +149,31 @@ public void OnFormClosing(FormClosingEventArgs e)
}
}
- Log.Debug(ScannerForm.Name + ", SyncObj.Status: " + SyncLock.Status + ", hashcode: " + SyncLock.GetHashCode());
+ _logger.LogDebug("{ScannerFormName}, SyncObj.Status: {Status}, hashcode: {HashCode}", ScannerForm.Name, SyncLock.Status, SyncLock.GetHashCode());
if (SyncLock.Status != SyncLock.StatusValues.None)
{
- Log.Debug(ScannerForm.Name + ", SyncObj.Status: " + SyncLock.Status + ", form already closed. returning");
+ _logger.LogDebug("{ScannerFormName}, SyncObj.Status: {Status}, form already closed. returning", ScannerForm.Name, SyncLock.Status);
return;
}
- Log.Debug(ScannerForm.Name + ", SyncObj.Status: " + SyncLock.Status + ", Will continue closing");
+ _logger.LogDebug("{ScannerFormName}, SyncObj.Status: {Status}, Will continue closing", ScannerForm.Name, SyncLock.Status);
- Log.Debug("Setting SyncLock.Status to CLOSING " + ScannerForm.Name);
+ _logger.LogDebug("Setting SyncLock.Status to CLOSING {ScannerFormName}", ScannerForm.Name);
SyncLock.Status = SyncLock.StatusValues.Closing;
- Log.Debug("Before animationmangoer.stop");
+ _logger.LogDebug("Before animationmangoer.stop");
AnimationManager.Stop();
- Log.Debug("After animationmangoer.stop");
+ _logger.LogDebug("After animationmangoer.stop");
- Log.Debug("Unsubscribe to EvtHeartbeat for " + ScannerForm.Name);
+ _logger.LogDebug("Unsubscribe to EvtHeartbeat for {ScannerFormName}", ScannerForm.Name);
WindowActivityMonitor.EvtWindowMonitorHeartbeat -= WindowActivityMonitorEvtWindowMonitorHeartbeat;
- Log.Debug("Unsubscribe to EvtHeartbeat DONE for " + ScannerForm.Name);
+ _logger.LogDebug("Unsubscribe to EvtHeartbeat DONE for {ScannerFormName}", ScannerForm.Name);
unsubscribeEvents();
- Log.Debug("Exiting FormClosing for " + ScannerForm.Name);
+ _logger.LogDebug("Exiting FormClosing for {ScannerFormName}", ScannerForm.Name);
}
[EnvironmentPermission(SecurityAction.LinkDemand, Unrestricted = true)]
@@ -195,7 +199,7 @@ public void OnPause()
}
catch (Exception ex)
{
- Log.Exception(ex.ToString());
+ _logger.LogError(ex, "Exception in OnPause");
}
}
@@ -214,7 +218,7 @@ public void OnResume()
}
catch (Exception ex)
{
- Log.Exception(ex.ToString());
+ _logger.LogError(ex, "Exception in OnResume");
}
}
@@ -223,7 +227,7 @@ protected virtual void Dispose(bool disposing)
// Check to see if Dispose has already been called.
if (!disposed)
{
- Log.Verbose();
+ _logger.LogTrace("Disposing UserControlCommon");
if (disposing)
{
@@ -273,7 +277,7 @@ private bool initAnimationManager(UserControlConfigMapEntry panelConfigMapEntry)
if (!retVal)
{
- Log.Error("Error initializing animation manager");
+ _logger.LogError("Error initializing animation manager");
AnimationManager = null;
}
@@ -289,7 +293,7 @@ private bool initWidgetManager(UserControlConfigMapEntry mapEntry)
bool retVal = WidgetManager.Initialize(mapEntry.ConfigFileName);
if (!retVal)
{
- Log.Error("Unable to initialize widget manager");
+ _logger.LogError("Unable to initialize widget manager");
}
else
{
@@ -314,7 +318,7 @@ public void runCommand(String command)
command = command.Substring(1);
}
- Log.Debug("Calling scanner common runcomand with " + command);
+ _logger.LogDebug("Calling scanner common runcomand with {Command}", command);
ScannerForm.Invoke(new MethodInvoker(delegate
{
String[] parts = command.Split('.');
@@ -362,7 +366,7 @@ private void setWidgetEnabledStates(WindowActivityMonitorInfo monitorInfo)
{
if (SyncLock.IsClosing())
{
- Log.Debug("Form is closing " + ScannerForm.Name);
+ _logger.LogDebug("Form is closing {ScannerFormName}", ScannerForm.Name);
WindowActivityMonitor.EvtWindowMonitorHeartbeat -= WindowActivityMonitorEvtWindowMonitorHeartbeat;
return;
}
@@ -391,7 +395,7 @@ private void setWidgetEnabledStates(WindowActivityMonitorInfo monitorInfo)
break;
}
- Log.Verbose($"widget.Enabled set to: {widget.Enabled} for feature {widget.Name}");
+ _logger.LogTrace("widget.Enabled set to: {Enabled} for feature {WidgetName}", widget.Enabled, widget.Name);
}
}
}
@@ -418,7 +422,7 @@ private void subscribeToEvents()
private void textToSpeech(String text)
{
- Log.Debug("Convert to speech. text=" + text);
+ _logger.LogDebug("Convert to speech. text={Text}", text);
Context.AppTTSManager.ActiveEngine.Speak(text);
}
@@ -449,7 +453,7 @@ private void widgetEvtActuated(object sender, WidgetActuatedEventArgs e)
var value = widget.Value;
if (!String.IsNullOrEmpty(value))
{
- Log.Debug("**Actuate** " + widget.Name + " Value: " + value);
+ _logger.LogDebug("**Actuate** {WidgetName} Value: {Value}", widget.Name, value);
actuateButton(widget);
}
diff --git a/src/Libraries/ACATCore/UserControlManagement/UserControlManager.cs b/src/Libraries/ACATCore/UserControlManagement/UserControlManager.cs
index 359ed66f..ca81eb52 100644
--- a/src/Libraries/ACATCore/UserControlManagement/UserControlManager.cs
+++ b/src/Libraries/ACATCore/UserControlManagement/UserControlManager.cs
@@ -15,6 +15,7 @@
using ACAT.Core.Utility;
using ACAT.Core.WidgetManagement;
using ACAT.Core.Widgets;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Windows.Forms;
@@ -28,6 +29,7 @@ namespace ACAT.Core.UserControlManagement
///
public class UserControlManager
{
+ private readonly ILogger _logger;
private int _iterationCount = 0;
private int _iterations = 1;
private volatile bool _playerTransitioned = false;
@@ -40,9 +42,8 @@ public class UserControlManager
private readonly Dictionary _userControlCache = new();
- public UserControlManager(IScannerPanel scannerPanel, TextController textController)
- {
- _scannerPanel = scannerPanel;
+ public UserControlManager(IScannerPanel scannerPanel, TextController textController, ILogger logger)
+ { _logger = logger; _scannerPanel = scannerPanel;
GridScanIterations = CoreGlobals.AppPreferences.GridScanIterations;
_textController = textController;
}
@@ -92,7 +93,7 @@ public static List findAllWidgets(List list)
}
catch (Exception es)
{
- Log.Exception("Error geting widgets: " + es.ToString());
+ _logger.LogError(es, "Error geting widgets: {Exception}", es.ToString());
}
return Widgets;
}
@@ -151,12 +152,12 @@ public void OnClosing()
public void OnPause()
{
- Log.Debug("CALIBTEST UserControlManager.OnPause()");
+ _logger.LogDebug("CALIBTEST UserControlManager.OnPause()");
_playerTransitioned = false;
foreach (var userControl in _userControls)
{
- Log.Verbose("CALIBTEST calling onPause for " + userControl.Descriptor.Name);
+ _logger.LogTrace("CALIBTEST calling onPause for {UserControlName}", userControl.Descriptor.Name);
userControl.OnPause();
}
}
@@ -165,15 +166,15 @@ public void OnResume()
{
_stopTopLevelAnimation = true;
- Log.Debug("CALIBTEST UserControlManager.OnResume()");
+ _logger.LogDebug("CALIBTEST UserControlManager.OnResume()");
foreach (var userControl in _userControls)
{
- Log.Verbose("CALIBTEST. Calling onResume for uc" + userControl.Descriptor.Name);
+ _logger.LogTrace("CALIBTEST. Calling onResume for uc{UserControlName}", userControl.Descriptor.Name);
userControl.OnResume();
}
- Log.Debug("CALIBTEST Calling StartTopLevelAnimation");
+ _logger.LogDebug("CALIBTEST Calling StartTopLevelAnimation");
StartTopLevelAnimation();
}
@@ -204,7 +205,7 @@ public bool PopUserControl(Control parent)
}
else
{
- Log.Warn("MLEAK: list.Count is already zero");
+ _logger.LogWarning("MLEAK: list.Count is already zero");
}
}
@@ -255,7 +256,7 @@ public void StartTopLevelAnimation()
if (_userControls.Count > 0)
{
- Log.Debug("CALIBTEST StartTopLevelAnimation. Starting animation for " + _userControls[0].Descriptor.Name);
+ _logger.LogDebug("CALIBTEST StartTopLevelAnimation. Starting animation for {UserControlName}", _userControls[0].Descriptor.Name);
_userControls[0].UserControlCommon.AnimationManager.Start();
}
}
@@ -298,7 +299,7 @@ private bool addUserControlByKey(Control parent, String userControlKeyName, obje
}
catch (Exception ex)
{
- Log.Exception("Unable to load userControl " + userControlName + ", exception: " + ex.ToString());
+ _logger.LogError(ex, "Unable to load userControl {UserControlName}", userControlName);
retVal = false;
}
@@ -314,7 +315,7 @@ private bool addUserControlByName(Control parent, String userControlName, object
}
catch (Exception ex)
{
- Log.Exception("Unable to load userControl " + userControlName + ", exception: " + ex.ToString());
+ _logger.LogError(ex, "Unable to load userControl {UserControlName}", userControlName);
retVal = false;
}
@@ -323,29 +324,29 @@ private bool addUserControlByName(Control parent, String userControlName, object
private void animationManager_EvtPlayerAnimationTransition(object sender, string animationName, bool isTopLevel)
{
- Log.Debug("AP1: transition " + animationName + ", isTopLevel: " + isTopLevel);
+ _logger.LogDebug("AP1: transition {AnimationName}, isTopLevel: {IsTopLevel}", animationName, isTopLevel);
if (!isTopLevel)
{
- Log.Verbose("AP1: SETTING _PlayerTransitioned to TRUE");
+ _logger.LogTrace("AP1: SETTING _PlayerTransitioned to TRUE");
_playerTransitioned = true;
_iterationCount = 0;
}
else
{
- Log.Verbose("AP1: SETTING _PlayerTransitioned to FALSE");
+ _logger.LogTrace("AP1: SETTING _PlayerTransitioned to FALSE");
_playerTransitioned = false;
}
}
private void appActuatorManager_EvtSwitchActivated(object sender, ActuatorSwitchEventArgs e)
{
- Log.Debug("Switch activated");
+ _logger.LogDebug("Switch activated");
foreach (var userControl in _userControls)
{
var playerState = userControl.UserControlCommon.AnimationManager.GetPlayerState();
- Log.Verbose("userControl: " + userControl.Descriptor.Name + ", state: " + playerState);
+ _logger.LogTrace("userControl: {UserControlName}, state: {PlayerState}", userControl.Descriptor.Name, playerState);
if (playerState != PlayerState.Timeout && playerState != PlayerState.Interrupted)
{
@@ -387,12 +388,12 @@ private bool createAndInitializeUserControl(Control parent, String userControlNa
iUserControl = (userControl as IUserControl);
_userControlCache.Add(iUserControl.Descriptor.Id, iUserControl);
- Log.Verbose("Adding UserControl to cache: " + iUserControl.Descriptor.Name);
+ _logger.LogTrace("Adding UserControl to cache: {UserControlName}", iUserControl.Descriptor.Name);
}
else
{
userControl = (iUserControl as UserControl);
- Log.Verbose("Got UserControl from cache: " + iUserControl.Descriptor.Name);
+ _logger.LogTrace("Got UserControl from cache: {UserControlName}", iUserControl.Descriptor.Name);
}
if (tag != null)
@@ -427,12 +428,12 @@ private bool createAndInitializeUserControl(Control parent, String userControlNa
private IUserControl getNextUserControl(IUserControl userControl)
{
int ii;
- Log.Verbose("AP1 Find next user control. Count: " + _userControls.Count);
+ _logger.LogTrace("AP1 Find next user control. Count: {Count}", _userControls.Count);
for (ii = 0; ii < _userControls.Count; ii++)
{
if (_userControls[ii] == userControl)
{
- Log.Verbose("AP1 Found! ii = " + ii);
+ _logger.LogTrace("AP1 Found! ii = {Index}", ii);
break;
}
}
@@ -445,7 +446,7 @@ private IUserControl getNextUserControl(IUserControl userControl)
ii = 0;
}
- Log.Verbose("AP1 Returning next user control " + _userControls[ii].Descriptor.Name);
+ _logger.LogTrace("AP1 Returning next user control {UserControlName}", _userControls[ii].Descriptor.Name);
return _userControls[ii];
}
@@ -471,23 +472,23 @@ private void removeUserControl(Control parent, IUserControl userControl)
private void userControl_EvtPlayerStateChanged(IUserControl userControl, PlayerStateChangedEventArgs e)
{
- Log.Verbose("AP1 playerStateChanged for " + userControl.Descriptor.Name + ", " + "newState: " + e.NewState);
+ _logger.LogTrace("AP1 playerStateChanged for {UserControlName}, newState: {NewState}", userControl.Descriptor.Name, e.NewState);
if (_playerTransitioned)
{
- Log.Verbose("AP1: _playterTransitioned is TRUE. Returning");
+ _logger.LogTrace("AP1: _playterTransitioned is TRUE. Returning");
return;
}
if (_stopTopLevelAnimation)
{
- Log.Verbose("AP1: _stopTopLevelanimation is TRUE. Returning");
+ _logger.LogTrace("AP1: _stopTopLevelanimation is TRUE. Returning");
return;
}
if (e.NewState == PlayerState.Timeout)
{
- Log.Verbose("PlayerState timeout for " + userControl.Descriptor.Name);
+ _logger.LogTrace("PlayerState timeout for {UserControlName}", userControl.Descriptor.Name);
var next = getNextUserControl(userControl);
if (next != null)
{
@@ -495,7 +496,7 @@ private void userControl_EvtPlayerStateChanged(IUserControl userControl, PlayerS
if (_iterationCount < _iterations)
{
- Log.Verbose("AP1 Calling start on " + next.Descriptor.Name);
+ _logger.LogTrace("AP1 Calling start on {UserControlName}", next.Descriptor.Name);
next.UserControlCommon.AnimationManager.Start();
}
}
diff --git a/src/Libraries/ACATCore/UserManagement/UserManager.cs b/src/Libraries/ACATCore/UserManagement/UserManager.cs
index 86cb66dd..195cea50 100644
--- a/src/Libraries/ACATCore/UserManagement/UserManager.cs
+++ b/src/Libraries/ACATCore/UserManagement/UserManager.cs
@@ -6,6 +6,7 @@
////////////////////////////////////////////////////////////////////////////
using ACAT.Core.Utility;
+using Microsoft.Extensions.Logging;
using System;
using System.Globalization;
using System.IO;
@@ -23,6 +24,8 @@ namespace ACAT.Core.UserManagement
///
public class UserManager
{
+ private static ILogger _logger;
+
public const String BaseUserInstallDir = "Install\\Users";
///
@@ -40,6 +43,7 @@ public class UserManager
///
static UserManager()
{
+ _logger = LoggerFactory.Create(builder => builder.AddConsole()).CreateLogger();
_currentUserName = DefaultUserName;
}
@@ -136,7 +140,7 @@ public static bool CreateUserDir(String userName)
{
MessageBox.Show("Error creating dir. ex: " + ex);
- Log.Exception(ex.ToString());
+ _logger.LogError(ex, ex.Message);
retVal = false;
}
diff --git a/src/Libraries/ACATCore/Utility/AutomationEventManager.cs b/src/Libraries/ACATCore/Utility/AutomationEventManager.cs
index 605675b1..65f585d4 100644
--- a/src/Libraries/ACATCore/Utility/AutomationEventManager.cs
+++ b/src/Libraries/ACATCore/Utility/AutomationEventManager.cs
@@ -5,6 +5,7 @@
//
////////////////////////////////////////////////////////////////////////////
+using Microsoft.Extensions.Logging;
using System;
using System.Collections;
using System.Collections.Generic;
@@ -30,6 +31,8 @@ namespace ACAT.Core.Utility
///
public class AutomationEventManager : IDisposable
{
+ private readonly ILogger _logger;
+
///
/// Returns the singleton instance
///
@@ -65,8 +68,9 @@ public class AutomationEventManager : IDisposable
///
/// Prevents a default instance of AutomationEventManager class from being created
///
- private AutomationEventManager()
+ private AutomationEventManager(ILogger logger = null)
{
+ _logger = logger;
Start();
}
@@ -91,7 +95,7 @@ public static void AddAutomationEventHandler(IntPtr hWnd,
AutomationElement element,
AutomationEventHandler eventHandler)
{
- Log.Verbose();
+ _logger?.LogTrace("AddAutomationEventHandler called");
var windowElement = (WindowElement)WindowTable[hWnd];
if (windowElement == null)
@@ -113,7 +117,7 @@ public static void AddAutomationEventHandler(IntPtr hWnd,
}
else
{
- Log.Debug("Found window element");
+ _logger?.LogDebug("Found window element");
}
// create the item and add it
@@ -168,7 +172,7 @@ public static void AddAutomationPropertyChangedEventHandler(IntPtr hWnd,
/// window handle
public static void RemoveAllAutomationEventHandlers(IntPtr hwnd)
{
- Log.Debug(hwnd.ToString());
+ _instance._logger?.LogDebug("RemoveAllAutomationEventHandlers: {Hwnd}", hwnd);
lock (WindowTable)
{
@@ -177,17 +181,17 @@ public static void RemoveAllAutomationEventHandlers(IntPtr hwnd)
var windowElement = (WindowElement)WindowTable[hwnd];
windowElement.EvtOnWindowClosed -= windowElement_EvtOnWindowClosed;
- Log.Debug("Found " + hwnd + " in hashtable. removing it");
+ _instance._logger?.LogDebug("Found {Hwnd} in hashtable. removing it", hwnd);
WindowTable.Remove(hwnd);
- Log.Debug("Calling RemoveAllEvents");
+ _instance._logger?.LogDebug("Calling RemoveAllEvents");
var item = new RemoveAllEventsItem { WinElement = windowElement };
RemoveAllEvents(item);
}
else
{
- Log.Debug("Did not find " + hwnd + " in hashtable.");
+ _instance._logger?.LogDebug("Did not find {Hwnd} in hashtable", hwnd);
}
}
}
@@ -200,7 +204,7 @@ public static void RemoveAllAutomationEventHandlers(IntPtr hwnd)
/// the automation element
public static void RemoveAutomationEventHandler(IntPtr hWnd, AutomationEvent autoEvent, AutomationElement element)
{
- Log.Debug("hWnd=" + hWnd);
+ _instance._logger?.LogDebug("RemoveAutomationEventHandler: hWnd={HWnd}", hWnd);
if (hWnd != IntPtr.Zero)
{
lock (WindowTable)
@@ -234,7 +238,7 @@ public static void RemoveAutomationPropertyChangedEventHandler(IntPtr hWnd,
AutomationElement element,
AutomationPropertyChangedEventHandler eventHandler)
{
- Log.Verbose();
+ _instance._logger?.LogTrace("RemoveAutomationPropertyChangedEventHandler called");
if (hWnd == IntPtr.Zero)
{
@@ -310,11 +314,11 @@ public void HandlerThread()
}
else if (obj is DoneEventHandlerItem)
{
- Log.Debug("Received command to quit thread");
+ _logger?.LogDebug("Received command to quit thread");
_done = true;
}
}
- Log.Debug("Exiting Handler Thread");
+ _logger?.LogDebug("Exiting Handler Thread");
}
///
@@ -346,7 +350,7 @@ protected virtual void Dispose(bool disposing)
// Check to see if Dispose has already been called.
if (!_disposed)
{
- Log.Verbose();
+ _logger?.LogTrace("Dispose called");
try
{
@@ -358,15 +362,15 @@ protected virtual void Dispose(bool disposing)
_queue.Enqueue(item);
- Log.Debug("Aborting thread...");
+ _logger?.LogDebug("Aborting thread...");
_thread.Abort();
- Log.Debug("Returned from abort");
+ _logger?.LogDebug("Returned from abort");
// Wait until oThread finishes. Join also has overloads
// that take a millisecond interval or a TimeSpan object.
- Log.Debug("Calling Join");
+ _logger?.LogDebug("Calling Join");
_thread.Join();
- Log.Debug("REturned from join");
+ _logger?.LogDebug("Returned from join");
// dispose all managed resources.
Automation.RemoveAllEventHandlers();
@@ -472,7 +476,7 @@ private static void RemoveAutomationPropertyChanged(RemoveAutomationPropertyChan
/// handle to the window that was closed
private static void windowElement_EvtOnWindowClosed(IntPtr hwnd)
{
- Log.Debug(hwnd.ToString());
+ _instance._logger?.LogDebug("Window closed: {Hwnd}", hwnd);
RemoveAllAutomationEventHandlers(hwnd);
}
@@ -569,7 +573,7 @@ public WindowElement(IntPtr handle)
}
catch (Exception ex)
{
- Log.Exception(ex.ToString());
+ _instance._logger?.LogError(ex, "Exception in WindowElement constructor");
}
}
@@ -592,38 +596,38 @@ public WindowElement(IntPtr handle)
/// the event handler
public void AddAutomationEventHandler(AutomationElement element, AutomationEvent autoEvent, AutomationEventHandler eventHandler)
{
- Log.Verbose();
+ _instance._logger?.LogTrace("AddAutomationEventHandler called");
try
{
var events = (Hashtable)_controlElements[element];
if (events == null)
{
- Log.Debug("events Arraylist is null. Creating one...");
+ _instance._logger?.LogDebug("events Arraylist is null. Creating one...");
_controlElements.Add(element, new Hashtable());
events = (Hashtable)_controlElements[element];
}
if (!events.Contains(autoEvent))
{
- Log.Debug("Events array does not contain. Adding automation event " +
- autoEvent.ProgrammaticName +
- ". AutomationID: " + (element.Current.AutomationId ?? "none"));
+ _instance._logger?.LogDebug("Events array does not contain. Adding automation event {EventName}. AutomationID: {AutomationId}",
+ autoEvent.ProgrammaticName,
+ element.Current.AutomationId ?? "none");
Automation.AddAutomationEventHandler(autoEvent, element, TreeScope.Element, eventHandler);
- Log.Debug("Returned from AddAutomationEventHandler");
+ _instance._logger?.LogDebug("Returned from AddAutomationEventHandler");
events.Add(autoEvent, eventHandler);
- Log.Debug("Done adding");
+ _instance._logger?.LogDebug("Done adding");
}
else
{
- Log.Debug("Event already registered. Will not be readded" +
- autoEvent.ProgrammaticName +
- ". AutomationID: " + (element.Current.AutomationId ?? "none"));
+ _instance._logger?.LogDebug("Event already registered. Will not be readded {EventName}. AutomationID: {AutomationId}",
+ autoEvent.ProgrammaticName,
+ element.Current.AutomationId ?? "none");
}
}
catch (Exception e)
{
- Log.Exception("Exception occured! e=" + e.ToString());
+ _instance._logger?.LogError(e, "Exception occurred in AddAutomationEventHandler");
}
}
@@ -637,7 +641,7 @@ public void AddAutomationPropertyChangedEventHandler(AutomationElement element,
AutomationProperty property,
AutomationPropertyChangedEventHandler eventHandler)
{
- Log.Verbose();
+ _instance._logger?.LogTrace("AddAutomationPropertyChangedEventHandler called");
try
{
@@ -652,8 +656,9 @@ public void AddAutomationPropertyChangedEventHandler(AutomationElement element,
{
Automation.AddAutomationPropertyChangedEventHandler(element, TreeScope.Element, onPropertyChanged, property);
- Log.Debug("Adding property changed event " + property.ProgrammaticName +
- ". AutomationID: " + (element.Current.AutomationId ?? "none"));
+ _instance._logger?.LogDebug("Adding property changed event {PropertyName}. AutomationID: {AutomationId}",
+ property.ProgrammaticName,
+ element.Current.AutomationId ?? "none");
var eventHandlerList = new List
{
@@ -666,22 +671,23 @@ public void AddAutomationPropertyChangedEventHandler(AutomationElement element,
var eventHandlerList = (List)events[property];
if (!eventHandlerList.Contains(eventHandler))
{
- Log.Debug("Registering event. " + property.ProgrammaticName +
- ". AutomationID: " + (element.Current.AutomationId ?? "none"));
+ _instance._logger?.LogDebug("Registering event. {PropertyName}. AutomationID: {AutomationId}",
+ property.ProgrammaticName,
+ element.Current.AutomationId ?? "none");
eventHandlerList.Add(eventHandler);
}
else
{
- Log.Debug("Property change already registered. " +
- property.ProgrammaticName + ". AutomationID: " +
- (element.Current.AutomationId ?? "none"));
+ _instance._logger?.LogDebug("Property change already registered. {PropertyName}. AutomationID: {AutomationId}",
+ property.ProgrammaticName,
+ element.Current.AutomationId ?? "none");
}
}
}
catch (Exception e)
{
- Log.Exception(e);
+ _instance._logger?.LogError(e, "Exception in AddAutomationPropertyChangedEventHandler");
}
}
@@ -690,15 +696,15 @@ public void AddAutomationPropertyChangedEventHandler(AutomationElement element,
///
public void RemoveAllEvents()
{
- Log.Verbose();
+ _instance._logger?.LogTrace("RemoveAllEvents called");
try
{
- Log.Debug("ControlElements count: " + _controlElements.Count);
+ _instance._logger?.LogDebug("ControlElements count: {Count}", _controlElements.Count);
foreach (AutomationElement element in _controlElements.Keys)
{
var events = (Hashtable)_controlElements[element];
- Log.Debug("events count: " + events.Count);
+ _instance._logger?.LogDebug("events count: {Count}", events.Count);
foreach (var key in events.Keys)
{
if (key is AutomationEvent)
@@ -707,9 +713,9 @@ public void RemoveAllEvents()
var eventHandler = (AutomationEventHandler)events[autoEvent];
try
{
- Log.Debug("Removing automation event " + autoEvent.ProgrammaticName);
+ _instance._logger?.LogDebug("Removing automation event {EventName}", autoEvent.ProgrammaticName);
Automation.RemoveAutomationEventHandler(autoEvent, element, eventHandler);
- Log.Debug("Done removing automation event");
+ _instance._logger?.LogDebug("Done removing automation event");
}
catch { }
}
@@ -719,9 +725,9 @@ public void RemoveAllEvents()
var eventHandler = (AutomationPropertyChangedEventHandler)events[autoProperty];
try
{
- Log.Debug("Removing automation property " + autoProperty.ProgrammaticName);
+ _instance._logger?.LogDebug("Removing automation property {PropertyName}", autoProperty.ProgrammaticName);
Automation.RemoveAutomationPropertyChangedEventHandler(element, eventHandler);
- Log.Debug("Done removing automation property");
+ _instance._logger?.LogDebug("Done removing automation property");
}
catch { }
}
@@ -732,7 +738,7 @@ public void RemoveAllEvents()
}
catch (Exception e)
{
- Log.Exception("Exception occured! e=" + e.ToString());
+ _instance._logger?.LogError(e, "Exception occurred in RemoveAllEvents");
}
}
@@ -743,28 +749,28 @@ public void RemoveAllEvents()
/// the event
public void RemoveAutomationEventHandler(AutomationElement element, AutomationEvent autoEvent)
{
- Log.Verbose();
+ _instance._logger?.LogTrace("RemoveAutomationEventHandler called");
try
{
var events = (Hashtable)_controlElements[element];
if (events != null && events.Contains(autoEvent))
{
- Log.Debug("Removing automation event " + autoEvent.ProgrammaticName);
+ _instance._logger?.LogDebug("Removing automation event {EventName}", autoEvent.ProgrammaticName);
var eventHandler = (AutomationEventHandler)events[autoEvent];
Automation.RemoveAutomationEventHandler(autoEvent, element, eventHandler);
- Log.Debug("RemoveAutomationEventHandler succeeded!");
+ _instance._logger?.LogDebug("RemoveAutomationEventHandler succeeded!");
events.Remove(autoEvent);
}
else
{
- Log.Debug("Event already Removed." +
- autoEvent.ProgrammaticName + ". AutomationID: " +
- (element.Current.AutomationId ?? "none"));
+ _instance._logger?.LogDebug("Event already Removed. {EventName}. AutomationID: {AutomationId}",
+ autoEvent.ProgrammaticName,
+ element.Current.AutomationId ?? "none");
}
}
catch (Exception e)
{
- Log.Exception(e);
+ _instance._logger?.LogError(e, "Exception in RemoveAutomationEventHandler");
}
}
@@ -778,11 +784,11 @@ public void RemoveAutomationPropertyChangedEventHandler(AutomationElement elemen
AutomationProperty property,
AutomationPropertyChangedEventHandler eventHandler)
{
- Log.Verbose();
+ _instance._logger?.LogTrace("RemoveAutomationPropertyChangedEventHandler called");
try
{
- Log.Debug("Removing propertychanged event for automation property " + property.ProgrammaticName);
+ _instance._logger?.LogDebug("Removing propertychanged event for automation property {PropertyName}", property.ProgrammaticName);
var events = (Hashtable)_controlElements[element];
if (events != null && events.Contains(property))
{
@@ -790,28 +796,28 @@ public void RemoveAutomationPropertyChangedEventHandler(AutomationElement elemen
if (eventHandlerList.Contains(eventHandler))
{
eventHandlerList.Remove(eventHandler);
- Log.Debug("RemoveAutomationPropertyChangedEventHandler succeeded!");
+ _instance._logger?.LogDebug("RemoveAutomationPropertyChangedEventHandler succeeded!");
if (eventHandlerList.Count == 0)
{
- Log.Debug("Event handler list is empty. No more subscribers. Removing event");
+ _instance._logger?.LogDebug("Event handler list is empty. No more subscribers. Removing event");
Automation.RemoveAutomationPropertyChangedEventHandler(element, onPropertyChanged);
events.Remove(property);
}
}
else
{
- Log.Error("Could not remove event. Did not find event handler in the eventhandlers list");
+ _instance._logger?.LogError("Could not remove event. Did not find event handler in the eventhandlers list");
}
}
else
{
- Log.Error("Could not remove event. Did not find property in the events list");
+ _instance._logger?.LogError("Could not remove event. Did not find property in the events list");
}
}
catch (Exception e)
{
- Log.Exception("Exception occured! e=" + e.ToString());
+ _instance._logger?.LogError(e, "Exception occurred in RemoveAutomationPropertyChangedEventHandler");
}
}
@@ -823,7 +829,7 @@ public void RemoveAutomationPropertyChangedEventHandler(AutomationElement elemen
/// event args
private void onPropertyChanged(object sender, AutomationPropertyChangedEventArgs e)
{
- Log.Debug(e.Property.ProgrammaticName);
+ _instance._logger?.LogDebug("Property changed: {PropertyName}", e.Property.ProgrammaticName);
var element = sender as AutomationElement;
Hashtable events = (Hashtable)_controlElements[element];
@@ -831,10 +837,10 @@ private void onPropertyChanged(object sender, AutomationPropertyChangedEventArgs
if (events != null && events.Contains(e.Property))
{
var eventHandlerList = (List)events[e.Property];
- Log.Debug("eventHandlerList.Count = " + eventHandlerList.Count);
+ _instance._logger?.LogDebug("eventHandlerList.Count = {Count}", eventHandlerList.Count);
foreach (var p in eventHandlerList)
{
- Log.Debug("Calling property changed for " + e.Property.ProgrammaticName);
+ _instance._logger?.LogDebug("Calling property changed for {PropertyName}", e.Property.ProgrammaticName);
p(sender, e);
}
}
@@ -849,7 +855,7 @@ private void onWindowClose(object sender, AutomationEventArgs e)
{
if (EvtOnWindowClosed != null)
{
- Log.Debug("Triggering event closed");
+ _instance._logger?.LogDebug("Triggering event closed");
EvtOnWindowClosed(_hwnd);
}
}
diff --git a/src/Libraries/ACATCore/Utility/CachedLog.cs b/src/Libraries/ACATCore/Utility/CachedLog.cs
index c62e7c99..dc66531c 100644
--- a/src/Libraries/ACATCore/Utility/CachedLog.cs
+++ b/src/Libraries/ACATCore/Utility/CachedLog.cs
@@ -5,6 +5,7 @@
//
////////////////////////////////////////////////////////////////////////////
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.IO;
@@ -17,6 +18,8 @@ namespace ACAT.Core.Utility
///
public class CachedLog
{
+ private readonly ILogger _logger;
+
///
/// Full path to the log file
///
@@ -29,8 +32,9 @@ public class CachedLog
///
private readonly string LogFileName;
- public CachedLog(string baseFileName)
+ public CachedLog(string baseFileName, ILogger logger)
{
+ _logger = logger;
string logFileFolder = FileUtils.GetLogsDir();
try
@@ -80,7 +84,7 @@ public bool Save()
}
catch (Exception ex)
{
- Log.Exception(ex.ToString());
+ _logger.LogError(ex, ex.Message);
return false;
}
finally
diff --git a/src/Libraries/ACATCore/Utility/DirectoryWalker.cs b/src/Libraries/ACATCore/Utility/DirectoryWalker.cs
index b34a68d8..dff1d2a4 100644
--- a/src/Libraries/ACATCore/Utility/DirectoryWalker.cs
+++ b/src/Libraries/ACATCore/Utility/DirectoryWalker.cs
@@ -5,6 +5,7 @@
//
////////////////////////////////////////////////////////////////////////////
+using Microsoft.Extensions.Logging;
using System;
using System.IO;
using System.Linq;
@@ -30,6 +31,8 @@ namespace ACAT.Core.Utility
/// files to find
public class DirectoryWalker
{
+ private readonly ILogger _logger;
+
/////
///// Invoked when a directory is found
/////
@@ -59,8 +62,9 @@ public DirectoryWalker(String rootDir) : this(rootDir, string.Empty)
{
}
- public DirectoryWalker(String rootDir, String fileWildCard)
+ public DirectoryWalker(String rootDir, String fileWildCard, ILogger logger = null)
{
+ _logger = logger ?? LoggerFactory.Create(builder => builder.AddConsole()).CreateLogger();
_rootDir = rootDir;
_wildCard = fileWildCard;
}
@@ -83,21 +87,21 @@ public void Walk(OnFileFoundDelegate fileFoundDelegate)
foreach (var file in dllFiles)
{
- Log.Verbose("Found file: " + file);
+ _logger.LogTrace("Found file: " + file);
fileFoundDelegate?.Invoke(file);
}
}
catch (UnauthorizedAccessException ex)
{
- Log.Exception("Access denied: " + ex.Message);
+ _logger.LogError(ex, "Access denied: " + ex.Message);
}
catch (IOException ex)
{
- Log.Verbose("IO error: " + ex.Message);
+ _logger.LogTrace("IO error: " + ex.Message);
}
catch (Exception ex)
{
- Log.Exception("Error: " + ex.Message);
+ _logger.LogError(ex, "Error: " + ex.Message);
}
}
diff --git a/src/Libraries/ACATCore/Utility/EnumWindows.cs b/src/Libraries/ACATCore/Utility/EnumWindows.cs
index aacd8f89..8a288232 100644
--- a/src/Libraries/ACATCore/Utility/EnumWindows.cs
+++ b/src/Libraries/ACATCore/Utility/EnumWindows.cs
@@ -7,6 +7,7 @@
using ACAT.Core.PanelManagement;
using ACAT.Core.PanelManagement.Interfaces;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
@@ -20,6 +21,8 @@ namespace ACAT.Core.Utility
///
public static class EnumWindows
{
+ private static ILogger _logger;
+
///
/// Ignore windows with these class names during enumeration
///
@@ -52,6 +55,11 @@ public static class EnumWindows
///
private static List windowList;
+ static EnumWindows()
+ {
+ _logger = LoggerFactory.Create(builder => builder.AddConsole()).CreateLogger(typeof(EnumWindows));
+ }
+
///
/// Synchronously enumerates windows and returns a window list
///
@@ -76,7 +84,7 @@ public static List Enumerate(bool excludeThisProcess = true)
public static void RestoreFocusToTopWindow(int ignoreHandle = 0)
{
var winList = Enumerate(false);
- Log.Debug("winList Count: " + winList.Count);
+ _logger.LogDebug("winList Count: " + winList.Count);
bool found = false;
var handle = IntPtr.Zero;
IntPtr ignoreWindowHandle = new(ignoreHandle);
@@ -94,7 +102,7 @@ public static void RestoreFocusToTopWindow(int ignoreHandle = 0)
var control = Form.FromHandle(handle);
if (control is IDialogPanel)
{
- Log.Debug("Setting focus to ACAT dialog." + windowInfo.Title);
+ _logger.LogDebug("Setting focus to ACAT dialog." + windowInfo.Title);
found = true;
break;
}
@@ -107,7 +115,7 @@ public static void RestoreFocusToTopWindow(int ignoreHandle = 0)
control is not MenuPanelBase &&
control is not IScannerPanel)
{
- Log.Debug("Found top window " + windowInfo.Title);
+ _logger.LogDebug("Found top window " + windowInfo.Title);
found = true;
break;
}
@@ -131,7 +139,7 @@ control is not MenuPanelBase &&
public static void RestoreFocusToTopWindowOnDesktop()
{
var winList = Enumerate();
- Log.Debug("winList Count: " + winList.Count);
+ _logger.LogDebug("winList Count: " + winList.Count);
bool found = false;
var handle = IntPtr.Zero;
@@ -146,7 +154,7 @@ public static void RestoreFocusToTopWindowOnDesktop()
if (!windowInfo.Title.Contains("DebugView") &&
!Windows.IsMinimized(handle))
{
- Log.Debug("Found top window " + windowInfo.Title);
+ _logger.LogDebug("Found top window " + windowInfo.Title);
found = true;
break;
}
@@ -249,7 +257,7 @@ private static bool enumWindowsCallback(IntPtr winHandle, int lParam)
if (!string.IsNullOrEmpty(windowTitle))
{
- Log.Debug("hWnd=" + winHandle + " windowTitle=" + windowTitle);
+ _logger.LogDebug("hWnd=" + winHandle + " windowTitle=" + windowTitle);
var info = new WindowInfo(winHandle, windowTitle);
windowList.Add(info);
diff --git a/src/Libraries/ACATCore/Utility/FileUtils.cs b/src/Libraries/ACATCore/Utility/FileUtils.cs
index 2c2d0742..e4f4ae84 100644
--- a/src/Libraries/ACATCore/Utility/FileUtils.cs
+++ b/src/Libraries/ACATCore/Utility/FileUtils.cs
@@ -6,6 +6,7 @@
////////////////////////////////////////////////////////////////////////////
using ACAT.Core.UserManagement;
+using Microsoft.Extensions.Logging;
using System;
using System.Diagnostics;
using System.IO;
@@ -25,6 +26,8 @@ namespace ACAT.Core.Utility
///
public class FileUtils
{
+ private static ILogger _logger;
+
///
/// Folder under which ACAT extensions are stored
///
@@ -125,16 +128,17 @@ public static Assembly AssemblyResolve(Assembly executingAssembly, ResolveEventA
return null;
}
- Log.Debug($"RequestingAssembly: [{args.RequestingAssembly.Location}], Name:[{args.Name}]");
+ _logger?.LogDebug("RequestingAssembly: [{Location}], Name:[{Name}]",
+ args.RequestingAssembly.Location, args.Name);
var requestingAssemblyDir = Path.GetDirectoryName(args.RequestingAssembly.Location);
- Log.Debug($"RequestingAssembly directory is {requestingAssemblyDir}");
+ _logger?.LogDebug("RequestingAssembly directory is {Directory}", requestingAssemblyDir);
var assemblyName = new AssemblyName(args.Name).Name;
var assemblyPath = $"{requestingAssemblyDir}\\{assemblyName}.dll";
- Log.Debug($"Resolved assembly location: {assemblyPath}");
+ _logger?.LogDebug("Resolved assembly location: {Path}", assemblyPath);
Assembly retVal = null;
try
@@ -149,13 +153,13 @@ public static Assembly AssemblyResolve(Assembly executingAssembly, ResolveEventA
return null;
}
- Log.Exception(fnf);
+ _logger?.LogError(fnf, "Exception loading assembly");
throw;
}
catch (Exception ex)
{
- Log.Exception($"Could not load assembly. Exception: {ex}");
+ _logger?.LogError(ex, "Could not load assembly");
}
return retVal;
}
@@ -240,7 +244,7 @@ public static bool Copy(String source, String target)
}
catch (Exception ex)
{
- Log.Exception(ex.ToString());
+ _logger?.LogError(ex, "Exception in Copy");
retVal = false;
}
@@ -317,12 +321,14 @@ public static String GetPanelConfigDir()
/// input assembly
public static void GetDependentAssemblyVersion(Assembly assembly)
{
- Log.Debug("Assembly name: " + assembly.GetName() + " Version: " + assembly.GetName().Version.ToString());
+ _logger?.LogDebug("Assembly name: {Name} Version: {Version}",
+ assembly.GetName(), assembly.GetName().Version);
AssemblyName[] referenced = assembly.GetReferencedAssemblies();
foreach (AssemblyName refAssembly in referenced)
{
- Log.Debug("Assembly name: " + refAssembly.Name + " Version: " + refAssembly.Version.ToString());
+ _logger?.LogDebug("Assembly name: {Name} Version: {Version}",
+ refAssembly.Name, refAssembly.Version);
}
}
@@ -635,7 +641,8 @@ public static void LogAssemblyInfo(Assembly executingAssembly = null)
var appVersion = "Version " + assembly.GetName().Version;
- Log.Info("***** " + appName + ". " + appVersion + ". " + DateTime.Now.ToString() + " *****");
+ _logger?.LogInformation("***** {AppName}. {AppVersion}. {DateTime} *****",
+ appName, appVersion, DateTime.Now);
}
///
@@ -648,7 +655,7 @@ public static bool Run(String executable, ProcessWindowStyle style = ProcessWind
{
bool retVal = true;
- Log.Debug("Run " + executable);
+ _logger?.LogDebug("Run {Executable}", executable);
var startInfo = new ProcessStartInfo
{
@@ -663,11 +670,11 @@ public static bool Run(String executable, ProcessWindowStyle style = ProcessWind
}
catch (Exception e)
{
- Log.Error("Error executing " + executable + ". Exception: " + e);
+ _logger?.LogError(e, "Error executing {Executable}", executable);
return false;
}
- Log.Debug("Returning " + retVal);
+ _logger?.LogDebug("Returning {Result}", retVal);
return retVal;
}
diff --git a/src/Libraries/ACATCore/Utility/GlobalPreferences.cs b/src/Libraries/ACATCore/Utility/GlobalPreferences.cs
index 27eadd52..f4091c89 100644
--- a/src/Libraries/ACATCore/Utility/GlobalPreferences.cs
+++ b/src/Libraries/ACATCore/Utility/GlobalPreferences.cs
@@ -6,6 +6,7 @@
////////////////////////////////////////////////////////////////////////////
using System;
+using Microsoft.Extensions.Logging;
namespace ACAT.Core.Utility
{
@@ -17,6 +18,7 @@ namespace ACAT.Core.Utility
[Serializable]
public class GlobalPreferences
{
+ private static ILogger _logger;
public static String DefaultPreferencesFilePath = String.Empty;
public static String LogFileName = String.Empty;
@@ -53,7 +55,7 @@ public static GlobalPreferences Load(String prefFile, bool loadDefaultsOnFail =
if (retVal == null)
{
- Log.Error($"Could not load global preferences from {prefFile}. Creating a new one.");
+ _logger?.LogError("Could not load global preferences from {PrefFile}. Creating a new one.", prefFile);
if (loadDefaultsOnFail)
{
retVal = new GlobalPreferences();
@@ -66,7 +68,7 @@ public static GlobalPreferences Load(String prefFile, bool loadDefaultsOnFail =
if (!XmlUtils.XmlFileSave(retVal, prefFile))
{
- Log.Error("Unable to save global preferences!");
+ _logger?.LogError("Unable to save global preferences!");
retVal = null;
}
@@ -107,7 +109,7 @@ public static bool Save(GlobalPreferences prefs, String preferencesFile)
if (retVal == false)
{
- Log.Error("Error saving preferences! file=" + preferencesFile);
+ _logger?.LogError("Error saving preferences! file={PreferencesFile}", preferencesFile);
}
return retVal;
diff --git a/src/Libraries/ACATCore/Utility/HtmlUtils.cs b/src/Libraries/ACATCore/Utility/HtmlUtils.cs
index 97deb9b0..8f9119a5 100644
--- a/src/Libraries/ACATCore/Utility/HtmlUtils.cs
+++ b/src/Libraries/ACATCore/Utility/HtmlUtils.cs
@@ -12,11 +12,13 @@
using System.IO;
using System.Text;
using System.Web;
+using Microsoft.Extensions.Logging;
namespace ACAT.Core.Utility
{
public class HtmlUtils
{
+ private static ILogger _logger;
///
/// Paths of the browsers exe
///
@@ -166,7 +168,7 @@ public static void LoadHtml(string path, string[] htmlData)
}
catch (Exception ex)
{
- Log.Exception("Error loading HTML script: " + ex.Message);
+ _logger?.LogError(ex, "Error loading HTML script: {Message}", ex.Message);
}
}
diff --git a/src/Libraries/ACATCore/Utility/ImageUtils.cs b/src/Libraries/ACATCore/Utility/ImageUtils.cs
index 78b2a46c..781f4e4e 100644
--- a/src/Libraries/ACATCore/Utility/ImageUtils.cs
+++ b/src/Libraries/ACATCore/Utility/ImageUtils.cs
@@ -10,6 +10,7 @@
using System.Drawing.Imaging;
using System.IO;
using System.Reflection;
+using Microsoft.Extensions.Logging;
namespace ACAT.Core.Utility
{
@@ -18,6 +19,7 @@ namespace ACAT.Core.Utility
///
public class ImageUtils
{
+ private static ILogger _logger;
///
/// Converts the specified icon into a bitmap
///
@@ -84,7 +86,7 @@ public static Bitmap ImageCrop(String imageFile, Rectangle cropRectangle)
}
catch (Exception e)
{
- Log.Error("ImageCrop: Could not crop image " + imageFile + ". Exception: " + e.ToString());
+ _logger?.LogError(e, "ImageCrop: Could not crop image {ImageFile}", imageFile);
}
return retVal;
@@ -167,16 +169,16 @@ public static Image LoadImage(String bitmapFile)
return null;
}
- Log.Debug("imagePath: " + bitmapFile);
+ _logger?.LogDebug("imagePath: {BitmapFile}", bitmapFile);
if (File.Exists(bitmapFile))
{
- Log.Debug("File exists. Loading image");
+ _logger?.LogDebug("File exists. Loading image");
retVal = Image.FromFile(bitmapFile);
}
else
{
- Log.Error("Could not find bitmap file " + bitmapFile);
+ _logger?.LogError("Could not find bitmap file {BitmapFile}", bitmapFile);
}
return retVal;
diff --git a/src/Libraries/ACATCore/Utility/KeyStateTracker.cs b/src/Libraries/ACATCore/Utility/KeyStateTracker.cs
index 02c75c12..0227d58c 100644
--- a/src/Libraries/ACATCore/Utility/KeyStateTracker.cs
+++ b/src/Libraries/ACATCore/Utility/KeyStateTracker.cs
@@ -9,6 +9,7 @@
using System.Collections;
using System.Collections.Generic;
using System.Windows.Forms;
+using Microsoft.Extensions.Logging;
namespace ACAT.Core.Utility
{
@@ -25,6 +26,7 @@ namespace ACAT.Core.Utility
///
public class KeyStateTracker
{
+ private static ILogger _logger;
private const byte VK_CAPITAL = 0x14;
private const byte VK_NUMLOCK = 0x90;
diff --git a/src/Libraries/ACATCore/Utility/NamedPipe/PipeServer.cs b/src/Libraries/ACATCore/Utility/NamedPipe/PipeServer.cs
index 2a3999ce..6c61ddc9 100644
--- a/src/Libraries/ACATCore/Utility/NamedPipe/PipeServer.cs
+++ b/src/Libraries/ACATCore/Utility/NamedPipe/PipeServer.cs
@@ -12,11 +12,13 @@
using System.Security.Principal;
using System.Text;
using System.Threading;
+using Microsoft.Extensions.Logging;
namespace ACAT.Core.Utility.NamedPipe
{
public sealed class PipeServer : IDisposable
{
+ private readonly ILogger _logger;
private CancellationToken cancellationToken;
private readonly CancellationTokenSource cancellationTokenSource;
private bool disposed;
@@ -34,8 +36,10 @@ public sealed class PipeServer : IDisposable
/// Allow the pipe to be visible by all the users
/// Current user and Administrator user
///
- public PipeServer(string pipeName, PipeDirection pipeDirection, bool allowAllReadWrite = false)
+ /// Logger for dependency injection
+ public PipeServer(string pipeName, PipeDirection pipeDirection, bool allowAllReadWrite = false, ILogger logger = null)
{
+ _logger = logger;
if (!allowAllReadWrite)
{
ServerStream = new NamedPipeServerStream(
@@ -203,7 +207,7 @@ private void ReadCallback(IAsyncResult ar)
}
catch (Exception ex)
{
- Log.Exception("Error in ReadCallback: " + ex.Message);
+ _logger?.LogError(ex, "Error in ReadCallback: {Message}", ex.Message);
// Check to make sure the Pipe is still around
try
@@ -214,7 +218,7 @@ private void ReadCallback(IAsyncResult ar)
catch (Exception e)
{
// Something happened to the pipe. Just send an Exit message to the client
- Log.Debug("Pipe is not connected. Sending exit message to client. " + e.Message);
+ _logger?.LogDebug("Pipe is not connected. Sending exit message to client. {Message}", e.Message);
OnMessageReceived(new MessageReceivedEventArgs("quit"));
}
}
diff --git a/src/Libraries/ACATCore/Utility/ResourceUtils.cs b/src/Libraries/ACATCore/Utility/ResourceUtils.cs
index db8269f7..0bf85dd5 100644
--- a/src/Libraries/ACATCore/Utility/ResourceUtils.cs
+++ b/src/Libraries/ACATCore/Utility/ResourceUtils.cs
@@ -6,6 +6,7 @@
////////////////////////////////////////////////////////////////////////////
using ACAT.Core.UserManagement;
+using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Globalization;
@@ -18,6 +19,7 @@ namespace ACAT.Core.Utility
///
public class ResourceUtils
{
+ private static ILogger _logger;
///
/// Name of the language resources dll
///
@@ -78,7 +80,7 @@ public static IEnumerable EnumerateInstalledLanguages(bool excludeC
}
catch (Exception ex)
{
- Log.Exception(ex);
+ _logger?.LogError(ex, "Exception in EnumerateInstalledLanguages");
}
}
@@ -114,7 +116,7 @@ public static IEnumerable GetInstalledLangugageDirectories()
}
catch (Exception ex)
{
- Log.Verbose("Language detect: Skipping folder " + dir + ". " + ex.Message);
+ _logger?.LogDebug("Language detect: Skipping folder {Dir}. {Message}", dir, ex.Message);
}
}
@@ -151,7 +153,7 @@ public static void InstallLanguageForUser(String baseDir = null)
var targetDir = Path.Combine(UserManager.CurrentUserDir, language);
- Log.Debug("Copy directory " + srcDir + "=> " + targetDir);
+ _logger?.LogDebug("Copy directory {SrcDir} => {TargetDir}", srcDir, targetDir);
FileUtils.CopyDir(srcDir, targetDir);
}
@@ -228,7 +230,7 @@ public static void SetCulture(String language = "en")
//TODO: Code Smell
if (!Directory.Exists(resourcesDir) || !File.Exists(resourceDll))
{
- Log.Warn(language + " resources not found. Will use English as the default");
+ _logger?.LogWarning("{Language} resources not found. Will use English as the default", language);
culture = CultureInfo.CreateSpecificCulture("en");
}
@@ -237,7 +239,7 @@ public static void SetCulture(String language = "en")
}
catch (Exception ex)
{
- Log.Error("Error setting culture to " + language + ", " + ex + ", will use English as the default");
+ _logger?.LogError(ex, "Error setting culture to {Language}, will use English as the default", language);
CultureInfo.DefaultThreadCurrentCulture = CultureInfo.CreateSpecificCulture("en");
CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.CreateSpecificCulture("en");
}
diff --git a/src/Libraries/ACATCore/Utility/SoundManager.cs b/src/Libraries/ACATCore/Utility/SoundManager.cs
index bcd05790..50194f17 100644
--- a/src/Libraries/ACATCore/Utility/SoundManager.cs
+++ b/src/Libraries/ACATCore/Utility/SoundManager.cs
@@ -10,14 +10,16 @@
using System;
using System.Collections.Generic;
using System.Media;
+using Microsoft.Extensions.Logging;
namespace ACAT.Core.Utility
{
///
- /// Class that use the C:\Windows\Media Sounds
+ /// Class that use the C:\\Windows\\Media Sounds
///
public class SoundManager
{
+ private static ILogger _logger;
///
/// Are the sounds initialized
///
@@ -101,7 +103,7 @@ public static void playSound(SoundType soundType, string customPath = null)
}
catch (Exception ex)
{
- Log.Exception("Error playing Sound: " + ex);
+ _logger?.LogError(ex, "Error playing Sound");
}
}
@@ -120,7 +122,7 @@ private static void SetSoundFile(SoundPlayer player, string soundFilePath)
player.Play();
}
else
- Log.Debug("_soundPlayer object was null");
+ _logger?.LogDebug("_soundPlayer object was null");
}
///
@@ -138,7 +140,7 @@ private static void SetSoundFileSync(SoundPlayer player, string soundFilePath)
player.PlaySync();
}
else
- Log.Debug("_soundPlayer object was null");
+ _logger?.LogDebug("_soundPlayer object was null");
}
private static void SetSounds()
diff --git a/src/Libraries/ACATCore/Utility/TextUtils.cs b/src/Libraries/ACATCore/Utility/TextUtils.cs
index 86dcb8fb..c5a9a018 100644
--- a/src/Libraries/ACATCore/Utility/TextUtils.cs
+++ b/src/Libraries/ACATCore/Utility/TextUtils.cs
@@ -8,6 +8,7 @@
using System;
using System.Text;
using System.Windows.Forms;
+using Microsoft.Extensions.Logging;
namespace ACAT.Core.Utility
{
@@ -17,6 +18,7 @@ namespace ACAT.Core.Utility
///
public class TextUtils
{
+ private static ILogger _logger;
///
/// Converts a byte array into a hex string
///
@@ -40,7 +42,7 @@ public static string ByteArrayToHexString(byte[] byteArray)
///
public static String Capitalize(String word)
{
- Log.Debug(word);
+ _logger?.LogDebug("{Word}", word);
if (String.IsNullOrEmpty(word))
{
return word;
@@ -59,7 +61,7 @@ public static String Capitalize(String word)
}
char c = word[index];
- Log.Debug("index: " + index + "c: " + c.ToString());
+ _logger?.LogDebug("index: {Index}, c: {Char}", index, c);
if (!Char.IsLetter(c) || Char.IsUpper(c))
{
@@ -69,7 +71,7 @@ public static String Capitalize(String word)
word = word.Remove(index, 1);
c = Char.ToUpper(c);
word = word.Insert(index, c.ToString());
- Log.Debug("returning " + word);
+ _logger?.LogDebug("returning {Word}", word);
return word;
}
@@ -95,7 +97,7 @@ public static bool CheckInsertOrReplaceWord(String inputString, int caretPos, ou
if (String.IsNullOrEmpty(inputString))
{
- Log.Debug("NULL string. return true " + insertOrReplaceOffset);
+ _logger?.LogDebug("NULL string. return true {Offset}", insertOrReplaceOffset);
return true;
}
diff --git a/src/Libraries/ACATCore/Utility/TypeLoader/TypeLoader.cs b/src/Libraries/ACATCore/Utility/TypeLoader/TypeLoader.cs
index c7697fed..3ef5533d 100644
--- a/src/Libraries/ACATCore/Utility/TypeLoader/TypeLoader.cs
+++ b/src/Libraries/ACATCore/Utility/TypeLoader/TypeLoader.cs
@@ -3,12 +3,14 @@
using System.IO;
using System.Linq;
using System.Reflection;
+using Microsoft.Extensions.Logging;
namespace ACAT.Core.Utility.TypeLoader
{
public class TypeLoader : ITypeLoader