diff --git a/src/Applications/ACATApp/Program.cs b/src/Applications/ACATApp/Program.cs index fe08c339..52ddca7c 100644 --- a/src/Applications/ACATApp/Program.cs +++ b/src/Applications/ACATApp/Program.cs @@ -22,10 +22,10 @@ using ACAT.Extension; using ACAT.Extension.CommandHandlers; using ACATResources; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using System; using System.Windows.Forms; -using System.Windows.Navigation; namespace ACATApp { @@ -36,8 +36,9 @@ namespace ACATApp internal static class Program { private static Splash splash = null; - private static Microsoft.Extensions.Logging.ILoggerFactory modernLoggingFactory = null; + private static ILoggerFactory modernLoggingFactory = null; private static ILogger _logger; + private static IServiceProvider _serviceProvider; /// /// The main entry point for the application. @@ -56,6 +57,7 @@ public static void Main(string[] args) InitializeGlobals(); InitializeUser(); InitializeLogging(); + InitializeDependencyInjection(); InitializeContext(); if (!PerformOnboarding()) @@ -101,14 +103,31 @@ private static void InitializeLogging() { // Initialize legacy logging Log.SetupListeners(); - - // Initialize modern logging infrastructure (ticket #3) + + // Initialize modern logging infrastructure modernLoggingFactory = LoggingConfiguration.CreateLoggerFactory(); _logger = modernLoggingFactory.CreateLogger(typeof(Program)); _logger.LogDebug("ACAT Dashboard Application Launch"); } + private static void InitializeDependencyInjection() + { + // Set up dependency injection for extension instantiation + var services = new ServiceCollection(); + + // Add logging (reuse existing factory) + services.AddSingleton(modernLoggingFactory); + services.AddLogging(); + + _serviceProvider = services.BuildServiceProvider(); + + // Make service provider available to Context for extension loading + Context.ServiceProvider = _serviceProvider; + + _logger.LogDebug("Dependency injection initialized"); + } + private static void InitializeUser() { AppCommon.SetUserName(); @@ -213,7 +232,7 @@ private static void ShutdownApplication() Context.Dispose(); Common.Uninit(); CloseSplashScreen(); - _logger.LogDebug("ACATTalk Application shutdown"); + _logger.LogDebug("ACAT Dashboard Application shutdown"); Log.Close(); modernLoggingFactory?.Dispose(); AppCommon.OnExit(); diff --git a/src/Applications/ACATConfigNext/Forms/SettingsForm.cs b/src/Applications/ACATConfigNext/Forms/SettingsForm.cs index fc33658f..3faec7d2 100644 --- a/src/Applications/ACATConfigNext/Forms/SettingsForm.cs +++ b/src/Applications/ACATConfigNext/Forms/SettingsForm.cs @@ -6,6 +6,7 @@ using ACAT.Core.WidgetManagement; using ACAT.Extension; using ACATConfigNext.UserControls; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; @@ -20,6 +21,7 @@ namespace ACATConfigNext.Forms public class SettingsForm : Form { private readonly ILogger _logger; + private readonly IServiceProvider _serviceProvider; private TableLayoutPanel basePanel; private FlowLayoutPanel leftPanel; private TableLayoutPanel navPanel; @@ -42,13 +44,13 @@ public class SettingsForm : Form private bool _isDirty = false; - public SettingsForm(ILogger logger) + public SettingsForm(ILogger logger, IServiceProvider serviceProvider) { _logger = logger; + _serviceProvider = serviceProvider; WpfInitializationHelper.EnsureApplicationResources(); InitializeComponent(); - } private FlowLayoutPanel CreateLeftPanel() @@ -159,7 +161,7 @@ private void ButtonClicked_Save(object sender, EventArgs e) } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, "Error occurred while saving settings"); MessageBox.Show("An error occurred while saving settings.", "Save Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } @@ -410,6 +412,12 @@ private void CopyPreferencesValues(IPreferences source, IPreferences target) } } + private object CreateExtensionInstance(Type type) + { + // Use shared helper method for consistent extension instantiation across all applications + return ExtensionHelper.CreateExtensionInstance(_serviceProvider, type, _logger); + } + private IEnumerable LoadSettings(string category) { @@ -431,7 +439,7 @@ private IEnumerable LoadSettings(string category) { var wordPredictorTypes = Context.AppWordPredictionManager.WordPredictorExtensions; var wordPredictorExtensions = wordPredictorTypes - .Select(type => Activator.CreateInstance(type) as IExtension) + .Select(type => CreateExtensionInstance(type) as IExtension) .Where(instance => instance != null); return wordPredictorExtensions; @@ -443,7 +451,7 @@ private IEnumerable LoadSettings(string category) { var ttsEngineTypes = Context.AppTTSManager.GetExtensions(); var ttsExtensions = ttsEngineTypes - .Select(type => Activator.CreateInstance(type) as IExtension) + .Select(type => CreateExtensionInstance(type) as IExtension) .Where(instance => instance != null); return ttsExtensions; } diff --git a/src/Applications/ACATConfigNext/Program.cs b/src/Applications/ACATConfigNext/Program.cs index 0675da92..96b4487a 100644 --- a/src/Applications/ACATConfigNext/Program.cs +++ b/src/Applications/ACATConfigNext/Program.cs @@ -1,4 +1,6 @@ using ACATConfigNext.Forms; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; using System; using System.Windows.Forms; @@ -15,7 +17,27 @@ static void Main() Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); - Application.Run(new SettingsForm()); + // Set up dependency injection + var services = new ServiceCollection(); + ConfigureServices(services); + var serviceProvider = services.BuildServiceProvider(); + + // Get SettingsForm from DI container + var settingsForm = serviceProvider.GetRequiredService(); + Application.Run(settingsForm); + } + + private static void ConfigureServices(IServiceCollection services) + { + // Configure logging + services.AddLogging(builder => + { + builder.AddConsole(); + builder.SetMinimumLevel(LogLevel.Information); + }); + + // Register SettingsForm - IServiceProvider will be injected automatically + services.AddTransient(); } } } \ No newline at end of file diff --git a/src/Applications/ACATTalk/Program.cs b/src/Applications/ACATTalk/Program.cs index 9aa8a71e..bc4e29d0 100644 --- a/src/Applications/ACATTalk/Program.cs +++ b/src/Applications/ACATTalk/Program.cs @@ -22,6 +22,7 @@ using ACAT.Extension; using ACAT.Extension.CommandHandlers; using ACATResources; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using System; using System.Windows.Forms; @@ -34,7 +35,9 @@ namespace ACATTalk internal static class Program { private static Splash splash = null; + private static ILoggerFactory modernLoggingFactory = null; private static ILogger _logger; + private static IServiceProvider _serviceProvider; /// /// The main entry point for the application. @@ -50,11 +53,6 @@ public static void Main(string[] args) Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); - //if (!AppCommon.CheckFontsInstalled()) - //{ - // return; - //} - CoreGlobals.AppId = "ACATTalk"; CoreGlobals.ACATUserGuideFileName = "ACAT User Guide.pdf"; FatalErrorHandler.EvtFatalError += CoreGlobals_EvtFatalError; @@ -66,8 +64,6 @@ public static void Main(string[] args) AppCommon.SetUserName(); AppCommon.SetProfileName(); - bool freshInstallForUser = !UserManager.UserExists(UserManager.CurrentUser); - if (!AppCommon.CreateUserAndProfile()) { return; @@ -91,12 +87,17 @@ public static void Main(string[] args) // Initialize legacy logging system Log.SetupListeners(); - // Initialize modern logging infrastructure (ticket #3) - var modernLoggingFactory = LoggingConfiguration.CreateLoggerFactory(); + // Initialize modern logging infrastructure FIRST - before anything else needs it + modernLoggingFactory = LoggingConfiguration.CreateLoggerFactory(); + LogManager.Initialize(modernLoggingFactory); // Initialize global logger manager + _logger = modernLoggingFactory.CreateLogger(typeof(Program)); _logger.LogDebug("ACAT Talk Application Launch"); + // Set up dependency injection for extension instantiation + InitializeDependencyInjection(); + AuditLog.Audit(new AuditEvent("Application", "start")); CommandDescriptors.Init(); @@ -193,7 +194,6 @@ public static void Main(string[] args) Common.Uninit(); - splash?.Close(); splash = null; @@ -211,6 +211,23 @@ public static void Main(string[] args) AppCommon.OnExit(); } + private static void InitializeDependencyInjection() + { + // Set up dependency injection for extension instantiation + var services = new ServiceCollection(); + + // Add logging (reuse existing factory) + services.AddSingleton(modernLoggingFactory); + services.AddLogging(); + + _serviceProvider = services.BuildServiceProvider(); + + // Make service provider available to Context for extension loading + Context.ServiceProvider = _serviceProvider; + + _logger.LogDebug("Dependency injection initialized"); + } + /// /// A fatal error has occurred. Try and gracefully exit ACAT /// @@ -219,7 +236,6 @@ private static void CoreGlobals_EvtFatalError(string reason) { splash?.Close(); - if (Context.AppPanelManager != null && Context.AppPanelManager.GetCurrentForm() != null && Context.AppPanelManager.GetCurrentForm().PanelCommon != null && Context.AppPanelManager.GetCurrentForm().PanelCommon.RootWidget != null) { diff --git a/src/Applications/AppCommon/ExtensionHelper.cs b/src/Applications/AppCommon/ExtensionHelper.cs new file mode 100644 index 00000000..936f4000 --- /dev/null +++ b/src/Applications/AppCommon/ExtensionHelper.cs @@ -0,0 +1,46 @@ +using ACAT.Core.Extensions; +using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; + +namespace ACAT.Applications +{ + /// + /// Helper class for creating extension instances with proper dependency injection + /// Wrapper around ExtensionInstantiator from ACAT.Core for backward compatibility + /// + public static class ExtensionHelper + { + /// + /// Creates instances of extension types using dependency injection. + /// This ensures extensions receive proper logger instances and other registered services. + /// + /// The service provider for dependency resolution + /// Collection of extension types to instantiate + /// Optional logger for diagnostics + /// Collection of successfully created extension instances + public static IEnumerable CreateExtensionInstances( + IServiceProvider serviceProvider, + IEnumerable extensionTypes, + ILogger logger = null) + { + return ExtensionInstantiator.CreateExtensionInstances(serviceProvider, extensionTypes, logger); + } + + /// + /// Creates a single extension instance using dependency injection + /// + /// The service provider for dependency resolution + /// The extension type to instantiate + /// Optional logger for diagnostics + /// The created extension instance, or null if creation fails + public static IExtension CreateExtensionInstance( + IServiceProvider serviceProvider, + Type extensionType, + ILogger logger = null) + { + return ExtensionInstantiator.CreateExtensionInstance(serviceProvider, extensionType, logger) as IExtension; + } + } +} diff --git a/src/Applications/AppCommon/Onboarding.cs b/src/Applications/AppCommon/Onboarding.cs index 15bba16f..f455dc25 100644 --- a/src/Applications/AppCommon/Onboarding.cs +++ b/src/Applications/AppCommon/Onboarding.cs @@ -50,7 +50,7 @@ public static bool DoOnboarding() public static bool ResetAllPreferences(List currentCategory) { - var logger = LoggingConfiguration.CreateLogger(typeof(AppCommon)); + var logger = LoggingConfiguration.CreateLogger(); try { // Reset general preferences @@ -91,7 +91,7 @@ public static bool ResetAllPreferences(List currentCategory private static void CopyPreferencesValues(IPreferences source, IPreferences target) { - var logger = LoggingConfiguration.CreateLogger(typeof(AppCommon)); + var logger = LoggingConfiguration.CreateLogger(); var sourceType = source.GetType(); var targetType = target.GetType(); diff --git a/src/Extensions/ACAT.Extensions.Onboarding/Onboarding/OnboardingLanguageSelect.cs b/src/Extensions/ACAT.Extensions.Onboarding/Onboarding/OnboardingLanguageSelect.cs index 030ede7e..9e28a146 100644 --- a/src/Extensions/ACAT.Extensions.Onboarding/Onboarding/OnboardingLanguageSelect.cs +++ b/src/Extensions/ACAT.Extensions.Onboarding/Onboarding/OnboardingLanguageSelect.cs @@ -9,6 +9,7 @@ using ACAT.Extensions.Onboarding.UI.UserControls; using ACAT.Extensions.Onboarding.UI; using ACAT.Core.CoreInterfaces; +using Microsoft.Extensions.Logging; using System.Globalization; namespace ACAT.Extensions.Onboarding.Onboarding @@ -25,8 +26,14 @@ public class OnboardingLanguageSelect : OnboardingExtensionBase // TODO - Localize Me private const string Step1 = "STEP 1"; + private readonly ILogger _logger; private IOnboardingWizard _wizard; + public OnboardingLanguageSelect() + { + _logger = LoggingConfiguration.CreateLogger(); + } + public override ClassDescriptorAttribute Descriptor { get { return ClassDescriptorAttribute.GetDescriptor(GetType()); } @@ -85,7 +92,7 @@ public override void OnEndStep(IOnboardingUserControl userControl, Reason reason { case Step1: var cultureInfo = userControlLang.currentCulture; - Log.Debug ("User selected language: " + cultureInfo.DisplayName); + _logger.LogDebug("User selected language: {LanguageName}", cultureInfo.DisplayName); CoreGlobals.AppPreferences.Language = cultureInfo.TwoLetterISOLanguageName; CoreGlobals.AppPreferences.Save(); diff --git a/src/Extensions/ACAT.Extensions.Onboarding/UI/UserControls/UserControlHardwareSwitchSetup.cs b/src/Extensions/ACAT.Extensions.Onboarding/UI/UserControls/UserControlHardwareSwitchSetup.cs index 9608c041..ba664330 100644 --- a/src/Extensions/ACAT.Extensions.Onboarding/UI/UserControls/UserControlHardwareSwitchSetup.cs +++ b/src/Extensions/ACAT.Extensions.Onboarding/UI/UserControls/UserControlHardwareSwitchSetup.cs @@ -481,7 +481,7 @@ private void UserControlHardwareSwitchSetup_Load(object sender, EventArgs e) } String html = String.Format(_htmlTemplate, headStyle, bodyStyle, textStyle, "Click here for help"); - Log.Debug(html); + _logger.LogDebug("Generated HTML: {Html}", html); webBrowser.DocumentText = html; //webBrowser.DocumentText = diff --git a/src/Extensions/ACAT.Extensions.Onboarding/UI/UserControls/UserControlHardwareSwitchTest.cs b/src/Extensions/ACAT.Extensions.Onboarding/UI/UserControls/UserControlHardwareSwitchTest.cs index 72046ee3..23a0a191 100644 --- a/src/Extensions/ACAT.Extensions.Onboarding/UI/UserControls/UserControlHardwareSwitchTest.cs +++ b/src/Extensions/ACAT.Extensions.Onboarding/UI/UserControls/UserControlHardwareSwitchTest.cs @@ -334,7 +334,7 @@ private void WebBrowser_Navigating(object sender, WebBrowserNavigatingEventArgs { var str = e.Url.ToString(); - Log.Debug("Url is [" + str + "]"); + _logger.LogDebug("Url is [{Url}]", str); if (str.ToLower().Contains("blank")) { diff --git a/src/Extensions/ACAT.Extensions.UI/Scanners/CursorNavigationScanner.cs b/src/Extensions/ACAT.Extensions.UI/Scanners/CursorNavigationScanner.cs index 82e5277b..f0d87793 100644 --- a/src/Extensions/ACAT.Extensions.UI/Scanners/CursorNavigationScanner.cs +++ b/src/Extensions/ACAT.Extensions.UI/Scanners/CursorNavigationScanner.cs @@ -179,7 +179,7 @@ public bool Initialize(StartupArg startupArg) if (!_scannerCommon.Initialize(startupArg)) { - Log.Warn("Could not initialize form " + Name); + _logger.LogWarning("Could not initialize form {Name}", Name); return false; } diff --git a/src/Extensions/ACAT.Extensions.UI/Scanners/WordPredictionSetModeScanner.cs b/src/Extensions/ACAT.Extensions.UI/Scanners/WordPredictionSetModeScanner.cs index a8fb706b..1639755f 100644 --- a/src/Extensions/ACAT.Extensions.UI/Scanners/WordPredictionSetModeScanner.cs +++ b/src/Extensions/ACAT.Extensions.UI/Scanners/WordPredictionSetModeScanner.cs @@ -52,7 +52,7 @@ public partial class WordPredictionSetModeScanner : HorizontalStripScanner /// /// Scanner class /// Title of the scanner - public WordPredictionSetModeScanner(String panelClass, String title) : base(panelClass, title) + public WordPredictionSetModeScanner(String panelClass, String title) : base(panelClass, title, null) { InitializeComponent(); _dispatcher = new Dispatcher(this); diff --git a/src/Extensions/ACAT.Extensions.UI/Scanners/YesNoResponseScanner.cs b/src/Extensions/ACAT.Extensions.UI/Scanners/YesNoResponseScanner.cs index b0488b21..38129f3d 100644 --- a/src/Extensions/ACAT.Extensions.UI/Scanners/YesNoResponseScanner.cs +++ b/src/Extensions/ACAT.Extensions.UI/Scanners/YesNoResponseScanner.cs @@ -218,7 +218,7 @@ public bool Initialize(StartupArg startupArg) if (!scannerCommon.Initialize(startupArg)) { - Log.Warn("Could not initialize form " + Name); + _logger.LogWarning("Could not initialize form {Name}", Name); return false; } @@ -354,8 +354,6 @@ private void YesNoResponseScanner_FormClosing(object sender, FormClosingEventArg /// private void YesNoResponseScanner_Load(object sender, EventArgs e) { - Log.Verbose(); - scannerCommon.OnLoad(); if (!String.IsNullOrEmpty(_title)) diff --git a/src/Extensions/ACAT.Extensions.UI/Scanners/YesNoScanner.cs b/src/Extensions/ACAT.Extensions.UI/Scanners/YesNoScanner.cs index 95a48612..d4cc3a1b 100644 --- a/src/Extensions/ACAT.Extensions.UI/Scanners/YesNoScanner.cs +++ b/src/Extensions/ACAT.Extensions.UI/Scanners/YesNoScanner.cs @@ -199,7 +199,7 @@ protected override CreateParams CreateParams { get { - _logger.LogTrace("CreateParams"); + _logger?.LogTrace("CreateParams"); return Windows.SetFormStyles(base.CreateParams); } } @@ -238,7 +238,7 @@ public ExtensionInvoker GetInvoker() /// true on success public bool Initialize(StartupArg startupArg) { - _logger.LogTrace("Initialize"); + _logger?.LogTrace("Initialize"); PanelClass = startupArg.PanelClass; startupCommandArg = startupArg.Arg; this.startupArg = startupArg; @@ -247,7 +247,7 @@ public bool Initialize(StartupArg startupArg) if (!scannerCommon.Initialize(startupArg)) { - Log.Warn("Could not initialize form " + Name); + _logger.LogWarning("Could not initialize form {Name}", Name); return false; } @@ -270,7 +270,7 @@ public void OnFocusChanged(WindowActivityMonitorInfo monitorInfo) /// public virtual void OnPause() { - _logger.LogTrace("OnPause"); + _logger?.LogTrace("OnPause"); scannerCommon.OnPause(); } @@ -290,7 +290,7 @@ public bool OnQueryPanelChange(PanelRequestEventArgs arg) /// public virtual void OnResume() { - _logger.LogTrace("OnResume"); + _logger?.LogTrace("OnResume"); scannerCommon.OnResume(); } @@ -432,8 +432,6 @@ private void YesNoScanner_FormClosing(object sender, FormClosingEventArgs e) /// private void YesNoScanner_Load(object sender, EventArgs e) { - Log.Verbose(); - scannerCommon.OnLoad(); var widget = PanelCommon.RootWidget.Finder.FindChild("Prompt"); diff --git a/src/Extensions/ACAT.Extensions.UI/UserControls/SentencePredictionUserControl.cs b/src/Extensions/ACAT.Extensions.UI/UserControls/SentencePredictionUserControl.cs index 412608bd..80d0669c 100644 --- a/src/Extensions/ACAT.Extensions.UI/UserControls/SentencePredictionUserControl.cs +++ b/src/Extensions/ACAT.Extensions.UI/UserControls/SentencePredictionUserControl.cs @@ -31,18 +31,16 @@ namespace ACAT.Extensions.UI.UserControls "User Control for Sentence Prediction")] public partial class SentencePredictionUserControl : KeyboardUserControl { - private readonly ILogger _logger; private UserControlWordPredictionCommon _userControlWordPredictionCommon; public SentencePredictionUserControl() { - _logger = LoggingConfiguration.CreateLogger(); InitializeComponent(); } protected override bool HandleInitialize() { - _userControlWordPredictionCommon = new UserControlWordPredictionCommon(this, _keybordUserControlCommon.TextController, _keybordUserControlCommon.ScannerPanel, new PredictionTypes[] { PredictionTypes.Sentences }); + _userControlWordPredictionCommon = new UserControlWordPredictionCommon(this, _keybordUserControlCommon.TextController, _keybordUserControlCommon.ScannerPanel, new PredictionTypes[] { PredictionTypes.Sentences }, null); bool retVal = _userControlWordPredictionCommon.Initialize(_keybordUserControlCommon.RootWidget); return retVal; diff --git a/src/Extensions/ACAT.Extensions.UI/UserControls/Toolbars/LargeToolbarUserControl.cs b/src/Extensions/ACAT.Extensions.UI/UserControls/Toolbars/LargeToolbarUserControl.cs index 6379b534..27ce45ff 100644 --- a/src/Extensions/ACAT.Extensions.UI/UserControls/Toolbars/LargeToolbarUserControl.cs +++ b/src/Extensions/ACAT.Extensions.UI/UserControls/Toolbars/LargeToolbarUserControl.cs @@ -1,6 +1,7 @@ using ACAT.Core.Utility; using ACAT.Core.WidgetManagement; using ACAT.Extension.UI.UserControls; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.ComponentModel; @@ -55,6 +56,7 @@ protected class ButtonSpec } public LargeToolbarUserControl(string name) { + _logger = LoggingConfiguration.CreateLogger(); Name = name; InitializeButtonsList(); InitializeComponent(); @@ -154,7 +156,7 @@ protected virtual void InitializeComponent() protected override void OnPaint(PaintEventArgs e) { - Log.Debug($"{e.Graphics.DpiX} x {e.Graphics.DpiY}"); + _logger.LogDebug("{DpiX} x {DpiY}", e.Graphics.DpiX, e.Graphics.DpiY); e.Graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit; base.OnPaint(e); diff --git a/src/Extensions/ACAT.Extensions.UI/UserControls/Toolbars/LaunchAppUserControl.cs b/src/Extensions/ACAT.Extensions.UI/UserControls/Toolbars/LaunchAppUserControl.cs index 561412f9..3c2e72cd 100644 --- a/src/Extensions/ACAT.Extensions.UI/UserControls/Toolbars/LaunchAppUserControl.cs +++ b/src/Extensions/ACAT.Extensions.UI/UserControls/Toolbars/LaunchAppUserControl.cs @@ -1,6 +1,7 @@ using ACAT.Core.PanelManagement; using ACAT.Core.Utility; using ACAT.Core.WidgetManagement; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.ComponentModel; @@ -14,6 +15,8 @@ namespace ACAT.Extensions.UI.UserControls.Toolbars [DesignerCategory("code")] public class LaunchAppUserControl : LargeToolbarUserControl { + private static readonly ILogger _logger = LoggingConfiguration.CreateLogger(); + private class LaunchButtonSpec : ButtonSpec { public AppInfo AppInfo { get; set; } @@ -51,7 +54,7 @@ public LaunchAppUserControl() : base("LaunchAppUserControl") public override void OnButtonClicked(object s, EventArgs e) { string buttonName = e.ToString(); - Log.Info($"Button clicked: {buttonName}"); + _logger.LogInformation("Button clicked: {ButtonName}", buttonName); var dict = Buttons.ToDictionary(x => x.Name); diff --git a/src/Extensions/ACAT.Extensions.UI/UserControls/WordPredictionUserControl.cs b/src/Extensions/ACAT.Extensions.UI/UserControls/WordPredictionUserControl.cs index 96959718..ac9a1b3b 100644 --- a/src/Extensions/ACAT.Extensions.UI/UserControls/WordPredictionUserControl.cs +++ b/src/Extensions/ACAT.Extensions.UI/UserControls/WordPredictionUserControl.cs @@ -37,7 +37,7 @@ public override bool Initialize(UserControlConfigMapEntry mapEntry, TextControll { base.Initialize(mapEntry, textController, scanner); - _userControlWordPredictionCommon = new UserControlWordPredictionCommon(this, textController, scanner, new PredictionTypes[] { PredictionTypes.Words }); + _userControlWordPredictionCommon = new UserControlWordPredictionCommon(this, textController, scanner, new PredictionTypes[] { PredictionTypes.Words }, null); bool retVal = _userControlWordPredictionCommon.Initialize(_keybordUserControlCommon.RootWidget); return retVal; } diff --git a/src/Extensions/BCI/ACAT.Extensions.BCI.UI/Scanners/TalkApplicationBCIScanner.cs b/src/Extensions/BCI/ACAT.Extensions.BCI.UI/Scanners/TalkApplicationBCIScanner.cs index 4913dfa5..76959dd2 100644 --- a/src/Extensions/BCI/ACAT.Extensions.BCI.UI/Scanners/TalkApplicationBCIScanner.cs +++ b/src/Extensions/BCI/ACAT.Extensions.BCI.UI/Scanners/TalkApplicationBCIScanner.cs @@ -34,6 +34,7 @@ using ACAT.Extensions.BCI.Common.BCIInterfaceUtilities; using ACAT.Extensions.BCI.UI.UserControls; using ACATResources; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; @@ -65,6 +66,11 @@ public partial class TalkApplicationBCIScanner : Form, IScannerPanel, ISupportsS /// private readonly Dispatcher _dispatcher; + /// + /// Logger instance for this class + /// + private readonly ILogger _logger; + /// /// The AlphabetScannerCommon object. Has a number of /// helper functions @@ -187,8 +193,9 @@ public partial class TalkApplicationBCIScanner : Form, IScannerPanel, ISupportsS /// /// Initializes a new instance of the class. /// - public TalkApplicationBCIScanner() + public TalkApplicationBCIScanner(ILogger logger = null) { + _logger = logger; _scannerCommon = new ScannerCommon(this); InitializeComponent(); this.DoubleBuffered = true; @@ -737,7 +744,7 @@ private void BciActuator_EvtIoctlResponse(int opcode, object response) { if (!_RequestCalibration)//have a delay before start typing so the user can see the options and suggestions and start looking where is desired { - Log.Debug("BCI LOG | Delay before Typing ");//Run the delay in another therad to avoid blocking the UI + _logger?.LogDebug("BCI LOG | Delay before Typing ");//Run the delay in another therad to avoid blocking the UI _ = ShowTimedMessageBoxAsync().ConfigureAwait(false); } else @@ -752,14 +759,14 @@ private void BciActuator_EvtIoctlResponse(int opcode, object response) if (_BCIState == BCIState.BCIStartSession) { _BCIState = BCIState.BCIInitDone; - Log.Debug("BCI LOG | BCI Init state: " + BCIState.BCIInitDone); + _logger?.LogDebug("BCI LOG | BCI Init state: {State}", BCIState.BCIInitDone); } break; case (int)OpCodes.SendCalibrationStatus: //STEP - 1 var bciCalibrationStatus = response as BCICalibrationStatus; - Log.Debug("BCI LOG | bciCalibrationStatus.OkToGoToTyping: " + bciCalibrationStatus.OkToGoToTyping); + _logger?.LogDebug("BCI LOG | bciCalibrationStatus.OkToGoToTyping: {OkToGoToTyping}", bciCalibrationStatus.OkToGoToTyping); if (_ShowMainOptions)//This window should only display once { _ShowMainOptions = false; @@ -988,7 +995,7 @@ private void BCIShowRecalibrationWindowMessage() } catch (Exception es) { - Log.Exception("BCI LOG | " + es.Message.ToString()); + _logger?.LogError("BCI LOG | {Message}", es.Message.ToString()); } } @@ -1006,32 +1013,32 @@ private void BCIUpdateBCI(BCIState bCIState) break; case BCIState.UIRefresh://1 Init state - Log.Debug("BCI LOG | BCI Init state: " + BCIState.UIRefresh); + _logger?.LogDebug("BCI LOG | BCI Init state: {State}", BCIState.UIRefresh); _BCIState = BCIState.UIRefresh; _ = ControlsUIAdjustment().ConfigureAwait(false); break; case BCIState.Initializing://2 Init state - Log.Debug("BCI LOG | BCI Init state: " + BCIState.Initializing); + _logger?.LogDebug("BCI LOG | BCI Init state: {State}", BCIState.Initializing); _BCIState = BCIState.Initializing; _ = InitializeBCI().ConfigureAwait(false); break; case BCIState.ReqCalibrationStatus://3 Init state _BCIState = BCIState.ReqCalibrationStatus; - Log.Debug("BCI LOG | BCI Init state: " + BCIState.ReqCalibrationStatus); + _logger?.LogDebug("BCI LOG | BCI Init state: {State}", BCIState.ReqCalibrationStatus); _ = BCIRequestCalibrationStatus().ConfigureAwait(false); break; case BCIState.StartBCIReqParams://4 Init state //STEP - 4 - Log.Debug("BCI LOG | BCI Init state: " + BCIState.StartBCIReqParams); + _logger?.LogDebug("BCI LOG | BCI Init state: {State}", BCIState.StartBCIReqParams); _BCIState = BCIState.StartBCIReqParams; _ = BCIStartBCIReqParams().ConfigureAwait(false); break; case BCIState.BCIStartSession://5 Init state - Log.Debug("BCI LOG | BCI Init state: " + BCIState.BCIStartSession); + _logger?.LogDebug("BCI LOG | BCI Init state: {State}", BCIState.BCIStartSession); _BCIState = BCIState.BCIStartSession; _ = BCIStartSession().ConfigureAwait(false); break; @@ -1039,7 +1046,7 @@ private void BCIUpdateBCI(BCIState bCIState) } catch (Exception ex) { - Log.Exception("BCI LOG | Error in BCI Init state: " + bCIState + " Messagge: " + ex.Message); + _logger?.LogError("BCI LOG | Error in BCI Init state: {State} Message: {Message}", bCIState, ex.Message); } } @@ -1129,7 +1136,7 @@ private void ExitApplication() } catch (Exception e) { - Log.Exception("BCI LOG | Error in ExitApplication() BCI: " + e.Message); + _logger?.LogError("BCI LOG | Error in ExitApplication() BCI: {Message}", e.Message); } } @@ -1250,8 +1257,8 @@ private void LearnCannedPhrases(string textToLearn) private void LogAssemblyVersion() { var version = ACATPreferences.ApplicationAssembly.GetName().Version.Major + "." + ACATPreferences.ApplicationAssembly.GetName().Version.Minor; - Log.Debug("BCI LOG | ACAT - Assembly version info"); - Log.Debug("BCI LOG | AssemblyVersion: " + version); + _logger?.LogDebug("BCI LOG | ACAT - Assembly version info"); + _logger?.LogDebug("BCI LOG | AssemblyVersion: {Version}", version); } /// @@ -1348,7 +1355,7 @@ private void SetCaretPositionForTextBoxUC(UserControl userControl, Control panel if (BCIInterfaceUtils.GetCaretPositionOfTextBoxUC() != currentCaretPosition) { Windows.SetCaretPosition(_textBoxTalkWindow, BCIInterfaceUtils.GetCaretPositionOfTextBoxUC()); - Log.Debug("BCI LOG | Caret position reestablish | Textbox user control changed"); + _logger?.LogDebug("BCI LOG | Caret position reestablish | Textbox user control changed"); } } } @@ -1359,14 +1366,14 @@ private void SetCaretPositionForTextBoxUC(UserControl userControl, Control panel if (BCIInterfaceUtils.GetCaretPhrasePositionOfTextBoxUC() != currentCaretPosition) { Windows.SetCaretPosition(_textBoxTalkWindow, BCIInterfaceUtils.GetCaretPhrasePositionOfTextBoxUC()); - Log.Debug("BCI LOG | Caret position reestablish | Textbox user control changed"); + _logger?.LogDebug("BCI LOG | Caret position reestablish | Textbox user control changed"); } } } } catch (Exception ex) { - Log.Debug("BCI LOG | Error | SetCaretPositionForTextBoxUC: " + ex.Message); + _logger?.LogDebug("BCI LOG | Error | SetCaretPositionForTextBoxUC: {Message}", ex.Message); } } @@ -1540,7 +1547,7 @@ private void TextBoxTalkWindowOnKeyPress(object sender, KeyPressEventArgs keyPre } catch (Exception ex) { - Log.Exception(ex); + _logger?.LogError(ex, ex.Message); } } @@ -1552,9 +1559,9 @@ private void TextToSpeech(String text) { if (!String.IsNullOrEmpty(text)) { - Log.Debug("*** TTS *** : " + text); + _logger?.LogDebug("*** TTS *** : {Text}", text); TTSManager.Instance.ActiveEngine.Speak(text); - Log.Debug("*** TTS *** : sent text!"); + _logger?.LogDebug("*** TTS *** : sent text!"); AuditLog.Audit(new AuditEventTextToSpeech(TTSManager.Instance.ActiveEngine.Descriptor.Name)); } @@ -1639,6 +1646,8 @@ private void UpdatetextBoxEvt(string message) /// private class CommandHandler : RunCommandHandler { + private static ILogger _logger; + /// /// Initializes a new instance of the class. /// @@ -1648,6 +1657,15 @@ public CommandHandler(String cmd) { } + /// + /// Sets the logger instance for the command handler + /// + /// logger instance + public static void SetLogger(ILogger logger) + { + _logger = logger; + } + /// /// Executes the command /// @@ -1660,7 +1678,7 @@ public override bool Execute(ref bool handled) { handled = true; List[] widgets; - Log.Debug("BCI LOG | Command | selected | Pressed | " + Command.ToString()); + _logger?.LogDebug("BCI LOG | Command | selected | Pressed | {Command}", Command.ToString()); switch (Command) { case "CmdEditScanner": @@ -1871,7 +1889,7 @@ public override bool Execute(ref bool handled) } } else - Log.Debug("BCI LOG | Command | selected | Pressed in calibration | No action | " + Command.ToString()); + _logger?.LogDebug("BCI LOG | Command | selected | Pressed in calibration | No action | {Command}", Command.ToString()); return true; } } @@ -1888,6 +1906,13 @@ private class Dispatcher : DefaultCommandDispatcher public Dispatcher(IScannerPanel panel) : base(panel) { + // Set the logger for CommandHandler + var form = panel.Form as TalkApplicationBCIScanner; + if (form != null) + { + CommandHandler.SetLogger(form._logger); + } + Commands.Add(new CommandHandler("CmdEditScanner")); Commands.Add(new CommandHandler("CmdEntryModeSelect")); Commands.Add(new CommandHandler("CmdMenuScanner")); diff --git a/src/Extensions/BCI/ACAT.Extensions.BCI.UI/UserControls/PhrasesUserControlBCI.cs b/src/Extensions/BCI/ACAT.Extensions.BCI.UI/UserControls/PhrasesUserControlBCI.cs index 95fb1e47..dd16a226 100644 --- a/src/Extensions/BCI/ACAT.Extensions.BCI.UI/UserControls/PhrasesUserControlBCI.cs +++ b/src/Extensions/BCI/ACAT.Extensions.BCI.UI/UserControls/PhrasesUserControlBCI.cs @@ -44,7 +44,7 @@ public partial class PhrasesUserControlBCI : UserControl, IUserControl private UserControlWordPredictionCommon _sentencePredictionCommon; public PhrasesUserControlBCI(ILogger logger = null) { - _logger = logger ?? LoggerFactory.GetLogger(); + _logger = logger ?? LoggingConfiguration.CreateLogger(); InitializeComponent(); } @@ -95,7 +95,7 @@ public bool Initialize(UserControlConfigMapEntry mapEntry, TextController textCo _keyboardCommon = new UserControlKeyboardCommon(this, mapEntry, textController, scanner); - _sentencePredictionCommon = new UserControlWordPredictionCommon(this, textController, scanner, new PredictionTypes[] { PredictionTypes.Sentences}); + _sentencePredictionCommon = new UserControlWordPredictionCommon(this, textController, scanner, new PredictionTypes[] { PredictionTypes.Sentences}, null); _scanner = scanner; diff --git a/src/Extensions/BCI/ACAT.Extensions.BCI.UI/UserControls/TTSYesNoUserControlBCI.cs b/src/Extensions/BCI/ACAT.Extensions.BCI.UI/UserControls/TTSYesNoUserControlBCI.cs index a71971dc..c202069a 100644 --- a/src/Extensions/BCI/ACAT.Extensions.BCI.UI/UserControls/TTSYesNoUserControlBCI.cs +++ b/src/Extensions/BCI/ACAT.Extensions.BCI.UI/UserControls/TTSYesNoUserControlBCI.cs @@ -37,7 +37,7 @@ public partial class TTSYesNoUserControlBCI : UserControl, IUserControl public TTSYesNoUserControlBCI(ILogger logger = null) { - _logger = logger ?? LoggerFactory.GetLogger(); + _logger = logger ?? LoggingConfiguration.CreateLogger(); InitializeComponent(); } diff --git a/src/Extensions/BCI/ACAT.Extensions.BCI.UI/UserControls/TTSYesNoUserControlBCI2.cs b/src/Extensions/BCI/ACAT.Extensions.BCI.UI/UserControls/TTSYesNoUserControlBCI2.cs index a560f504..3cc9e443 100644 --- a/src/Extensions/BCI/ACAT.Extensions.BCI.UI/UserControls/TTSYesNoUserControlBCI2.cs +++ b/src/Extensions/BCI/ACAT.Extensions.BCI.UI/UserControls/TTSYesNoUserControlBCI2.cs @@ -37,7 +37,7 @@ public partial class TTSYesNoUserControlBCI2 : UserControl, IUserControl public TTSYesNoUserControlBCI2(ILogger logger = null) { - _logger = logger ?? LoggerFactory.GetLogger(); + _logger = logger ?? LoggingConfiguration.CreateLogger(); InitializeComponent(); } diff --git a/src/Extensions/BCI/ACAT.Extensions.BCI.UI/UserControls/WordPredictionUserControlBCI.cs b/src/Extensions/BCI/ACAT.Extensions.BCI.UI/UserControls/WordPredictionUserControlBCI.cs index a55dce13..c863b7e2 100644 --- a/src/Extensions/BCI/ACAT.Extensions.BCI.UI/UserControls/WordPredictionUserControlBCI.cs +++ b/src/Extensions/BCI/ACAT.Extensions.BCI.UI/UserControls/WordPredictionUserControlBCI.cs @@ -88,7 +88,7 @@ public bool Initialize(UserControlConfigMapEntry mapEntry, TextController textCo _keyboardCommon = new UserControlKeyboardCommon(this, mapEntry, textController, scanner); - _wordPredictionCommon = new UserControlWordPredictionCommon(this, textController, scanner, new PredictionTypes[] { PredictionTypes.Words }); + _wordPredictionCommon = new UserControlWordPredictionCommon(this, textController, scanner, new PredictionTypes[] { PredictionTypes.Words }, null); _scanner = scanner; diff --git a/src/Extensions/BCI/Actuators/BCIActuator/BCIActuator.cs b/src/Extensions/BCI/Actuators/BCIActuator/BCIActuator.cs index dea1f592..db6f9b8d 100644 --- a/src/Extensions/BCI/Actuators/BCIActuator/BCIActuator.cs +++ b/src/Extensions/BCI/Actuators/BCIActuator/BCIActuator.cs @@ -1,4 +1,4 @@ -//////////////////////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////////////////// // // Copyright 2013-2019; 2023 Intel Corporation // SPDX-License-Identifier: Apache-2.0 @@ -29,6 +29,7 @@ using ACAT.Extensions.BCI.Actuators.openBCISensorUI; using ACAT.Extensions.BCI.Common.BCIControl; using ACATResources; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.IO; @@ -45,6 +46,8 @@ namespace ACAT.Extensions.BCI.Actuators.BCIActuator "BCI Actuator")] internal class BCIActuator : ActuatorBase, ISupportsPreferences { + private readonly ILogger _logger; + /// /// The setting object for the box calibration /// @@ -214,6 +217,7 @@ internal class BCIActuator : ActuatorBase, ISupportsPreferences /// public BCIActuator() { + _logger = LoggingConfiguration.CreateLogger(); try { // Load settings @@ -249,7 +253,7 @@ public BCIActuator() } catch (Exception e) { - Log.Exception(e.Message); + _logger.LogError(e, "Failed to initialize BCIActuator"); } } @@ -273,7 +277,7 @@ private bool AreChannelsEqual(bool[] currentChannels, int[] classifierChannels) } catch (Exception e) { - Log.Exception("Exception: " + e.Message); + _logger.LogError(e, "Failed to compare channels"); } return equalChannels; } @@ -290,7 +294,7 @@ private Dictionary GetAvailableClassifiers() //If recheck needed, all classifiers need to be recalibrated if (BCISettingsFixed.SignalControl_RecheckNeeded) { - Log.Debug("Signal recheck needed.No available classifiers"); + _logger.LogDebug("Signal recheck needed.No available classifiers"); return availableClassifiers; } @@ -323,7 +327,7 @@ private Dictionary GetAvailableClassifiers() // NOTE: Status set to Expired, in a future release a new status should be created for this condition if (!AreChannelsEqual(currentChannels, tmpDecisionMaker.TrainedClassifiersObj.channelSubset)) { - Log.Debug("Classifier: " + scanSection + " - Different channels than calibration. Current channels will be used in calibration."); + _logger.LogDebug("Classifier: " + scanSection + " - Different channels than calibration. Current channels will be used in calibration."); classifierStatus = BCIClassifierStatus.Mismatch; } // Check if classifier expired @@ -338,14 +342,14 @@ private Dictionary GetAvailableClassifiers() // Add classifier to dictionary BCIClassifierInfo classifierInfo = new(isRequired, scanSection, classifierStatus, auc); availableClassifiers.Add(scanSection, classifierInfo); - Log.Debug("Classifier: " + scanSection + " found | AUC:" + availableClassifiers[scanSection].Auc + " isRequired:" + isRequired + " Status:" + classifierStatus); + _logger.LogDebug("Classifier: " + scanSection + " found | AUC:" + availableClassifiers[scanSection].Auc + " isRequired:" + isRequired + " Status:" + classifierStatus); } } } } catch (Exception e) { - Log.Exception(e.Message); + _logger.LogError(e, "Failed to get available classifiers"); } return availableClassifiers; } @@ -370,11 +374,11 @@ private void LoadTypingMappings() }; foreach (KeyValuePair mapping in DictTypingCalibrationMappings) - Log.Debug("Typing section:" + mapping.Key + " Using classifier:" + mapping.Value); + _logger.LogDebug("Typing section:" + mapping.Key + " Using classifier:" + mapping.Value); } catch (Exception e) { - Log.Exception(e.Message); + _logger.LogError(e, "Failed to load typing mappings"); } } @@ -416,7 +420,7 @@ private bool LoadClassifiers() if (File.Exists(classifierFilePath)) { - Log.Debug("Section: " + typingMapping.Key + " | Loading classifier:" + typingMapping.Value + " from:" + classifierFilePath); + _logger.LogDebug("Section: " + typingMapping.Key + " | Loading classifier:" + typingMapping.Value + " from:" + classifierFilePath); DecisionMaker tmpDecisionMaker = new(classifierFilePath); if (tmpDecisionMaker != null && tmpDecisionMaker.TrainedClassifiersObj != null) @@ -430,7 +434,7 @@ private bool LoadClassifiers() { EEGProcessingGlobals.DecisionMakerDict.Add(typingMapping.Key, tmpDecisionMaker); - Log.Debug(typingMapping.Key.ToString() + " typing section - Using " + typingMapping.Value.ToString() + " classifier. Status: loaded"); + _logger.LogDebug(typingMapping.Key.ToString() + " typing section - Using " + typingMapping.Value.ToString() + " classifier. Status: loaded"); var bciLogEntry = new BCILogEntryClassifierLoaded() { @@ -451,19 +455,19 @@ private bool LoadClassifiers() else { missingClassifier = true; - Log.Warn(typingMapping.Key.ToString() + " typing section - Using " + typingMapping.Value.ToString() + " classifier. Status: missing!!"); + _logger.LogWarning(typingMapping.Key.ToString() + " typing section - Using " + typingMapping.Value.ToString() + " classifier. Status: missing!!"); } } else { missingClassifier = true; - Log.Warn(typingMapping.Key.ToString() + " typing section. Classifier file not found. - Using " + typingMapping.Value.ToString() + " classifier. Status: missing!!"); + _logger.LogWarning(typingMapping.Key.ToString() + " typing section. Classifier file not found. - Using " + typingMapping.Value.ToString() + " classifier. Status: missing!!"); } } } catch (Exception e) { - Log.Exception(e.Message); + _logger.LogError(e, "Failed to load classifiers"); return false; } return !missingClassifier; @@ -556,12 +560,12 @@ public override bool PostInit() if (_daqInstance.GetType() == typeof(DAQ_gTecBCI)) { - Log.Debug("startgTecUnicornTesting"); + _logger.LogDebug("startgTecUnicornTesting"); TestGtecDevice(); } else { - Log.Debug("startOpenBCITesting"); + _logger.LogDebug("startOpenBCITesting"); TestBCIDevices(); } @@ -584,7 +588,7 @@ public override bool IoctlRequest(int opcode, object request) { bool retVal = false; - Log.Debug("IoctRequest received: " + (OpCodes)opcode + " | Request: " + request); + _logger.LogDebug("IoctRequest received: " + (OpCodes)opcode + " | Request: " + request); switch (opcode) { @@ -716,7 +720,7 @@ protected override void Dispose(bool disposing) { try { - Log.Verbose(); + _logger.LogTrace("Disposing BCIActuator resources"); if (disposing) { @@ -754,10 +758,10 @@ private void bciDeviceTestingCompleted() actuatorState = (GTecDeviceTester.ExitOnboardingEarly) ? State.Stopped : State.Running; } - Log.Debug("\nbciDeviceTestingCompleted | actuatorState: " + actuatorState.ToString()); + _logger.LogDebug("\nbciDeviceTestingCompleted | actuatorState: " + actuatorState.ToString()); SendIoctlResponse((int)OpCodes.CalibrationWindowClose, String.Empty); - Log.Debug("IoctRequest " + OpCodes.CalibrationWindowClose + " sent. Message: empty"); + _logger.LogDebug("IoctRequest " + OpCodes.CalibrationWindowClose + " sent. Message: empty"); } /// @@ -788,13 +792,13 @@ private IActuatorSwitch find(String switchSource) /// private void OnTriggerTestRequestParameters(object request) { - Log.Debug("TriggerTest parameters requested"); + _logger.LogDebug("TriggerTest parameters requested"); // Send parameters to ACAT var bciTriggerTestParameters = new BCITriggerTestParameters(BCIActuatorSettings.Settings.TriggerTest_NumRepetitions, BCIActuatorSettings.Settings.TriggerTest_ScanTime); - Log.Debug(" Sending parameters. Scan time: " + bciTriggerTestParameters.ScanTime + " | Num repetitions: " + bciTriggerTestParameters.NumRepetitions); + _logger.LogDebug(" Sending parameters. Scan time: " + bciTriggerTestParameters.ScanTime + " | Num repetitions: " + bciTriggerTestParameters.NumRepetitions); SendIoctlResponse((int)OpCodes.TriggerTestSendParameters, bciTriggerTestParameters); - Log.Debug("IoctRequest " + OpCodes.TriggerTestSendParameters + " sent. Message: empty"); + _logger.LogDebug("IoctRequest " + OpCodes.TriggerTestSendParameters + " sent. Message: empty"); } /// @@ -803,7 +807,7 @@ private void OnTriggerTestRequestParameters(object request) /// private void OnRequestCalibrationStatus(object request) { - Log.Debug("Request Calibration Status received"); + _logger.LogDebug("Request Calibration Status received"); BCIError error; BCIClassifierStatus overallStatus = BCIClassifierStatus.NotFound; @@ -840,7 +844,7 @@ private void OnRequestCalibrationStatus(object request) // Add classifier to dictionary DictClassifierInfo.Add(calibrationSection, classifierInfo); - Log.Warn("Calibration:" + calibrationSection + " isRequired:" + classifierInfo.IsRequired + " Status:" + classifierInfo.ClassifierStatus.ToString() + " Auc:" + classifierInfo.Auc); + _logger.LogDebug("Calibration:" + calibrationSection + " isRequired:" + classifierInfo.IsRequired + " Status:" + classifierInfo.ClassifierStatus.ToString() + " Auc:" + classifierInfo.Auc); // Set overall status if (classifierInfo.IsRequired && classifierInfo.ClassifierStatus != BCIClassifierStatus.Ok) @@ -863,7 +867,7 @@ private void OnRequestCalibrationStatus(object request) showOnlyDefaults = false; } - Log.Debug("Additional classifier:" + calibrationSection + "Set showOnlyDefaults to:" + showOnlyDefaults); + _logger.LogDebug("Additional classifier:" + calibrationSection + "Set showOnlyDefaults to:" + showOnlyDefaults); } } error = new BCIError(BCIErrorCodes.Status_Ok, BCIMessages.Status_Ok); @@ -871,7 +875,7 @@ private void OnRequestCalibrationStatus(object request) catch (Exception e) { error = new BCIError(BCIErrorCodes.CalibrationError_LoadingClassifiers, StringResources.ClassifiersNotLoadedError); - Log.Exception("Error " + BCIErrorCodes.CalibrationError_LoadingClassifiers.ToString() + " " + "Excepction: " + e.Message); + _logger.LogError(e, "Error " + BCIErrorCodes.CalibrationError_LoadingClassifiers.ToString()); } // Set oKToGoToTyping status @@ -879,9 +883,9 @@ private void OnRequestCalibrationStatus(object request) // Send parameters to ACAT var bciCalibrationStatus = new BCICalibrationStatus(showOnlyDefaults, areMoreClassifiersThanMapping, okToGoToTyping, overallStatus, DictClassifierInfo, error); - Log.Debug("Sending Calibration Status. ShowOnlyDefaults:" + showOnlyDefaults + " | areMoreClassifiersThanMappings:" + areMoreClassifiersThanMapping + " | okToGoToTyping:" + okToGoToTyping + " | OverallStatus:" + overallStatus.ToString()); + _logger.LogDebug("Sending Calibration Status. ShowOnlyDefaults:" + showOnlyDefaults + " | areMoreClassifiersThanMappings:" + areMoreClassifiersThanMapping + " | okToGoToTyping:" + okToGoToTyping + " | OverallStatus:" + overallStatus.ToString()); SendIoctlResponse((int)OpCodes.SendCalibrationStatus, bciCalibrationStatus); - Log.Debug("IoctRequest: " + OpCodes.SendCalibrationStatus + " sent. Message: " + bciCalibrationStatus.ToString()); + _logger.LogDebug("IoctRequest: " + OpCodes.SendCalibrationStatus + " sent. Message: " + bciCalibrationStatus.ToString()); } /// @@ -890,7 +894,7 @@ private void OnRequestCalibrationStatus(object request) /// private void OnRequestMapOptions(object request) { - Log.Debug("Request Map options received"); + _logger.LogDebug("Request Map options received"); BCIError error; @@ -946,10 +950,10 @@ private void OnRequestMapOptions(object request) if (availableClassifiers.ContainsKey(availableClassifierForSection) && availableClassifiers[availableClassifierForSection].ClassifierStatus == BCIClassifierStatus.Ok) { availableClassifiersForSection.Add(availableClassifiers[availableClassifierForSection]); - Log.Debug("Section:" + typingSection + " Available classifier:" + availableClassifierForSection + " Auc:" + availableClassifiers[availableClassifierForSection].Auc); + _logger.LogDebug("Section:" + typingSection + " Available classifier:" + availableClassifierForSection + " Auc:" + availableClassifiers[availableClassifierForSection].Auc); } else - Log.Debug("Section:" + typingSection + " Classsifier:" + DictAllowedMappings[typingSection] + " is not available"); + _logger.LogDebug("Section:" + typingSection + " Classsifier:" + DictAllowedMappings[typingSection] + " is not available"); } // Add classifier found in dictionary DictClassifierInfoForAvailableMappings.Add(typingSection, availableClassifiersForSection); @@ -959,14 +963,14 @@ private void OnRequestMapOptions(object request) catch (Exception e) { error = new BCIError(BCIErrorCodes.CalibrationError_LoadingClassifiers, StringResources.ClassifiersNotLoadedError); - Log.Exception("Error " + BCIErrorCodes.CalibrationError_LoadingClassifiers.ToString() + " " + "Excepction: " + e.Message); + _logger.LogError(e, "Error " + BCIErrorCodes.CalibrationError_LoadingClassifiers.ToString()); } // Send response to ACAT var bciMapOptions = new BCIMapOptions(BCIActuatorSettings.Settings.Calibration_UseAdvanceModeForTypingMappings, DictClassifierInfoForAvailableMappings, DictTypingCalibrationMappings, error); - Log.Debug("Sending map options. Is advanced: " + bciMapOptions.IsAdvanced + " | error: " + (BCIErrorCodes)error.ErrorCode); + _logger.LogDebug("Sending map options. Is advanced: " + bciMapOptions.IsAdvanced + " | error: " + (BCIErrorCodes)error.ErrorCode); SendIoctlResponse((int)OpCodes.SendMapOptions, bciMapOptions); - Log.Debug("IoctRequest " + OpCodes.SendMapOptions + " sent. Message: " + bciMapOptions.ToString()); + _logger.LogDebug("IoctRequest " + OpCodes.SendMapOptions + " sent. Message: " + bciMapOptions.ToString()); } /// @@ -975,7 +979,7 @@ private void OnRequestMapOptions(object request) /// private void OnSendUpdatedMappings(object request) { - Log.Debug("Send Updated mappings called"); + _logger.LogDebug("Send Updated mappings called"); try { var bciUpdatedMappings = request as BCICalibrationUpdatedMappings; @@ -1008,21 +1012,21 @@ private void OnSendUpdatedMappings(object request) TypingCalibrationMappings.KeyboardRCalibrationMapping = mappingForTypingSection.Value.ToString(); break; } - Log.Debug("Typing section:" + mappingForTypingSection.Key.ToString() + " Classifier used:" + mappingForTypingSection.Value.ToString()); + _logger.LogDebug("Typing section:" + mappingForTypingSection.Key.ToString() + " Classifier used:" + mappingForTypingSection.Value.ToString()); } // Save settings TypingCalibrationMappings.Save(); - Log.Debug("Settings updated and saved"); + _logger.LogDebug("Settings updated and saved"); // Reload classifiers LoadClassifiers(); - Log.Debug("Classifiers re-loaded"); + _logger.LogDebug("Classifiers re-loaded"); } } catch (Exception e) { - Log.Exception(e.Message); + _logger.LogError(e, "Failed to send updated mappings"); } } @@ -1032,7 +1036,7 @@ private void OnSendUpdatedMappings(object request) /// private void OnTriggerTestSaveParameters(object request) { - Log.Debug("Received OnTriggerTestSaveParameters"); + _logger.LogDebug("Received OnTriggerTestSaveParameters"); // Receive parameters from ACAT var bciTriggerTestParameters = request as BCITriggerTestParameters; @@ -1042,7 +1046,7 @@ private void OnTriggerTestSaveParameters(object request) BCIActuatorSettings.Settings.TriggerTest_ScanTime = bciTriggerTestParameters.ScanTime; BCIActuatorSettings.Settings.Save(); - Log.Debug("Eyes closed parameters (Scan time: " + BCIActuatorSettings.Settings.TriggerTest_ScanTime + " , num repetitions: " + BCIActuatorSettings.Settings.TriggerTest_NumRepetitions + ") received from ACAT and saved to BCISettings file"); + _logger.LogDebug("Eyes closed parameters (Scan time: " + BCIActuatorSettings.Settings.TriggerTest_ScanTime + " , num repetitions: " + BCIActuatorSettings.Settings.TriggerTest_NumRepetitions + ") received from ACAT and saved to BCISettings file"); } /// @@ -1051,15 +1055,15 @@ private void OnTriggerTestSaveParameters(object request) /// private void OnTriggerTestStart(object request) { - Log.Debug("Trigger test start"); + _logger.LogDebug("Trigger test start"); if (_daqInstance.GetType() == typeof(DAQ_OpenBCI)) { _ = ((DAQ_OpenBCI)_daqInstance).TriggerTestStart(); } - Log.Debug("Trigger test started"); + _logger.LogDebug("Trigger test started"); SendIoctlResponse((int)OpCodes.TriggerTestStartReady, null); - Log.Debug("IoctRequest " + OpCodes.TriggerTestStartReady + " sent. Message:null "); + _logger.LogDebug("IoctRequest " + OpCodes.TriggerTestStartReady + " sent. Message:null "); } /// @@ -1068,7 +1072,7 @@ private void OnTriggerTestStart(object request) /// private void OnTriggerTestStop(object request) { - Log.Debug("Trigger test stop"); + _logger.LogDebug("Trigger test stop"); BaseDAQ.ExitCodes exitCode = ((DAQ_OpenBCI)_daqInstance).TriggerTestStop(BCIActuatorSettings.Settings.TriggerTest_NumRepetitions, out _, out List dutyCycleList, out double dutyCycleAvg); bool triggerTestSuccesful = false; @@ -1077,9 +1081,9 @@ private void OnTriggerTestStop(object request) // Send parameters to ACAT var bciTriggerTest = new BCITriggerTestResult(triggerTestSuccesful, dutyCycleList, dutyCycleAvg); - Log.Debug("Sending trigger test results. TriggerTestSuccesful: " + triggerTestSuccesful + " | dutyCycleAvg: " + dutyCycleAvg + " | dutyCycle for individual pulses: " + dutyCycleList.ToArray().ToString()); + _logger.LogDebug("Sending trigger test results. TriggerTestSuccesful: " + triggerTestSuccesful + " | dutyCycleAvg: " + dutyCycleAvg + " | dutyCycle for individual pulses: " + dutyCycleList.ToArray().ToString()); SendIoctlResponse((int)OpCodes.TriggerTestResult, bciTriggerTest); - Log.Debug("IoctRequest " + OpCodes.TriggerTestResult + " sent. Message: " + bciTriggerTest.ToString()); + _logger.LogDebug("IoctRequest " + OpCodes.TriggerTestResult + " sent. Message: " + bciTriggerTest.ToString()); } /// @@ -1088,12 +1092,12 @@ private void OnTriggerTestStop(object request) /// private void OnCalibrationEyesClosedRequestParameters(object request) { - Log.Debug("Requesting calibration for eyes close parameters"); + _logger.LogDebug("Requesting calibration for eyes close parameters"); // Send parameters to ACAT var bciCalibrationEyesClosedParameters = new BCICalibrationEyesClosedParameters(BCIActuatorSettings.Settings.EyesClosedCalibration_NumRepetitions, BCIActuatorSettings.Settings.EyesClosedCalibration_IntervalDuration); - Log.Debug("Sending eyes close parameters. Num repetitions: " + bciCalibrationEyesClosedParameters.NumRepetitions + " | Interval duration: " + bciCalibrationEyesClosedParameters.IntervalDuration); + _logger.LogDebug("Sending eyes close parameters. Num repetitions: " + bciCalibrationEyesClosedParameters.NumRepetitions + " | Interval duration: " + bciCalibrationEyesClosedParameters.IntervalDuration); SendIoctlResponse((int)OpCodes.CalibrationEyesClosedSendParameters, bciCalibrationEyesClosedParameters); - Log.Debug("IoctRequest " + OpCodes.CalibrationEyesClosedSendParameters + " sent. Message: " + bciCalibrationEyesClosedParameters.ToString()); + _logger.LogDebug("IoctRequest " + OpCodes.CalibrationEyesClosedSendParameters + " sent. Message: " + bciCalibrationEyesClosedParameters.ToString()); } /// @@ -1102,7 +1106,7 @@ private void OnCalibrationEyesClosedRequestParameters(object request) /// private void OnCalibrationEyesClosedSaveParameters(object request) { - Log.Debug("Calibration eyes closed save parameters called"); + _logger.LogDebug("Calibration eyes closed save parameters called"); // Receive parameters from ACAT var bciCalibrationEyesClosedParameters = request as BCICalibrationEyesClosedParameters; @@ -1112,7 +1116,7 @@ private void OnCalibrationEyesClosedSaveParameters(object request) BCIActuatorSettings.Settings.EyesClosedCalibration_NumRepetitions = bciCalibrationEyesClosedParameters.NumRepetitions; BCIActuatorSettings.Settings.Save(); - Log.Debug("Eyes closed parameters (Interval duration: " + BCIActuatorSettings.Settings.EyesClosedCalibration_IntervalDuration + " , num repetitions: " + BCIActuatorSettings.Settings.EyesClosedCalibration_NumRepetitions + ") received from ACAT and saved to BCISettings file"); + _logger.LogDebug("Eyes closed parameters (Interval duration: " + BCIActuatorSettings.Settings.EyesClosedCalibration_IntervalDuration + " , num repetitions: " + BCIActuatorSettings.Settings.EyesClosedCalibration_NumRepetitions + ") received from ACAT and saved to BCISettings file"); } /// @@ -1136,11 +1140,11 @@ private void OnCalibrationEyesClosedIterationEnd(object request) // var bciLogEntry = new BCILogEntryEyesClosed(BCIActuatorSettings.Settings.EyesClosed_EnableDetection, 0, eyesClosedDetected, alphaValues, betaValues, avgAlpha, avgBeta, bciEyesClosedIterationEnd.BciEyesClosedMode.ToString()); // var jsonString = JsonConvert.SerializeObject(bciLogEntry); // AuditLog.Audit(new AuditEvent("BCIEyesClosedCalibration", jsonString)); - // Log.Debug("Saved to audit file:" + jsonString); + // _logger.LogDebug("Saved to audit file:" + jsonString); // } // catch (Exception e) // { - // Log.Exception(e.Message); + // _logger.LogError(e, "Failed to process eyes closed calibration event"); // } //} } @@ -1152,7 +1156,7 @@ private void OnCalibrationEyesClosedIterationEnd(object request) private void OnCalibrationEyesClosedEnd(object request) { // TODO: We do not use Eyes closed detection - //Log.Debug("Calibration eyes closed ended"); + //_logger.LogDebug("Calibration eyes closed ended"); //if (useSensor) //{ @@ -1167,11 +1171,11 @@ private void OnCalibrationEyesClosedEnd(object request) // // End the esssion // DAQ_OpenBCI.EndSession(); - // Log.Debug("Session ended"); + // _logger.LogDebug("Session ended"); // } // catch (Exception e) // { - // Log.Exception(e.Message); + // _logger.LogError(e, "Failed to end eyes closed calibration session"); // } //} } @@ -1184,7 +1188,7 @@ private void OnCalibrationEyesClosedEnd(object request) /// private void OnCalibrationEnd(object request) { - Log.Debug("Calibartion End Received"); + _logger.LogDebug("Calibration End Received"); var bciCalibrationEnd = request as BCICalibrationEnd; @@ -1219,18 +1223,18 @@ private void OnCalibrationEnd(object request) if (auc * 100 >= DictCalibrationParameters[_currentCalibrationMode].MinimumScoreRequired) calibrationSuccessful = true; - Log.Debug("Session: " + sessionID + " Calibrated successfully: " + calibrationSuccessful + " - AUC: " + auc); + _logger.LogDebug("Session: " + sessionID + " Calibrated successfully: " + calibrationSuccessful + " - AUC: " + auc); if (auc == -1)// Error when training classifiers { - Log.Debug("Error when training classifiers"); + _logger.LogDebug("Error when training classifiers"); error = new BCIError(BCIErrorCodes.CalibrationError_OnAnalyzingData_TrainingClassifiersError, StringResources.CalibrationError_CalibrationFailed); } } catch (Exception e) { auc = -1; - Log.Exception(e.Message); + _logger.LogError(e, "Failed during calibration data analysis"); error = new BCIError(BCIErrorCodes.CalibrationError_OnAnalyzingData_UnknownException, StringResources.CalibrationError_CalibrationFailed); } } @@ -1240,7 +1244,7 @@ private void OnCalibrationEnd(object request) if (BCIActuatorSettings.Settings.Testing_ForceRecalibrateFromFile && BCIActuatorSettings.Settings.Testing_CalibrationFileId != null) { auc = RecalibrateFromFile(); - Log.Debug("Recalibrated from file. AUC: " + auc); + _logger.LogDebug("Recalibrated from file. AUC: " + auc); } calibrationSuccessful = true; } @@ -1249,9 +1253,9 @@ private void OnCalibrationEnd(object request) // Send auc to ACAT var bciCalibrationResult = new BCICalibrationResult(auc, calibrationSuccessful, error); - Log.Debug("Sending response. Calibration result: " + calibrationSuccessful + " | AUC: " + auc); + _logger.LogDebug("Sending response. Calibration result: " + calibrationSuccessful + " | AUC: " + auc); SendIoctlResponse((int)OpCodes.CalibrationResult, bciCalibrationResult); - Log.Debug("IoctRequest " + OpCodes.CalibrationResult + " sent. Message: " + bciCalibrationResult.ToString()); + _logger.LogDebug("IoctRequest " + OpCodes.CalibrationResult + " sent. Message: " + bciCalibrationResult.ToString()); } /// @@ -1261,7 +1265,7 @@ private void OnCalibrationEnd(object request) /// private void OnCalibrationEndRepetition(object request) { - Log.Debug("Calibration end repetition received"); + _logger.LogDebug("Calibration end repetition received"); BCIError sensorError = new(BCIErrorCodes.Status_Ok, BCIMessages.Status_Ok); SignalStatus statusSignal = SignalStatus.SIGNAL_KO; @@ -1302,7 +1306,7 @@ private void OnCalibrationEndRepetition(object request) numTriggerPulsesExpected = bciCalibrationInput.RowColumnIDs.Count; if (numTriggerPulsesDetected == 0) { - Log.Debug("Optical sensor error. No pulses were detected"); + _logger.LogDebug("Optical sensor error. No pulses were detected"); sensorError = new BCIError(BCIErrorCodes.OpticalSensorError_NoPulsesDetected, StringResources.OpticalSensorError); } // Note: Removed code since we can't guarantee the number of pulses received given bluetooth delays @@ -1327,7 +1331,7 @@ private void OnCalibrationEndRepetition(object request) }; var jsonString = bciLogEntry; AuditLog.Audit(new AuditEvent("BCIEyesClosed", jsonString)); - Log.Debug("Line added to audit file: " + jsonString); + _logger.LogDebug("Line added to audit file: " + jsonString); } else { @@ -1339,7 +1343,7 @@ private void OnCalibrationEndRepetition(object request) catch (Exception e) { sensorError = new BCIError(BCIErrorCodes.CalibrationError_UnknwonException, StringResources.CalibrationError_CalibrationFailed); - Log.Exception(e.Message); + _logger.LogError(e, "Failed to process calibration input"); } } } @@ -1347,14 +1351,14 @@ private void OnCalibrationEndRepetition(object request) if (sensorError.ErrorCode != BCIErrorCodes.Status_Ok) { String txt = "Error on calibration repetition end (Error: " + sensorError.ErrorCode + " Message: " + sensorError.ErrorMessage + ") Expected pulses: " + numTriggerPulsesExpected + " - Detected pulses: " + numTriggerPulsesDetected; - Log.Debug(txt); + _logger.LogDebug(txt); } // Send result var bciCalibrationResult = new BCISensorStatus() { Error = sensorError, StatusSignal = statusSignal }; - Log.Debug("Sending response. SensorError:" + (BCIErrorCodes)bciCalibrationResult.Error.ErrorCode); + _logger.LogDebug("Sending response. SensorError:" + (BCIErrorCodes)bciCalibrationResult.Error.ErrorCode); SendIoctlResponse((int)OpCodes.CalibrationEndRepetitionResult, bciCalibrationResult); - Log.Debug("IoctRequest " + OpCodes.CalibrationEndRepetitionResult + " sent. Message: " + bciCalibrationResult.ToString()); + _logger.LogDebug("IoctRequest " + OpCodes.CalibrationEndRepetitionResult + " sent. Message: " + bciCalibrationResult.ToString()); } /// @@ -1374,7 +1378,7 @@ private void OnHighlightOnOff(object request) /// private void OnLanguageModelProbabilities(object request) { - Log.Debug("Language model probabilities received"); + _logger.LogDebug("Language model probabilities received"); var bciLanguageModelProbabilities = request as BCILanguageModelProbabilities; bool enableLanguageModelprobabilities = false; @@ -1383,7 +1387,7 @@ private void OnLanguageModelProbabilities(object request) epochIdx++; // Restart classifiers (nextcharacterprobs = clear talk window, resume after pause, etc) - Log.Debug("Restarting all probabilities"); + _logger.LogDebug("Restarting all probabilities"); EEGProcessingGlobals.RestartAllDecisionMakerProbabilities(); // Add next character probabilities (flag will be turn on/off if they shouldn't be @@ -1414,11 +1418,11 @@ private void OnLanguageModelProbabilities(object request) { EEGProcessingGlobals.DecisionMakerDict[currentSection].AddNextCharacterProbabilities(bciLanguageModelProbabilities.LanguageModelProbabilities); EEGProcessingGlobals.DecisionMakerDict[currentSection].enableLanguageModelProbabilities = enableLanguageModelprobabilities; - Log.Debug("Probabilities for " + currentSection + " added to. Use LM for section: " + enableLanguageModelprobabilities); + _logger.LogDebug("Probabilities for " + currentSection + " added to. Use LM for section: " + enableLanguageModelprobabilities); } else { - Log.Debug("Probabilities not added"); + _logger.LogDebug("Probabilities not added"); } } @@ -1431,7 +1435,7 @@ private void OnLanguageModelProbabilities(object request) }; var jsonString = bciLogEntry; AuditLog.Audit(new AuditEvent("BCILanguageModelProbabilitiesReceived", jsonString)); - Log.Debug("Line added to audit file: " + jsonString); + _logger.LogDebug("Line added to audit file: " + jsonString); } /// @@ -1472,7 +1476,7 @@ private void OnRequestParameters(object request) BCIError error = new(BCIErrorCodes.Status_Ok, BCIMessages.Status_Ok); var bciUserInputParameters = request as BCIUserInputParameters; - Log.Debug("Request parameters for mode " + bciUserInputParameters.BciMode); + _logger.LogDebug("Request parameters for mode " + bciUserInputParameters.BciMode); switch (bciUserInputParameters.BciMode) { @@ -1483,7 +1487,7 @@ private void OnRequestParameters(object request) break; case BCIModes.CALIBRATION: - Log.Debug("Calibration mode: " + bciUserInputParameters.BciCalibrationMode + " Scan time: " + bciUserInputParameters.ScanTime + " | Number of targets: " + bciUserInputParameters.NumTargets + " | Number of iterations per target: " + bciUserInputParameters.NumIterationsPerTarget + " | Minimum score required: " + bciUserInputParameters.MinScoreRequired); + _logger.LogDebug("Calibration mode: " + bciUserInputParameters.BciCalibrationMode + " Scan time: " + bciUserInputParameters.ScanTime + " | Number of targets: " + bciUserInputParameters.NumTargets + " | Number of iterations per target: " + bciUserInputParameters.NumIterationsPerTarget + " | Minimum score required: " + bciUserInputParameters.MinScoreRequired); // Update settings for the corresponding section from parameters sent from ACAT switch (bciUserInputParameters.BciCalibrationMode) @@ -1494,7 +1498,7 @@ private void OnRequestParameters(object request) BoxCalibrationSettings.NumberOfIterationsPerTarget = bciUserInputParameters.NumIterationsPerTarget; BoxCalibrationSettings.MinimumScoreRequired = bciUserInputParameters.MinScoreRequired; BoxCalibrationSettings.Save(); - Log.Debug("Parameters saved for box calibration"); + _logger.LogDebug("Parameters saved for box calibration"); break; case BCIScanSections.Word: @@ -1503,7 +1507,7 @@ private void OnRequestParameters(object request) WordCalibrationSettings.NumberOfIterationsPerTarget = bciUserInputParameters.NumIterationsPerTarget; WordCalibrationSettings.MinimumScoreRequired = bciUserInputParameters.MinScoreRequired; WordCalibrationSettings.Save(); - Log.Debug("Parameters saved for calibration"); + _logger.LogDebug("Parameters saved for calibration"); break; case BCIScanSections.Sentence: @@ -1512,7 +1516,7 @@ private void OnRequestParameters(object request) SentenceCalibrationSettings.NumberOfIterationsPerTarget = bciUserInputParameters.NumIterationsPerTarget; SentenceCalibrationSettings.MinimumScoreRequired = bciUserInputParameters.MinScoreRequired; SentenceCalibrationSettings.Save(); - Log.Debug("Parameters saved for sentence calibration"); + _logger.LogDebug("Parameters saved for sentence calibration"); break; case BCIScanSections.KeyboardL: @@ -1521,7 +1525,7 @@ private void OnRequestParameters(object request) KeyboardLeftCalibrationSettings.NumberOfIterationsPerTarget = bciUserInputParameters.NumIterationsPerTarget; KeyboardLeftCalibrationSettings.MinimumScoreRequired = bciUserInputParameters.MinScoreRequired; KeyboardLeftCalibrationSettings.Save(); - Log.Debug("Parameters saved for keyboard Left calibration"); + _logger.LogDebug("Parameters saved for keyboard Left calibration"); break; case BCIScanSections.KeyboardR: @@ -1530,7 +1534,7 @@ private void OnRequestParameters(object request) KeyboardRightCalibrationSettings.NumberOfIterationsPerTarget = bciUserInputParameters.NumIterationsPerTarget; KeyboardRightCalibrationSettings.MinimumScoreRequired = bciUserInputParameters.MinScoreRequired; KeyboardRightCalibrationSettings.Save(); - Log.Debug("Paramters saved for keyboard right calibration"); + _logger.LogDebug("Parameters saved for keyboard right calibration"); break; } @@ -1539,15 +1543,15 @@ private void OnRequestParameters(object request) DictCalibrationParameters[bciUserInputParameters.BciCalibrationMode].TargetCount = bciUserInputParameters.NumTargets; DictCalibrationParameters[bciUserInputParameters.BciCalibrationMode].IterationsPerTarget = bciUserInputParameters.NumIterationsPerTarget; DictCalibrationParameters[bciUserInputParameters.BciCalibrationMode].MinimumScoreRequired = bciUserInputParameters.MinScoreRequired; - Log.Debug("Parameters updated in the " + bciUserInputParameters.BciCalibrationMode + " dictionary"); + _logger.LogDebug("Parameters updated in the " + bciUserInputParameters.BciCalibrationMode + " dictionary"); break; } // Send parameters to ACAT var bciParameters = new BCIParameters(DictCalibrationParameters, recalibrationRequired, lastCalibrationAUC, BCIActuatorSettings.Settings.Scanning_PauseTime, BCIActuatorSettings.Settings.Scanning_ShortPauseTime, BCIActuatorSettings.Settings.Scanning_ShowDecisionTime, BCIActuatorSettings.Settings.Scanning_DelayAfterDecision, BCIActuatorSettings.Settings.Scanning_DelayToGetReady, BCIActuatorSettings.Settings.Testing_MinimumProbabiltyToDisplayBarOnTyping, BCIActuatorSettings.Settings.Scanning_FocalCircleColor, BCIActuatorSettings.Settings.Scanning_IsFocalCircleFilled, error); - Log.Debug("Sending parameters. Error:" + (BCIErrorCodes)bciParameters.Error.ErrorCode + " RecalibrationRequired:" + bciParameters.CalibrationRequiredFlag + " | Pause time:" + bciParameters.Scanning_PauseTime + ", Short pause time:" + bciParameters.Scanning_ShortPauseTime + ", Show decision time: " + bciParameters.Scanning_ShowDecisionTime + ", Delay after decision:" + bciParameters.Scanning_DelayAfterDecision + ", Minimum probability to display bars on typing:" + bciParameters.MinProbablityToDisplayBarOnTyping); + _logger.LogDebug("Sending parameters. Error:" + (BCIErrorCodes)bciParameters.Error.ErrorCode + " RecalibrationRequired:" + bciParameters.CalibrationRequiredFlag + " | Pause time:" + bciParameters.Scanning_PauseTime + ", Short pause time:" + bciParameters.Scanning_ShortPauseTime + ", Show decision time: " + bciParameters.Scanning_ShowDecisionTime + ", Delay after decision:" + bciParameters.Scanning_DelayAfterDecision + ", Minimum probability to display bars on typing:" + bciParameters.MinProbablityToDisplayBarOnTyping); SendIoctlResponse((int)OpCodes.SendParameters, bciParameters); - Log.Debug("IoctRequest " + OpCodes.SendParameters); + _logger.LogDebug("IoctRequest " + OpCodes.SendParameters); } /// @@ -1567,7 +1571,7 @@ private void OnSessionStart(object request) if (bciModeObj != null) { - Log.Debug("Start session: " + bciModeObj.BciMode); + _logger.LogDebug("Start session: " + bciModeObj.BciMode); if (useSensor) { @@ -1597,9 +1601,9 @@ private void OnSessionStart(object request) // For Debugging / Testing: calibrate from old file when selected from settings if (BCIActuatorSettings.Settings.Testing_ForceRecalibrateFromFile && BCIActuatorSettings.Settings.Testing_CalibrationFileId != null) { - Log.Debug("Recalibrating from file"); + _logger.LogDebug("Recalibrating from file"); float auc = RecalibrateFromFile(); - Log.Debug("Recalibrated from file. AUC: " + auc); + _logger.LogDebug("Recalibrated from file. AUC: " + auc); } if (!LoadClassifiers()) @@ -1617,7 +1621,7 @@ private void OnSessionStart(object request) } // Start session - Log.Debug("Starting session: " + sessionID); + _logger.LogDebug("Starting session: " + sessionID); sensorReady = _daqInstance.StartSession(sessionID, true); sessionDirectory = _daqInstance.GetSessionDirectory(); _isSessionInProgress = false; // set to true on calibrationEndRepetition and TypingEndRepetition @@ -1628,11 +1632,11 @@ private void OnSessionStart(object request) { filePathCopyTo = Path.Combine(sessionDirectory, fileName); filePathCopyFrom = UserManager.GetFullPath(fileName); - Log.Debug("Copying files from: " + filePathCopyFrom + " to " + filePathCopyTo); + _logger.LogDebug("Copying files from: " + filePathCopyFrom + " to " + filePathCopyTo); if (!String.IsNullOrEmpty(filePathCopyTo) && !String.IsNullOrEmpty(filePathCopyFrom) && File.Exists(filePathCopyFrom) && Directory.Exists(sessionDirectory)) { File.Copy(filePathCopyFrom, filePathCopyTo); - Log.Debug("FIles copied from: " + filePathCopyFrom + " to " + filePathCopyTo); + _logger.LogDebug("Files copied from: " + filePathCopyFrom + " to " + filePathCopyTo); } } } @@ -1655,13 +1659,13 @@ private void OnSessionStart(object request) SessionId = sessionID, Error = error }; - Log.Debug("Sending response. Error: " + (BCIErrorCodes)error.ErrorCode + " Sensor ready: " + bciStartSessionResults.SensorReady + " | session ID: " + sessionID + " | directory: " + sessionDirectory); + _logger.LogDebug("Sending response. Error: " + (BCIErrorCodes)error.ErrorCode + " Sensor ready: " + bciStartSessionResults.SensorReady + " | session ID: " + sessionID + " | directory: " + sessionDirectory); SendIoctlResponse((int)OpCodes.StartSessionResult, bciStartSessionResults); - Log.Debug("IoctRequest " + OpCodes.StartSessionResult + " sent. Message: " + bciStartSessionResults.ToString()); + _logger.LogDebug("IoctRequest " + OpCodes.StartSessionResult + " sent. Message: " + bciStartSessionResults.ToString()); } catch (Exception e) { - Log.Exception(e.Message); + _logger.LogError(e, "Failed to start session"); } } @@ -1683,7 +1687,7 @@ private float RecalibrateFromFile() if (idxCalibrationType != -1) { string calibrationType = sessionID.Substring(idxCalibrationType + strToFind.Length); - Log.Debug("Recalibrating from file " + sessionID + " | Test ID: " + BCIActuatorSettings.Settings.Testing_TestID + " | Calibration type:" + calibrationType); + _logger.LogDebug("Recalibrating from file " + sessionID + " | Test ID: " + BCIActuatorSettings.Settings.Testing_TestID + " | Calibration type:" + calibrationType); FeatureExtractionObj = calibrationType.ToLower() switch { @@ -1708,14 +1712,14 @@ private float RecalibrateFromFile() }; } - Log.Debug(" Recalibrating file " + sessionID); + _logger.LogDebug(" Recalibrating file " + sessionID); // Train classifiers auc = FeatureExtractionObj.Learn(sessionID); // will return -1 if error when training classifiers - Log.Debug("Recalibrated with AUC: " + auc); + _logger.LogDebug("Recalibrated with AUC: " + auc); } catch (Exception e) { - Log.Exception(e.Message); + _logger.LogError(e, "Failed to recalibrate from file"); } return auc; } @@ -1741,7 +1745,7 @@ private void OnToggleCalibrationWindow() /*if (!IsSignalFormVisible()) {*/ SendIoctlResponse((int)OpCodes.CalibrationWindowPreShow, String.Empty); - Log.Debug("IoctRequest " + OpCodes.CalibrationWindowPreShow + " sent. Message: empty"); + _logger.LogDebug("IoctRequest " + OpCodes.CalibrationWindowPreShow + " sent. Message: empty"); //} } @@ -1772,7 +1776,7 @@ private void OnTypingRepetitionEnd(object request) var bciTypingRepetitionEnd = request as BCITypingRepetitionEnd; BCIScanSections currentScanSection = bciTypingRepetitionEnd.ScanningSection; - Log.Debug("On typing Repetition end called for section: " + bciTypingRepetitionEnd.ScanningSection); + _logger.LogDebug("On typing Repetition end called for section: " + bciTypingRepetitionEnd.ScanningSection); if (useSensor) { @@ -1850,7 +1854,7 @@ private void OnTypingRepetitionEnd(object request) if (BCIActuatorSettings.Settings.EyesClosed_EnableDetection) { - Log.Debug("Eyes closed detected"); + _logger.LogDebug("Eyes closed detected"); returnToBoxScanningFlag = eyesClosedDetected; if (eyesClosedDetected) { @@ -1866,7 +1870,7 @@ private void OnTypingRepetitionEnd(object request) // Reduce and compute posterior probabilities decidedButtonID = 0; decidedFlag = false; - Log.Debug("Calculating posterior probabilities"); + _logger.LogDebug("Calculating posterior probabilities"); EEGProcessingGlobals.DecisionMakerDict[currentScanSection].ComputePosteriorProbs(allSamples, bciTypingRepetitionEnd.RowColumnIDs, bciTypingRepetitionEnd.FlashingSequence, @@ -1895,15 +1899,15 @@ private void OnTypingRepetitionEnd(object request) if (posteriorProbs == null || posteriorProbs.Count == 0) { //error = new BCIError(BCIErrorCodes.TypingError_OnRepetitionEnd_NoProbabilitiesCalculated, BCIMessages.TypingError); // no probabilities returned. optical sensor dead? - Log.Debug("Probabilities not returned from DeicisionMaker"); + _logger.LogDebug("Probabilities not returned from DeicisionMaker"); } else if (posteriorProbs.Count != buttonIds.Count) { // error = new BCIError(BCIErrorCodes.TypingError_OnRepetitionEnd_ProabilitiesMarkersMissmatch, BCIMessages.TypingError); - Log.Debug("Number of probabilities different than number of highlights. Num buttons: " + buttonIds.Count + " Num Probabilities: " + posteriorProbs.Count); + _logger.LogDebug("Number of probabilities different than number of highlights. Num buttons: " + buttonIds.Count + " Num Probabilities: " + posteriorProbs.Count); } - Log.Debug("Posterior probabilities calculated. Repetition: " + repetition + " Decided:" + decidedFlag + " DecisionLabel:" + decidedButtonLabel + " DecisionID: " + decidedButtonID + " Probabilities" + eegProbs.ToString()); + _logger.LogDebug("Posterior probabilities calculated. Repetition: " + repetition + " Decided:" + decidedFlag + " DecisionLabel:" + decidedButtonLabel + " DecisionID: " + decidedButtonID + " Probabilities" + eegProbs.ToString()); } } else @@ -1919,12 +1923,12 @@ private void OnTypingRepetitionEnd(object request) catch (Exception e) { error = new BCIError(BCIErrorCodes.TypingError_OnRepetitionEnd_UnknownException, StringResources.TypingError);// Error when processing data - Log.Exception("Error: " + error.ErrorCode + " Message" + error.ErrorMessage + " Excepcion: " + e.Message); + _logger.LogError(e, "Error: " + error.ErrorCode + " Message" + error.ErrorMessage); } // Display error on logs if (error.ErrorCode != BCIErrorCodes.Status_Ok) - Log.Exception("Error: " + error.ErrorCode + " Message" + error.ErrorMessage); + _logger.LogError("Error: {ErrorCode} Message: {ErrorMessage}", error.ErrorCode, error.ErrorMessage); } else { @@ -2017,7 +2021,7 @@ private void OnTypingRepetitionEnd(object request) }; var jsonString = bciLogEntry; AuditLog.Audit(new AuditEvent("BCIRepetitionEnd", jsonString)); - Log.Debug("Results: " + jsonString); + _logger.LogDebug("Results: " + jsonString); // Send results to application var bciTypingRepetitionResult = new BCITypingRepetitionResult @@ -2032,9 +2036,9 @@ private void OnTypingRepetitionEnd(object request) if (posteriorProbs != null) bciTypingRepetitionResult.PosteriorProbs = posteriorProbs; - Log.Debug("Sending response. Error: " + (BCIErrorCodes)error.ErrorCode + " | Decided:" + decidedFlag + "DecidedID:" + decidedButtonID + " ReturnToBoxScanning:" + returnToBoxScanningFlag + " StatusSignal: " + statusSignal); + _logger.LogDebug("Sending response. Error: " + (BCIErrorCodes)error.ErrorCode + " | Decided:" + decidedFlag + "DecidedID:" + decidedButtonID + " ReturnToBoxScanning:" + returnToBoxScanningFlag + " StatusSignal: " + statusSignal); SendIoctlResponse((int)OpCodes.TypingEndRepetitionResult, bciTypingRepetitionResult); - Log.Debug("IoctRequest " + OpCodes.TypingEndRepetitionResult + " sent. Message: " + bciTypingRepetitionResult.ToString()); + _logger.LogDebug("IoctRequest " + OpCodes.TypingEndRepetitionResult + " sent. Message: " + bciTypingRepetitionResult.ToString()); } /// @@ -2103,7 +2107,7 @@ private void TestBCIDevices() private void TestGtecDevice() { - _gtecDeviceTester = new GTecDeviceTester(); + _gtecDeviceTester = new GTecDeviceTester(null); _gtecDeviceTester.EvtBCIDeviceTestingCompleted += bciDeviceTestingCompleted; _gtecDeviceTester.initialize(); } @@ -2124,7 +2128,7 @@ private void unInit() } /// - /// Show disclamer + /// Show disclaimer /// private void showDisclaimer() { diff --git a/src/Extensions/BCI/Actuators/BCIActuator/BCIActuatorSwitch.cs b/src/Extensions/BCI/Actuators/BCIActuator/BCIActuatorSwitch.cs index 9b8c0488..8a3b0e6b 100644 --- a/src/Extensions/BCI/Actuators/BCIActuator/BCIActuatorSwitch.cs +++ b/src/Extensions/BCI/Actuators/BCIActuator/BCIActuatorSwitch.cs @@ -64,8 +64,6 @@ protected override void Dispose(bool disposing) { try { - Log.Verbose(); - if (disposing) { // release managed resources diff --git a/src/Extensions/BCI/Actuators/EEGDataAcquisition/BaseDAQ.cs b/src/Extensions/BCI/Actuators/EEGDataAcquisition/BaseDAQ.cs index 53f7fba3..86bf3dfb 100644 --- a/src/Extensions/BCI/Actuators/EEGDataAcquisition/BaseDAQ.cs +++ b/src/Extensions/BCI/Actuators/EEGDataAcquisition/BaseDAQ.cs @@ -19,6 +19,7 @@ using System; using System.Collections.Generic; using System.Linq; +using Microsoft.Extensions.Logging; namespace ACAT.Extensions.BCI.Actuators.EEG.EEGDataAcquisition { @@ -27,6 +28,8 @@ namespace ACAT.Extensions.BCI.Actuators.EEG.EEGDataAcquisition /// public abstract class BaseDAQ { + protected static ILogger _logger; + /// /// Settings file name /// @@ -313,7 +316,7 @@ public virtual bool StartSession(string sessionID, bool forceSavingData) if (saveDataToFile) { - Log.Debug("Creating files for session: " + sessionID); + _logger?.LogDebug("Creating files for session: {SessionID}", sessionID); // Creates new file if (sessionID == "") @@ -329,7 +332,7 @@ public virtual bool StartSession(string sessionID, bool forceSavingData) } catch (Exception e) { - Log.Exception("Exception " + e.Message); + _logger?.LogError(e, "Exception starting session"); } return result; } @@ -352,12 +355,12 @@ public virtual bool EndSession() { GetData(); // Empty buffer } - Log.Debug("Session closed"); + _logger?.LogDebug("Session closed"); result = true; } catch (Exception e) { - Log.Exception("Exception " + e.Message); + _logger?.LogError(e, "Exception ending session"); } return result; @@ -398,7 +401,7 @@ protected virtual bool AppendDataToBuffer(double[,] data, double[,] inBuffer, in } catch (Exception e) { - Log.Exception(e.Message); + _logger?.LogError(e, "Exception appending data to buffer"); } return result; } @@ -413,7 +416,7 @@ protected virtual void CreateFiles(string sessionID) { if (FileWriterObj == null) { - Log.Debug("Creating files for session: " + sessionID); + _logger?.LogDebug("Creating files for session: {SessionID}", sessionID); if (sessionID == "") FileWriterObj = new FileWriter(); @@ -433,12 +436,12 @@ public virtual void Config_Board(string cmd) { try { - Log.Debug("Config board. Command: " + cmd); + _logger?.LogDebug("Config board. Command: {Command}", cmd); DeviceObj.config_board(cmd); } catch (Exception ex) { - Log.Exception(ex); + _logger?.LogError(ex, "Exception configuring board"); } } } diff --git a/src/Extensions/BCI/Actuators/EEGDataAcquisition/DAQ_OpenBCI.cs b/src/Extensions/BCI/Actuators/EEGDataAcquisition/DAQ_OpenBCI.cs index 2726d2b3..b2636837 100644 --- a/src/Extensions/BCI/Actuators/EEGDataAcquisition/DAQ_OpenBCI.cs +++ b/src/Extensions/BCI/Actuators/EEGDataAcquisition/DAQ_OpenBCI.cs @@ -17,9 +17,11 @@ using ACAT.Extensions.BCI.Common.BCIControl; using Accord.Math; using brainflow; +using Microsoft.Extensions.Logging; using Microsoft.Win32; using System; using System.Collections.Generic; +using System.Configuration; using System.IO.Ports; using System.Linq; using System.Threading; @@ -28,6 +30,8 @@ namespace ACAT.Extensions.BCI.Actuators.EEG.EEGDataAcquisition { public class DAQ_OpenBCI : BaseDAQ { + private new readonly ILogger _logger; + // ********** Params set here (not read from settings) // private readonly string[] otherChannelsPinsNameList = { "x", "D11", "D12", "D13", "D17", "D18", "x" }; // private readonly int[] otherChannelsPinsIdxList = {12, 13, 14, 15, 16, 17, 18}; this is returnet when DeviceObj.get_other_channels(); @@ -56,17 +60,17 @@ public class DAQ_OpenBCI : BaseDAQ /// /// Status of the board /// - private BoardStatus status; + private new BoardStatus status; /// /// Boolean, true if device initialized /// - public bool deviceInitialized = false; + public new bool deviceInitialized = false; /// /// Buffer to store data and calculate signal stauts /// - private double[,] _bufferSignalStatus; + private new double[,] _bufferSignalStatus; /// /// Buffer to store data for eyes closed detection @@ -77,16 +81,16 @@ public class DAQ_OpenBCI : BaseDAQ /// Index of the EEG channels in data returned from sensor /// This is directly via from brainflow /// - public int[] indEegChannels; + public new int[] indEegChannels; - public enum DeviceStatus + public new enum DeviceStatus { DEVICE_STANDBY, DEVICE_ERROR, DEVICE_ACQUIRINGDATA, }; - public DeviceStatus deviceStatus; + public new DeviceStatus deviceStatus; // BoardStatus enum is now inherited from BaseDAQ @@ -105,13 +109,21 @@ public enum DaisyBoardStatus // ExitCodes enum is now inherited from BaseDAQ + /// + /// Initializes an instance of the class + /// + public DAQ_OpenBCI() + { + _logger = LoggingConfiguration.CreateLogger(); + } + /// /// Loads settings from the configuration file /// public override void LoadSettings() { SignalControl_WindowDurationForVrmsMeaseurment = BCIActuatorSettings.Settings.SignalControl_WindowDurationForVrmsMeaseurment; - Log.Debug("DAQ settings loaded. Window duration for uVrmsMeasurement: " + SignalControl_WindowDurationForVrmsMeaseurment); + _logger.LogDebug("DAQ settings loaded. Window duration for uVrmsMeasurement: " + SignalControl_WindowDurationForVrmsMeaseurment); switch (BCIActuatorSettings.Settings.DAQ_NumEEGChannels) { @@ -135,19 +147,19 @@ public override void LoadSettings() BCISettingsFixed.DataParser_IdxTriggerSignal_Hw = 16; BCISettingsFixed.DataParser_IdxTriggerSignal_Sw = 24; BCISettingsFixed.DimReduct_DownsampleRate = 2; - Log.Debug("Num Channels settings is incorrect. Sensor set to default: 8 channels"); + _logger.LogDebug("Num Channels settings is incorrect. Sensor set to default: 8 channels"); break; } BCIActuatorSettings.Save(); - Log.Debug("Sensor set to " + BCIActuatorSettings.Settings.DAQ_NumEEGChannels + " channels. SensorID: " + BCISettingsFixed.DAQ_SensorId + " , Downsample rate: " + BCISettingsFixed.DimReduct_DownsampleRate + + _logger.LogDebug("Sensor set to " + BCIActuatorSettings.Settings.DAQ_NumEEGChannels + " channels. SensorID: " + BCISettingsFixed.DAQ_SensorId + " , Downsample rate: " + BCISettingsFixed.DimReduct_DownsampleRate + " , Idx hw trigger signal: " + BCISettingsFixed.DataParser_IdxTriggerSignal_Hw + " , Idx sw trigger signal: " + BCISettingsFixed.DataParser_IdxTriggerSignal_Sw); boardID = BCISettingsFixed.DAQ_SensorId; saveDataToFile = BCIActuatorSettings.Settings.DAQ_SaveToFileFlag; frontendFilterIdx = BCIActuatorSettings.Settings.DAQ_FrontendFilterIdx; notchFilterIdx = BCIActuatorSettings.Settings.DAQ_NotchFilterIdx; - Log.Debug(" Frontend filter: " + frontendFilterIdx + " Notch filter: " + notchFilterIdx); + _logger.LogDebug(" Frontend filter: " + frontendFilterIdx + " Notch filter: " + notchFilterIdx); eyesClosedDetectionUseFixThreshold = BCIActuatorSettings.Settings.EyesClosed_UseFixThreshold; if (eyesClosedDetectionUseFixThreshold) @@ -155,7 +167,7 @@ public override void LoadSettings() else eyesClosedDetectionThreshold = BCIActuatorSettings.Settings.EyesClosed_AdaptiveThreshold; eyesClosed_WindowDuration = BCIActuatorSettings.Settings.EyesClosed_WindowDuration; - Log.Debug("Eyes closed detection. Use Fix Threshold" + eyesClosedDetectionUseFixThreshold + " Threshold: " + eyesClosedDetectionThreshold + " Window duration: " + eyesClosed_WindowDuration); + _logger.LogDebug("Eyes closed detection. Use Fix Threshold" + eyesClosedDetectionUseFixThreshold + " Threshold: " + eyesClosedDetectionThreshold + " Window duration: " + eyesClosed_WindowDuration); } #region Get/set @@ -221,13 +233,13 @@ public String DetectPort() foreach (String port in SerialPort.GetPortNames()) { - Log.Debug("Checking port " + port); + _logger.LogDebug("Checking port " + port); serialPort = port; AddWarning(ExitCodes.IDLE, " Time: " + DateTime.Now.ToString("h:mm:ss tt") + " TESTING PORT MESSAGE: Serial port " + serialPort); if (TestPort(port, out _)) { - Log.Debug("Detected cytonboard port " + port); + _logger.LogDebug("Detected cytonboard port " + port); return serialPort; } } @@ -298,13 +310,13 @@ public override bool InitDevice(string deviceIdentifier) { if (status == BoardStatus.BOARD_OPEN) { - Log.Debug("Board was open, closing device"); + _logger.LogDebug("Board was open, closing device"); CloseDevice(); } if (status == BoardStatus.BOARD_ACQUIRINGDATA) { - Log.Debug("Board already acquiring data, returning"); + _logger.LogDebug("Board already acquiring data, returning"); return true; } else @@ -314,13 +326,13 @@ public override bool InitDevice(string deviceIdentifier) // Enable /disable boardlogging if (boardLoggerEnabled) { - Log.Debug("BoardLoggerEnabled: " + boardLoggerEnabled + " Enabling brainflow logging"); + _logger.LogDebug("BoardLoggerEnabled: " + boardLoggerEnabled + " Enabling brainflow logging"); BoardShim.enable_dev_board_logger(); BoardShim.set_log_file(boardLogFileName); } else { - Log.Debug("BoardLoggerEnabled: " + boardLoggerEnabled + " Disabling brainflow logging"); + _logger.LogDebug("BoardLoggerEnabled: " + boardLoggerEnabled + " Disabling brainflow logging"); BoardShim.disable_board_logger(); } @@ -331,22 +343,22 @@ public override bool InitDevice(string deviceIdentifier) } // Test port - Log.Debug("Testing port: " + port); + _logger.LogDebug("Testing port: " + port); bool sensorConnected = TestPort(port, out _); if (!sensorConnected) { - Log.Debug("Sensor not connected to port " + port + ". Starting port detection"); + _logger.LogDebug("Sensor not connected to port " + port + ". Starting port detection"); port = DetectPort(); - Log.Debug("Port " + port + " detected. Testing port"); + _logger.LogDebug("Port " + port + " detected. Testing port"); sensorConnected = TestPort(port, out _); - Log.Debug("Port " + port + " tested. Result: " + sensorConnected); + _logger.LogDebug("Port " + port + " tested. Result: " + sensorConnected); } BrainFlowInputParams input_params = new(); if (sensorConnected) { - Log.Debug("Sensor connected to port " + port); + _logger.LogDebug("Sensor connected to port " + port); // Save port serialPort = port; @@ -354,7 +366,7 @@ public override bool InitDevice(string deviceIdentifier) // Save port to settings BCIActuatorSettings.Settings.DAQ_ComPort = serialPort; BCIActuatorSettings.Save(); - Log.Debug("Port: " + serialPort + " saved to settings"); + _logger.LogDebug("Port: " + serialPort + " saved to settings"); // Check if Cyton Daisy board attached // Makes separate COM connection (BrainFlow / BoardShim does not allow parsing of responses from lower level commands @@ -375,7 +387,7 @@ public override bool InitDevice(string deviceIdentifier) DeviceObj = new BoardShim(boardID, input_params); DeviceObj.prepare_session(); - Log.Debug("DAQ_OpenBCI - InitDevice | Board session prepared"); + _logger.LogDebug("DAQ_OpenBCI - InitDevice | Board session prepared"); indEegChannels = BoardShim.get_eeg_channels(boardID); sampleRate = BoardShim.get_sampling_rate(boardID); @@ -385,12 +397,12 @@ public override bool InitDevice(string deviceIdentifier) FrontendFilter = new Filter(frontendFilterIdx, Filter.FilterTypes.Frontend); NotchFilter = new Filter(notchFilterIdx, Filter.FilterTypes.Notch); - Log.Debug("Creating Frontend filter: " + frontendFilterIdx + " | Notch filter: " + notchFilterIdx); + _logger.LogDebug("Creating Frontend filter: " + frontendFilterIdx + " | Notch filter: " + notchFilterIdx); status = BoardStatus.BOARD_OPEN; deviceInitialized = true; AddWarning(ExitCodes.IDLE, " Time: " + DateTime.Now.ToString("h:mm:ss tt") + " STATUS MESSAGE: Device initialized at serial port: " + serialPort); - Log.Debug("Board initialized. Status: " + status.ToString()); + _logger.LogDebug("Board initialized. Status: " + status.ToString()); return true; } else @@ -399,7 +411,7 @@ public override bool InitDevice(string deviceIdentifier) } catch (Exception e) { - Log.Exception(e.Message); + _logger.LogError(e, e.Message); sensorStatus = getErrorCode(e.Message, ExitCodes.BOARD_NOT_READY_ERROR); AddWarning(sensorStatus, " Time: " + DateTime.Now.ToString("h:mm:ss tt") + " WARNING MESSAGE: Error Code: " + sensorStatus); return false; @@ -422,7 +434,7 @@ public override bool Start(string deviceIdentifier = "", bool saveData = false, { // Init device bool initPortSuccess; - Log.Debug("Initiating device"); + _logger.LogDebug("Initiating device"); if (status != BoardStatus.BOARD_OPEN) { if (!String.IsNullOrWhiteSpace(deviceIdentifier)) @@ -433,15 +445,15 @@ public override bool Start(string deviceIdentifier = "", bool saveData = false, else initPortSuccess = true; - Log.Debug("Starting stream"); + _logger.LogDebug("Starting stream"); DeviceObj.start_stream(); - Log.Debug("Stream started"); + _logger.LogDebug("Stream started"); status = BoardStatus.BOARD_ACQUIRINGDATA; if (saveDataToFile) { - Log.Debug("Creating files for session " + sessionID); + _logger.LogDebug("Creating files for session " + sessionID); CreateFiles(sessionID); } @@ -455,10 +467,10 @@ public override bool Start(string deviceIdentifier = "", bool saveData = false, { sensorStatus = getErrorCode(e.Message, ExitCodes.BOARD_NOT_CREATED_ERROR); AddWarning(sensorStatus, " Time: " + DateTime.Now.ToString("h:mm:ss tt") + " WARNING MESSAGE: Error Code: " + sensorStatus); - Log.Exception("Exception:" + e.Message + " Error code:" + sensorStatus); + _logger.LogError("Exception:" + e.Message + " Error code:" + sensorStatus); success = false; } - Log.Debug("Device started: " + success); + _logger.LogDebug("Device started: " + success); return success; } @@ -472,19 +484,19 @@ public override bool Stop() { if (status == BoardStatus.BOARD_ACQUIRINGDATA) { - Log.Debug("Board acquiring data. Stopping device"); + _logger.LogDebug("Board acquiring data. Stopping device"); GetData(); DeviceObj.stop_stream(); DeviceObj.release_session(); - Log.Debug("Device stopped"); + _logger.LogDebug("Device stopped"); } if (saveDataToFile && FileWriterObj != null && FileWriterObj.isFileOpened) { - Log.Debug("Closing files"); + _logger.LogDebug("Closing files"); FileWriterObj.CloseFiles(); FileWriterObj = null; - Log.Debug("Files closed"); + _logger.LogDebug("Files closed"); } status = BoardStatus.BOARD_STANDBY; @@ -494,7 +506,7 @@ public override bool Stop() { sensorStatus = getErrorCode(e.Message, ExitCodes.SYNC_TIMEOUT_ERROR); AddWarning(sensorStatus, " Time: " + DateTime.Now.ToString("h:mm:ss tt") + " WARNING MESSAGE: Error Code: " + sensorStatus); - Log.Exception("Exception:" + e.Message + " Error code: " + sensorStatus); + _logger.LogError("Exception:" + e.Message + " Error code: " + sensorStatus); return false; } } @@ -509,7 +521,7 @@ public override bool CloseDevice() { if (status == BoardStatus.BOARD_CLOSED) { - Log.Debug("Board already closed"); + _logger.LogDebug("Board already closed"); return true; } @@ -518,14 +530,14 @@ public override bool CloseDevice() DeviceObj.release_session(); status = BoardStatus.BOARD_CLOSED; - Log.Debug("Device closed"); + _logger.LogDebug("Device closed"); return true; } catch (Exception e) { sensorStatus = getErrorCode(e.Message, ExitCodes.UNABLE_TO_CLOSE); AddWarning(sensorStatus, " Time: " + DateTime.Now.ToString("h:mm:ss tt") + " WARNING MESSAGE: Error Code: " + sensorStatus); - Log.Exception("Exception:" + e.Message + " Error code: " + sensorStatus); + _logger.LogError("Exception:" + e.Message + " Error code: " + sensorStatus); return false; } } @@ -570,7 +582,7 @@ public override bool CloseDevice() } catch (Exception e) { - Log.Exception("Exception: " + e.Message); + _logger.LogError(e, e.Message); } if (returnFilteredData) @@ -715,7 +727,7 @@ public override SignalStatus GetStatus(out SignalStatus[] statusSignals) } catch (Exception e) { - Log.Exception("Exception: " + e.Message); + _logger.LogError(e, e.Message); } } return statusAllSignals; @@ -738,7 +750,7 @@ public SignalStatus GetStatus2_ReceivedData() /// /// /// - private bool AppendDataToBuffer(double[,] data, double[,] inBuffer, int numSamplesInBuffer, out double[,] outBuffer) + protected override bool AppendDataToBuffer(double[,] data, double[,] inBuffer, int numSamplesInBuffer, out double[,] outBuffer) { bool result = false; outBuffer = null; @@ -765,7 +777,7 @@ private bool AppendDataToBuffer(double[,] data, double[,] inBuffer, int numSampl } catch (Exception e) { - Log.Exception(e.Message); + _logger.LogError(e, e.Message); } return result; } @@ -831,7 +843,7 @@ public bool DetectEyesClosed(out double[] alphaValues, out double avgAlpha, out } catch (Exception e) { - Log.Exception(e.Message); + _logger.LogError(e, e.Message); } } avgAlpha /= indEegChannels.Length; @@ -860,7 +872,7 @@ private bool TestPort(String port, out bool portAlreadyOpen) portAlreadyOpen = false; try { - Log.Debug("Testing port " + port); + _logger.LogDebug("Testing port " + port); BrainFlowInputParams input_params = new() { serial_port = port @@ -869,7 +881,7 @@ private bool TestPort(String port, out bool portAlreadyOpen) DeviceObj = new BoardShim(boardID, input_params); DeviceObj.prepare_session(); DeviceObj.release_session(); - Log.Debug("Sensor detected to port" + port); + _logger.LogDebug("Sensor detected to port" + port); return true; } catch (Exception e) @@ -878,7 +890,7 @@ private bool TestPort(String port, out bool portAlreadyOpen) if (sensorStatus == ExitCodes.ANOTHER_BOARD_IS_CREATED_ERROR) portAlreadyOpen = true; AddWarning(sensorStatus, " Time: " + DateTime.Now.ToString("h:mm:ss tt") + " WARNING MESSAGE: Error Code: " + sensorStatus); - Log.Exception("Exception: " + e.Message); + _logger.LogError(e, e.Message); return false; } } @@ -927,7 +939,7 @@ private UInt32 ReadLatencyTimerValue(String comPort) } catch (Exception e) { - Log.Exception("Exception: " + e.Message); + _logger.LogError(e, e.Message); } return 0; @@ -953,13 +965,13 @@ private ExitCodes getErrorCode(string message, ExitCodes defaultErrorCode) /// Creates files where data is stored /// /// - private void CreateFiles(String sessionID) + protected override void CreateFiles(String sessionID) { if (saveDataToFile) { if (FileWriterObj == null) { - Log.Debug("Creating files for session: " + sessionID); + _logger.LogDebug("Creating files for session: " + sessionID); if (sessionID == "") FileWriterObj = new FileWriter(); @@ -993,7 +1005,7 @@ public override bool StartSession(string sessionID, bool forceSavingData) if (saveDataToFile) { - Log.Debug("Creating files for session: " + sessionID); + _logger.LogDebug("Creating files for session: " + sessionID); // Creates new file if (sessionID == "") @@ -1010,7 +1022,7 @@ public override bool StartSession(string sessionID, bool forceSavingData) } catch (Exception e) { - Log.Exception("Exception " + e.Message); + _logger.LogError(e.Message); } return result; } @@ -1033,12 +1045,12 @@ public override bool EndSession() { GetData(); // Empty buffer } - Log.Debug("Session closed"); + _logger.LogDebug("Session closed"); result = true; } catch (Exception e) { - Log.Exception("Exception " + e.Message); + _logger.LogError(e.Message); } return result; @@ -1082,7 +1094,7 @@ public Dictionary getWarning() } catch (Exception e) { - Log.Exception(e.Message); + _logger.LogError(e, e.Message); return info; } return info; @@ -1092,16 +1104,16 @@ public Dictionary getWarning() /// Send lower level config command to BoardShim device /// /// - public void Config_Board(string cmd) + public override void Config_Board(string cmd) { try { - Log.Debug("Config board. Command" + cmd); + _logger.LogDebug("Config board. Command" + cmd); DeviceObj.config_board(cmd); } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, ex.Message); } } @@ -1160,14 +1172,14 @@ private bool cytonIsDaisyAttached(String comPort) NewLine = "$$$" }; - Log.Debug(String.Format("cytonIsDaisyAttached | Opening serial port with port name: {0}, baud rate: {1}", serialPort.PortName, serialPort.BaudRate)); + _logger.LogDebug(String.Format("cytonIsDaisyAttached | Opening serial port with port name: {0}, baud rate: {1}", serialPort.PortName, serialPort.BaudRate)); serialPort.Open(); Thread.Sleep(100); // If the port is open, do something if (serialPort.IsOpen) { - Log.Debug("cytonIsDaisyAttached | serialPort is open"); + _logger.LogDebug("cytonIsDaisyAttached | serialPort is open"); int max_tries = 3; while (!receivedResponse && max_tries > 0) { @@ -1176,7 +1188,7 @@ private bool cytonIsDaisyAttached(String comPort) Thread.Sleep(1000); String response = serialPort.ReadLine().Trim(); - Log.Debug(String.Format("cytonIsDaisyAttached | response: {0}", response)); + _logger.LogDebug(String.Format("cytonIsDaisyAttached | response: {0}", response)); if (response == "8" || response == "16") { @@ -1203,7 +1215,7 @@ private bool cytonIsDaisyAttached(String comPort) Thread.Sleep(500); } - Log.Debug("cytonIsDaisyAttached | End read line / check loop. Sending reset board command"); + _logger.LogDebug("cytonIsDaisyAttached | End read line / check loop. Sending reset board command"); serialPort.WriteLine("d"); Thread.Sleep(3500); } @@ -1221,35 +1233,35 @@ private bool cytonIsDaisyAttached(String comPort) BCIActuatorSettings.Settings.DAQ_NumEEGChannels = 8; _daisyBoardStatus = DaisyBoardStatus.NOT_CONNECTED; } - Log.Debug("cytonIsDaisyAttached | Received a valid response from cyton board | DAQ_NumEEGChannels: " + + _logger.LogDebug("cytonIsDaisyAttached | Received a valid response from cyton board | DAQ_NumEEGChannels: " + BCIActuatorSettings.Settings.DAQ_NumEEGChannels.ToString()); BCIActuatorSettings.Save(); } else { - Log.Debug("cytonIsDaisyAttached | Did not receive a valid response from cyton board. Setting DAQ_NumEEGChannels to 8"); + _logger.LogDebug("cytonIsDaisyAttached | Did not receive a valid response from cyton board. Setting DAQ_NumEEGChannels to 8"); BCIActuatorSettings.Settings.DAQ_NumEEGChannels = 16; } } catch (Exception e) { - Log.Exception(e.Message); + _logger.LogError(e, e.Message); } finally { - Log.Debug("cytonIsDaisyAttached | closing serialPort from finally"); + _logger.LogDebug("cytonIsDaisyAttached | closing serialPort from finally"); serialPort.Close(); - Log.Debug("cytonIsDaisyAttached | serialPort closed from finally"); + _logger.LogDebug("cytonIsDaisyAttached | serialPort closed from finally"); } if (serialPort != null && serialPort.IsOpen) { - Log.Debug("cytonIsDaisyAttached | serialPort not yet closed. calling close() again"); + _logger.LogDebug("cytonIsDaisyAttached | serialPort not yet closed. calling close() again"); serialPort.Close(); } - Log.Debug(String.Format("cytonDaisyAttached() done | " + + _logger.LogDebug(String.Format("cytonDaisyAttached() done | " + "receivedResponse: {0}, " + "daisyBoardAttached: {1}, " + "BCIActuatorSettings.Settings.DAQ_NumEEGChannels: {2}", diff --git a/src/Extensions/BCI/Actuators/EEGDataAcquisition/DAQ_gTecBCI.cs b/src/Extensions/BCI/Actuators/EEGDataAcquisition/DAQ_gTecBCI.cs index 9f48cc7b..24e48f45 100644 --- a/src/Extensions/BCI/Actuators/EEGDataAcquisition/DAQ_gTecBCI.cs +++ b/src/Extensions/BCI/Actuators/EEGDataAcquisition/DAQ_gTecBCI.cs @@ -19,6 +19,7 @@ using Gtec.Unicorn; #endif +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; @@ -31,6 +32,8 @@ namespace ACAT.Extensions.BCI.Actuators.EEG.EEGDataAcquisition /// public class DAQ_gTecBCI : BaseDAQ { + private static new readonly ILogger _logger = LoggingConfiguration.CreateLogger(); + /// /// MInimum duty cycle required to pass trigger test. Set to 0 for no duty cycle requirement /// @@ -55,7 +58,7 @@ public override void LoadSettings() { SignalControl_WindowDurationForVrmsMeaseurment = BCIActuatorSettings.Settings.SignalControl_WindowDurationForVrmsMeaseurment; SignalControl_MinDutyCycleToPassTriggerTest = BCIActuatorSettings.Settings.TriggerTest_MinDutyCycleToPassTriggerTest; - Log.Debug("DAQ settings loaded. Min duty cycle to pass trigger test" + SignalControl_MinDutyCycleToPassTriggerTest + " Window duration for uVrmsMeasurement: " + SignalControl_WindowDurationForVrmsMeaseurment); + _logger.LogDebug("DAQ settings loaded. Min duty cycle to pass trigger test" + SignalControl_MinDutyCycleToPassTriggerTest + " Window duration for uVrmsMeasurement: " + SignalControl_WindowDurationForVrmsMeaseurment); // Gtec Does not have hardware trigger so we will keep both same for ML that support openbci BCIActuatorSettings.Settings.DAQ_NumEEGChannels = 8; @@ -80,14 +83,14 @@ public override void LoadSettings() BCIActuatorSettings.Save(); - Log.Debug("Sensor set to " + BCIActuatorSettings.Settings.DAQ_NumEEGChannels + " channels. SensorID: " + BCISettingsFixed.DAQ_SensorId + " , Downsample rate: " + BCISettingsFixed.DimReduct_DownsampleRate + + _logger.LogDebug("Sensor set to " + BCIActuatorSettings.Settings.DAQ_NumEEGChannels + " channels. SensorID: " + BCISettingsFixed.DAQ_SensorId + " , Downsample rate: " + BCISettingsFixed.DimReduct_DownsampleRate + " , Idx hw trigger signal: " + BCISettingsFixed.DataParser_IdxTriggerSignal_Hw + " , Idx sw trigger signal: " + BCISettingsFixed.DataParser_IdxTriggerSignal_Sw); saveDataToFile = BCIActuatorSettings.Settings.DAQ_SaveToFileFlag; frontendFilterIdx = BCIActuatorSettings.Settings.DAQ_FrontendFilterIdx; notchFilterIdx = BCIActuatorSettings.Settings.DAQ_NotchFilterIdx; - Log.Debug(" Frontend filter: " + frontendFilterIdx + " Notch filter: " + notchFilterIdx); + _logger.LogDebug(" Frontend filter: " + frontendFilterIdx + " Notch filter: " + notchFilterIdx); } public static bool IsDeviceAvailable() @@ -110,7 +113,7 @@ public static bool IsDeviceAvailable() } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, ex.Message); } return success; @@ -139,13 +142,13 @@ public override bool InitDevice(string serial_number = "") if (status == BoardStatus.BOARD_OPEN) { - Log.Debug("Board was open, closing device"); + _logger.LogDebug("Board was open, closing device"); CloseDevice(); } if (status == BoardStatus.BOARD_ACQUIRINGDATA) { - Log.Debug("Board already acquiring data, returning"); + _logger.LogDebug("Board already acquiring data, returning"); return true; } else @@ -155,30 +158,30 @@ public override bool InitDevice(string serial_number = "") // Enable /disable boardlogging if (boardLoggerEnabled) { - Log.Debug("BoardLoggerEnabled: " + boardLoggerEnabled + " Enabling brainflow logging"); + _logger.LogDebug("BoardLoggerEnabled: " + boardLoggerEnabled + " Enabling brainflow logging"); BoardShim.enable_dev_board_logger(); BoardShim.set_log_file(boardLogFileName); } else { - Log.Debug("BoardLoggerEnabled: " + boardLoggerEnabled + " Disabling brainflow logging"); + _logger.LogDebug("BoardLoggerEnabled: " + boardLoggerEnabled + " Disabling brainflow logging"); BoardShim.disable_board_logger(); } // Test port - Log.Debug("Testing port: " + serial_number); + _logger.LogDebug("Testing port: " + serial_number); bool sensorConnected = TestPort(serial_number, out _); BrainFlowInputParams input_params = new(); if (sensorConnected) { - Log.Debug("Sensor connected to port " + serial_number); + _logger.LogDebug("Sensor connected to port " + serial_number); // Save port to settings BCIActuatorSettings.Settings.GTecDeviceName = serial_number; BCIActuatorSettings.Save(); - Log.Debug("Port: " + serial_number + " saved to settings"); + _logger.LogDebug("Port: " + serial_number + " saved to settings"); // DAQ_NumEEGChannels may have changed - run LoadSettings() at this point LoadSettings(); @@ -202,14 +205,14 @@ public override bool InitDevice(string serial_number = "") FrontendFilter = new Filter(frontendFilterIdx, Filter.FilterTypes.Frontend); NotchFilter = new Filter(notchFilterIdx, Filter.FilterTypes.Notch); - Log.Debug("Creating Frontend filter: " + frontendFilterIdx + " | Notch filter: " + notchFilterIdx); + _logger.LogDebug("Creating Frontend filter: " + frontendFilterIdx + " | Notch filter: " + notchFilterIdx); status = BoardStatus.BOARD_OPEN; deviceInitialized = true; AddWarning(ExitCodes.IDLE, " Time: " + DateTime.Now.ToString("h:mm:ss tt") + " STATUS MESSAGE: Device initialized at serial port: " + serial_number); - Log.Debug("Board initialized. Status: " + status.ToString()); + _logger.LogDebug("Board initialized. Status: " + status.ToString()); return true; } @@ -219,7 +222,7 @@ public override bool InitDevice(string serial_number = "") } catch (Exception e) { - Log.Exception(e.Message); + _logger.LogError(e.Message); sensorStatus = getErrorCode(e.Message, ExitCodes.BOARD_NOT_READY_ERROR); AddWarning(sensorStatus, " Time: " + DateTime.Now.ToString("h:mm:ss tt") + " WARNING MESSAGE: Error Code: " + sensorStatus); return false; @@ -242,22 +245,22 @@ public override bool Start(string serial_number = "", bool saveData = false, str { // Init device bool initPortSuccess; - Log.Debug("Initiating device"); + _logger.LogDebug("Initiating device"); if (status != BoardStatus.BOARD_OPEN) initPortSuccess = InitDevice(serial_number); else initPortSuccess = true; - Log.Debug("Starting stream"); + _logger.LogDebug("Starting stream"); Start_Streaming(); - Log.Debug("Stream started"); + _logger.LogDebug("Stream started"); status = BoardStatus.BOARD_ACQUIRINGDATA; //triggerTestInProgressFlag = false; if (saveDataToFile) { - Log.Debug("Creating files for session " + sessionID); + _logger.LogDebug("Creating files for session " + sessionID); CreateFiles(sessionID); } @@ -271,10 +274,10 @@ public override bool Start(string serial_number = "", bool saveData = false, str { sensorStatus = getErrorCode(e.Message, ExitCodes.BOARD_NOT_CREATED_ERROR); AddWarning(sensorStatus, " Time: " + DateTime.Now.ToString("h:mm:ss tt") + " WARNING MESSAGE: Error Code: " + sensorStatus); - Log.Exception("Exception:" + e.Message + " Error code:" + sensorStatus); + _logger.LogError("Exception:" + e.Message + " Error code:" + sensorStatus); success = false; } - Log.Debug("Device started: " + success); + _logger.LogDebug("Device started: " + success); return success; } @@ -288,18 +291,18 @@ public override bool Stop() { if (status == BoardStatus.BOARD_ACQUIRINGDATA) { - Log.Debug("Board acquiring data. Stopping device"); + _logger.LogDebug("Board acquiring data. Stopping device"); GetData(); Stop_Streaming(); - Log.Debug("Device stopped"); + _logger.LogDebug("Device stopped"); } if (saveDataToFile && FileWriterObj != null && FileWriterObj.isFileOpened) { - Log.Debug("Closing files"); + _logger.LogDebug("Closing files"); FileWriterObj.CloseFiles(); FileWriterObj = null; - Log.Debug("Files closed"); + _logger.LogDebug("Files closed"); } status = BoardStatus.BOARD_STANDBY; @@ -309,7 +312,7 @@ public override bool Stop() { sensorStatus = getErrorCode(e.Message, ExitCodes.SYNC_TIMEOUT_ERROR); AddWarning(sensorStatus, " Time: " + DateTime.Now.ToString("h:mm:ss tt") + " WARNING MESSAGE: Error Code: " + sensorStatus); - Log.Exception("Exception:" + e.Message + " Error code: " + sensorStatus); + _logger.LogError("Exception:" + e.Message + " Error code: " + sensorStatus); return false; } } @@ -324,7 +327,7 @@ public override bool CloseDevice() { if (status == BoardStatus.BOARD_CLOSED) { - Log.Debug("Board already closed"); + _logger.LogDebug("Board already closed"); return true; } @@ -334,14 +337,14 @@ public override bool CloseDevice() } status = BoardStatus.BOARD_CLOSED; - Log.Debug("Device closed"); + _logger.LogDebug("Device closed"); return true; } catch (Exception e) { sensorStatus = getErrorCode(e.Message, ExitCodes.UNABLE_TO_CLOSE); AddWarning(sensorStatus, " Time: " + DateTime.Now.ToString("h:mm:ss tt") + " WARNING MESSAGE: Error Code: " + sensorStatus); - Log.Exception("Exception:" + e.Message + " Error code: " + sensorStatus); + _logger.LogError("Exception:" + e.Message + " Error code: " + sensorStatus); return false; } } @@ -383,7 +386,7 @@ public override bool CloseDevice() } catch (Exception e) { - Log.Exception("Exception: " + e.Message); + _logger.LogError("Exception: " + e.Message); } if (returnFilteredData) @@ -414,14 +417,14 @@ private bool TestPort(String serial_number, out bool portAlreadyOpen) portAlreadyOpen = false; try { - Log.Debug("Testing port " + serial_number); + _logger.LogDebug("Testing port " + serial_number); BrainFlowInputParams input_params = new(); //input_params.serial_number = serial_number; DeviceObj = new BoardShim(boardID, input_params); DeviceObj.prepare_session(); DeviceObj.release_session(); - Log.Debug("Sensor detected to port" + serial_number); + _logger.LogDebug("Sensor detected to port" + serial_number); return true; } catch (Exception e) @@ -430,7 +433,7 @@ private bool TestPort(String serial_number, out bool portAlreadyOpen) if (sensorStatus == ExitCodes.ANOTHER_BOARD_IS_CREATED_ERROR) portAlreadyOpen = true; AddWarning(sensorStatus, " Time: " + DateTime.Now.ToString("h:mm:ss tt") + " WARNING MESSAGE: Error Code: " + sensorStatus); - Log.Exception("Exception: " + e.Message); + _logger.LogError("Exception: " + e.Message); return false; } } @@ -488,7 +491,7 @@ public Dictionary getWarning() } catch (Exception e) { - Log.Exception(e.Message); + _logger.LogError(e.Message); return info; } return info; @@ -544,7 +547,7 @@ public async Task> ScanDevicesAsync(bool paired = true) } catch (Gtec.Unicorn.DeviceException ex) { - Log.Exception($"Error: {ex.Message}"); + _logger.LogError(ex, ex.Message); } return devices; }); @@ -576,9 +579,9 @@ public async Task connectionTestAsync() { #if !SIMULATIONBOARD - Log.Debug($"Selected device: {BCIActuatorSettings.Settings.GTecDeviceName}, trying to connect..."); + _logger.LogDebug($"Selected device: {BCIActuatorSettings.Settings.GTecDeviceName}, trying to connect..."); using Unicorn device = new Unicorn(BCIActuatorSettings.Settings.GTecDeviceName); - Log.Debug($"Device: {device} is connected..."); + _logger.LogDebug($"Device: {device} is connected..."); device.Dispose(); #endif EvtBluetoothResult(BluetoothEvent.SUCCESSFUL_CONNECTION, null); @@ -586,7 +589,7 @@ public async Task connectionTestAsync() } catch (Gtec.Unicorn.DeviceException ex) { - Log.Exception($"Error: {ex.Message}"); + _logger.LogError(ex, ex.Message); Dictionary eventParams = new() { ["error"] = ex.Message @@ -596,7 +599,7 @@ public async Task connectionTestAsync() } catch (Exception ex) { - Log.Exception($"Unexpected error: {ex.Message}"); + _logger.LogError(ex, ex.Message); Dictionary eventParams = new() { ["error"] = ex.Message @@ -615,7 +618,7 @@ public async Task connectionTestAsync() /// Any extra params sent with bluetooth event request public void bluetoothRequestHandler(BluetoothEvent bluetoothEvent, Dictionary eventParams) { - Log.Debug("DAQ_gTecBCI | bluetoothRequestHandler | bluetoothEvent: " + bluetoothEvent.ToString()); + _logger.LogDebug("DAQ_gTecBCI | bluetoothRequestHandler | bluetoothEvent: " + bluetoothEvent.ToString()); switch (bluetoothEvent) { @@ -657,7 +660,7 @@ public override SignalStatus GetStatus(out SignalStatus[] statusSignals) } catch (Exception e) { - Log.Exception("Exception: " + e.Message); + _logger.LogError("Exception: " + e.Message); } } return statusAllSignals; diff --git a/src/Extensions/BCI/Actuators/EEGDataAcquisition/FileManagement/FileWriter.cs b/src/Extensions/BCI/Actuators/EEGDataAcquisition/FileManagement/FileWriter.cs index e075462a..26cf5ce5 100644 --- a/src/Extensions/BCI/Actuators/EEGDataAcquisition/FileManagement/FileWriter.cs +++ b/src/Extensions/BCI/Actuators/EEGDataAcquisition/FileManagement/FileWriter.cs @@ -13,6 +13,7 @@ using ACAT.Core.UserManagement; using ACAT.Core.Utility; using ACAT.Extensions.BCI.Actuators.EEG.EEGSettings; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.IO; @@ -24,6 +25,7 @@ namespace ACAT.Extensions.BCI.Actuators.EEG.EEGDataAcquisition.FileManagement { public class FileWriter { + private static readonly ILogger _logger = LoggingConfiguration.CreateLogger(); /// /// Directory for session /// @@ -172,8 +174,7 @@ private void WriteDataToFile(StreamWriter sw, double[,] data) } catch (Exception ex) { - Log.Exception(data[channelIdx, sampleIdx].ToString()); - Log.Exception(ex.ToString()); + _logger.LogError(ex, "Error writing data at channel {ChannelIdx}, sample {SampleIdx}, value: {Value}", channelIdx, sampleIdx, data[channelIdx, sampleIdx]); } if (channelIdx < numChannels - 1) stringBuilder.Append(", "); @@ -188,7 +189,7 @@ private void WriteDataToFile(StreamWriter sw, double[,] data) } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex, "Error writing data to file"); } finally { diff --git a/src/Extensions/BCI/Actuators/EEGProcessing/DataLoader/DataParser.cs b/src/Extensions/BCI/Actuators/EEGProcessing/DataLoader/DataParser.cs index a70f5321..9b76827f 100644 --- a/src/Extensions/BCI/Actuators/EEGProcessing/DataLoader/DataParser.cs +++ b/src/Extensions/BCI/Actuators/EEGProcessing/DataLoader/DataParser.cs @@ -12,6 +12,7 @@ using ACAT.Core.Utility; using ACAT.Extensions.BCI.Actuators.EEG.EEGSettings; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; @@ -21,6 +22,8 @@ namespace ACAT.Extensions.BCI.Actuators.EEG.EEGProcessing.DataLoader [Serializable] public class DataParser { + private static readonly ILogger _logger = LoggerFactory.Create(builder => builder.AddConsole()).CreateLogger(); + /// /// Offset added to targets /// (this parameter is typically set in settings) @@ -264,8 +267,7 @@ public void ParseData(double[,] inputData, int[] triggerData, List markerVa } catch (Exception e) { - //Log.Exception(e.getClass().getName()); e) - Log.Debug(e.Message); + _logger.LogDebug("{Message}", e.Message); } } @@ -288,7 +290,7 @@ public void ParseData(double[,] inputData, int[] triggerData, List markerVa remainingData = new double[numColumns, numRemainingSamples]; string txtLog = "Get " + numRemainingSamples + " remaining data. Input data with Num Columns: " + numColumns + " Num Samples: " + numSamples; - Log.Debug(txtLog); + _logger.LogDebug("{Message}", txtLog); try { for (int columnIdx = 0; columnIdx < numColumns; columnIdx++) @@ -296,11 +298,11 @@ public void ParseData(double[,] inputData, int[] triggerData, List markerVa remainingData[columnIdx, i] = allData[columnIdx, startingSampleIdx + i]; txtLog = "Remaining dat. Num Columns: " + remainingData.GetLength(0) + " Num samples: " + remainingData.GetLength(1); - Log.Debug(txtLog); + _logger.LogDebug("{Message}", txtLog); } catch (Exception e) { - Log.Exception(e.Message); + _logger.LogError(e, "{Message}", e.Message); } } diff --git a/src/Extensions/BCI/Actuators/EEGProcessing/DecisionMaker.cs b/src/Extensions/BCI/Actuators/EEGProcessing/DecisionMaker.cs index 950995f3..d126b42b 100644 --- a/src/Extensions/BCI/Actuators/EEGProcessing/DecisionMaker.cs +++ b/src/Extensions/BCI/Actuators/EEGProcessing/DecisionMaker.cs @@ -16,6 +16,8 @@ using ACAT.Core.Utility; using ACAT.Extensions.BCI.Actuators.EEG.EEGProcessing.Utilities; using ACAT.Extensions.BCI.Actuators.EEG.EEGSettings; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; using System; using System.Collections.Generic; using System.IO; @@ -24,6 +26,9 @@ namespace ACAT.Extensions.BCI.Actuators.EEG.EEGProcessing { public class DecisionMaker { + private static readonly ILogger _nullLogger = NullLogger.Instance; + private readonly ILogger _logger; + // ************ Params and objects loaded at init /// @@ -91,8 +96,9 @@ public class DecisionMaker /// /// Constructor (Params read from settings) /// - public DecisionMaker(string TrainedClassifiersFilePath) + public DecisionMaker(string TrainedClassifiersFilePath, ILogger logger = null) { + _logger = logger ?? _nullLogger; enableLanguageModelProbabilities = false; // by default (actuator will set flag for different type of LM probabilities) maxNumberOfSequences = BCIActuatorSettings.Settings.Classifier_MaxDecisionSequences; confidenceThreshold = BCIActuatorSettings.Settings.Classifier_ConfidenceThreshold; @@ -110,23 +116,24 @@ public DecisionMaker(string TrainedClassifiersFilePath) { TrainedClassifiersObj = BinaryUtils.ReadFromBinaryFile(TrainedClassifiersFilePath); - string logTxt = "Decision maker created with calibration file " + TrainedClassifiersObj.trainedClassifiersSessionID + ". AUC: " + TrainedClassifiersObj.meanAUC + " Max number of sequences: " + maxNumberOfSequences + ". Confidence threshold: " + confidenceThreshold; - Log.Debug(logTxt); + _logger.LogDebug("Decision maker created with calibration file {SessionID}. AUC: {MeanAUC} Max number of sequences: {MaxSequences}. Confidence threshold: {ConfidenceThreshold}", + TrainedClassifiersObj.trainedClassifiersSessionID, TrainedClassifiersObj.meanAUC, maxNumberOfSequences, confidenceThreshold); } else - Log.Debug("Calibration file does not exist"); + _logger.LogDebug("Calibration file does not exist"); } catch (Exception e) { - Log.Exception(e.Message); + _logger.LogError(e, "Exception in DecisionMaker constructor"); } } /// /// Constructor (Params as input) /// - public DecisionMaker(int maxNumberOfSeqs, float confThreshold) + public DecisionMaker(int maxNumberOfSeqs, float confThreshold, ILogger logger = null) { + _logger = logger ?? _nullLogger; maxNumberOfSequences = maxNumberOfSeqs; confidenceThreshold = confThreshold; @@ -135,7 +142,7 @@ public DecisionMaker(int maxNumberOfSeqs, float confThreshold) if (File.Exists(filePath)) TrainedClassifiersObj = BinaryUtils.ReadFromBinaryFile(filePath); else - Log.Debug("Calibration file does not exist"); + _logger.LogDebug("Calibration file does not exist"); _likelihoodsTarget = new Dictionary>(); _likelihoodsNontarget = new Dictionary>(); @@ -193,7 +200,7 @@ public void ComputePosteriorProbs(double[,] data2parse, List markerValues, TrainedClassifiersObj.UpdateChannelSubset(availableChannels); List markerValuesString = markerValues.ConvertAll(x => x.ToString()); - Log.Debug("Reduce data w/ " + data2parse.Length + " samples and " + String.Join(", ", markerValuesString) + " markers"); + _logger.LogDebug("Reduce data w/ {SampleCount} samples and {Markers} markers", data2parse.Length, String.Join(", ", markerValuesString)); // Append incomplete data and markers double[,] allDataToParse; @@ -203,7 +210,7 @@ public void ComputePosteriorProbs(double[,] data2parse, List markerValues, // Concatenate markers allMarkersToParse = incompleteMarkers; allMarkersToParse.AddRange(markerValues); - Log.Debug("Markers concatenated. Total markers: " + allMarkersToParse.Count); + _logger.LogDebug("Markers concatenated. Total markers: {TotalMarkers}", allMarkersToParse.Count); // Concatenate data int numColumns = data2parse.GetLength(0); @@ -217,7 +224,8 @@ public void ComputePosteriorProbs(double[,] data2parse, List markerValues, for (int sampleIdx = 0; sampleIdx < data2parse.GetLength(1); sampleIdx++) allDataToParse[columnIdx, sampleIdx + incompleteData.GetLength(1)] = data2parse[columnIdx, sampleIdx]; } - Log.Debug("Data concatenated. Total data: " + allDataToParse.GetLength(1) + " containing " + incompleteData.GetLength(1) + " from previous iterations and " + data2parse.GetLength(1) + " from current iteration"); + _logger.LogDebug("Data concatenated. Total data: {TotalData} containing {PreviousData} from previous iterations and {CurrentData} from current iteration", + allDataToParse.GetLength(1), incompleteData.GetLength(1), data2parse.GetLength(1)); } else { @@ -229,14 +237,14 @@ public void ComputePosteriorProbs(double[,] data2parse, List markerValues, List trialScores = TrainedClassifiersObj.Reduce(allDataToParse, allMarkersToParse, flashingSequence, out incompleteData, out incompleteMarkers); if (trialScores != null) - Log.Debug("Data reduced " + trialScores.Count + " trial scores found"); + _logger.LogDebug("Data reduced {TrialScoreCount} trial scores found", trialScores.Count); else - Log.Debug("Data not reduced. Scores returned null. Will reduce in new iteration"); + _logger.LogDebug("Data not reduced. Scores returned null. Will reduce in new iteration"); List appendedTrialScores = new(); if (incompleteTrialScores != null) { - Log.Debug("Creating appended list with " + incompleteTrialScores.Count + " scores"); + _logger.LogDebug("Creating appended list with {IncompleteScoreCount} scores", incompleteTrialScores.Count); appendedTrialScores = new List(incompleteTrialScores); } if (trialScores != null && trialScores.Count > 0) @@ -244,18 +252,20 @@ public void ComputePosteriorProbs(double[,] data2parse, List markerValues, // Append trial scores if (appendedTrialScores != null && appendedTrialScores.Count > 0) { - Log.Debug("Adding current " + trialScores.Count + " scores to appended trialscores"); + _logger.LogDebug("Adding current {CurrentScoreCount} scores to appended trialscores", trialScores.Count); appendedTrialScores.AddRange(trialScores); if (incompleteTrialScores != null) - Log.Debug("Appended trialScores. Total scores: " + appendedTrialScores.Count + " with " + incompleteTrialScores.Count + " from previous iteration and " + trialScores.Count + " from current iteration"); + _logger.LogDebug("Appended trialScores. Total scores: {TotalScores} with {PreviousScores} from previous iteration and {CurrentScores} from current iteration", + appendedTrialScores.Count, incompleteTrialScores.Count, trialScores.Count); else - Log.Debug("Appended trialScores. Total scores: " + appendedTrialScores.Count + " with 0 from previous iteration and " + trialScores.Count + " from current iteration"); + _logger.LogDebug("Appended trialScores. Total scores: {TotalScores} with 0 from previous iteration and {CurrentScores} from current iteration", + appendedTrialScores.Count, trialScores.Count); } else { appendedTrialScores = trialScores; - Log.Debug("No trial scores from previous iterations. Current " + trialScores.Count + " will be used"); + _logger.LogDebug("No trial scores from previous iterations. Current {CurrentScoreCount} will be used", trialScores.Count); } } @@ -268,22 +278,22 @@ public void ComputePosteriorProbs(double[,] data2parse, List markerValues, // List completeTrialScores = new List(appendedTrialScores); List completeTrialScores = new(appendedTrialScores.GetRange(0, flashingSequence.Count)); - Log.Debug("Calculating probabilities for " + completeTrialScores.Count + " scores corresponding to " + flashingSequence.Count + " trials"); + _logger.LogDebug("Calculating probabilities for {CompleteScoreCount} scores corresponding to {TrialCount} trials", completeTrialScores.Count, flashingSequence.Count); ComputePosteriorProbs(completeTrialScores.ToArray(), flashingSequence, out decided, out decidedButtonID, out repetition, out posteriorProbs, out eegProbs, out nextCharacterProbs); - Log.Debug("Posterior probabilities calculated. Repetition: " + repetition + " , Decided: " + decided + " , Decided button ID: " + decidedButtonID); + _logger.LogDebug("Posterior probabilities calculated. Repetition: {Repetition} , Decided: {Decided} , Decided button ID: {DecidedButtonID}", repetition, decided, decidedButtonID); if (appendedTrialScores.Count > flashingSequence.Count) { incompleteTrialScores = new List(appendedTrialScores.GetRange(flashingSequence.Count, appendedTrialScores.Count - flashingSequence.Count)); - Log.Debug("Incomplete Trial scores " + incompleteTrialScores.Count + " saved for next iteration"); + _logger.LogDebug("Incomplete Trial scores {IncompleteScoreCount} saved for next iteration", incompleteTrialScores.Count); } } else { if (trialScores != null) - Log.Debug("Incomplete trial scores. Expected: " + flashingSequence.Count + " Calculated: " + trialScores.Count + " Waiting for new repetition"); + _logger.LogDebug("Incomplete trial scores. Expected: {ExpectedCount} Calculated: {CalculatedCount} Waiting for new repetition", flashingSequence.Count, trialScores.Count); else - Log.Debug("Incomplete trial scores. Expected: " + flashingSequence.Count + " Calculated: 0 Waiting for new repetition"); + _logger.LogDebug("Incomplete trial scores. Expected: {ExpectedCount} Calculated: 0 Waiting for new repetition", flashingSequence.Count); if (incompleteTrialScores == null) incompleteTrialScores = appendedTrialScores; @@ -294,7 +304,7 @@ public void ComputePosteriorProbs(double[,] data2parse, List markerValues, } catch (Exception e) { - Log.Exception(e.Message); + _logger.LogError(e, "Exception in ComputePosteriorProbs"); } } @@ -371,7 +381,7 @@ public void ComputePosteriorProbs(double[] trialScores, Dictionary t // Add next character probabilities if (enableLanguageModelProbabilities && _languageModelProbabilities != null) { - Log.Debug("Adding language model probabilities"); + _logger.LogDebug("Adding language model probabilities"); if (_languageModelProbabilities.ContainsKey(buttonID)) { buttonLogPosterior += Math.Log(Math.Sqrt(_languageModelProbabilities[buttonID])); @@ -427,8 +437,7 @@ public void ComputePosteriorProbs(double[] trialScores, Dictionary t decided = false; if (maxProb > confidenceThreshold || _sequenceCount == maxNumberOfSequences) { - string txtLog = "Decision made. Repetition: " + _sequenceCount + " Probability: " + maxProb; - Log.Debug(txtLog); + _logger.LogDebug("Decision made. Repetition: {SequenceCount} Probability: {MaxProb}", _sequenceCount, maxProb); decided = true; _sequenceCount = 0; _likelihoodsTarget = new Dictionary>(); @@ -440,14 +449,14 @@ public void ComputePosteriorProbs(double[] trialScores, Dictionary t } if (posteriorProbs == null || posteriorProbs.Count == 0) - Log.Debug("Zero posteriorProbs"); + _logger.LogDebug("Zero posteriorProbs"); } else - Log.Debug("Error when computing probabilities, trialScore is null or 0, returning null and restarting algorithm"); + _logger.LogDebug("Error when computing probabilities, trialScore is null or 0, returning null and restarting algorithm"); } catch (Exception e) { - Log.Exception(e.Message); + _logger.LogError(e, "Exception in ComputePosteriorProbs"); } } @@ -456,7 +465,7 @@ public void ComputePosteriorProbs(double[] trialScores, Dictionary t /// public void RestartProbabilities() { - Log.Debug("Restarting probabilities"); + _logger.LogDebug("Restarting probabilities"); _sequenceCount = 0; _likelihoodsTarget = new Dictionary>(); _likelihoodsNontarget = new Dictionary>(); diff --git a/src/Extensions/BCI/Actuators/EEGProcessing/DimReduction/DimReductChanSel.cs b/src/Extensions/BCI/Actuators/EEGProcessing/DimReduction/DimReductChanSel.cs index 4811b03d..143e692a 100644 --- a/src/Extensions/BCI/Actuators/EEGProcessing/DimReduction/DimReductChanSel.cs +++ b/src/Extensions/BCI/Actuators/EEGProcessing/DimReduction/DimReductChanSel.cs @@ -12,6 +12,7 @@ using ACAT.Core.Utility; using Accord.Math; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; @@ -21,11 +22,14 @@ namespace ACAT.Extensions.BCI.Actuators.EEG.EEGProcessing.DimReduction [Serializable] public class DimReductChanSel { + [NonSerialized] + private readonly ILogger _logger; // Subset of channels public int[] channelSubset; public DimReductChanSel(int[] pChannelSubset) { + _logger = LoggingConfiguration.CreateLogger(); channelSubset = pChannelSubset; } @@ -85,7 +89,7 @@ public bool Reduce(List inputData, out List outputData) } catch (Exception e) { - Log.Exception(e.Message); + _logger?.LogError(e, "Error during dimension reduction processing"); } return true; } diff --git a/src/Extensions/BCI/Actuators/EEGProcessing/FeatureExtraction.cs b/src/Extensions/BCI/Actuators/EEGProcessing/FeatureExtraction.cs index 3a0b89c9..2daf1ddd 100644 --- a/src/Extensions/BCI/Actuators/EEGProcessing/FeatureExtraction.cs +++ b/src/Extensions/BCI/Actuators/EEGProcessing/FeatureExtraction.cs @@ -23,6 +23,7 @@ using ACAT.Extensions.BCI.Actuators.EEG.EEGSettings; using ACAT.Extensions.BCI.Common.BCIControl; using Accord.Math; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.IO; @@ -33,6 +34,8 @@ namespace ACAT.Extensions.BCI.Actuators.EEG.EEGProcessing [Serializable] public class FeatureExtraction { + private readonly ILogger _logger; + /// /// Path of the trained classifiers /// @@ -161,8 +164,9 @@ public class FeatureExtraction /// /// /// - public FeatureExtraction(Dictionary pSymbolsInGroups, CalibrationParametersForSection pCalibrationParameters, int numRows = 6, int numCols = 6, bool isRowCol = true) + public FeatureExtraction(Dictionary pSymbolsInGroups, CalibrationParametersForSection pCalibrationParameters, int numRows = 6, int numCols = 6, bool isRowCol = true, ILogger logger = null) { + _logger = logger; // Get parameters from settings offsetTarget = BCIActuatorSettings.Settings.Calibration_OffsetTarget; windowDuration = BCIActuatorSettings.Settings.FeatureExtraction_WindowDurationInMs / 1000f; @@ -357,8 +361,7 @@ public float Learn(String sessionID) // Train classifiers trainedClassifiersSessionID = sessionID; - string txtLog = "Read data " + sessionID; - Log.Debug(txtLog); + _logger?.LogDebug("Read data {SessionID}", sessionID); FileReader fileReaderObj = new(); fileReaderObj.ReadDataAndMarkersFromFiles(sessionID, out rawData, out triggerSignal, out markerValues, out sessionDirectory); //fileReaderObj.ReadDataAndMarkersFromTestFiles(out rawData, out triggerSignal, out markerValues, out sessionDirectory, @@ -366,20 +369,19 @@ public float Learn(String sessionID) int numSamples = rawData.GetLength(1); int numColumns = rawData.GetLength(0); - txtLog = "Raw data read " + sessionID + " Num samples: " + numSamples + " Num channels: " + numColumns; - Log.Debug(txtLog); + _logger?.LogDebug("Raw data read {SessionID} Num samples: {NumSamples} Num channels: {NumColumns}", sessionID, numSamples, numColumns); //Plots.plotTriggerSignal(triggerSignal); // 1.2 Filter - Log.Debug("Filtering data"); + _logger?.LogDebug("Filtering data"); _BandPassFilter.FilterData(rawData, triggerSignal, out double[,] filteredData, out int[] delayedTriggerSignal); - Log.Debug("Data filtered"); + _logger?.LogDebug("Data filtered"); //Plots.plotSignal(filteredData, 1); // 1.2 Parse file - Log.Debug("Parsing data"); + _logger?.LogDebug("Parsing data"); _DataParserObj.ParseData(filteredData, delayedTriggerSignal, markerValues, _symbolsInGroups, out inputData, out trialTargetness, out trialLabels, out List trialGroups, out List targetLabels, out _, out _, true); // ===================== 2. Preprocessing ========================== @@ -387,8 +389,7 @@ public float Learn(String sessionID) { int[] trialTargetnessArray = trialTargetness.ToArray(); - txtLog = "Data parsed. Num trials: " + inputData.Count; - Log.Debug(txtLog); + _logger?.LogDebug("Data parsed. Num trials: {Count}", inputData.Count); // 2.1 Select subset of channels (if applicable) _DimReductChannelSelectionObj.Reduce(inputData, out inputData); @@ -400,21 +401,18 @@ public float Learn(String sessionID) // ===================== 3. Feature selection ========================== // 3.1 PCA (reduce dimensions) - Log.Debug("Applying PCA"); + _logger?.LogDebug("Applying PCA"); _DimReductPCAObj.Learn(inputData); _DimReductPCAObj.Reduce(inputData, out trialData); // 3.2 RDA (transform to scores using crossValidation) - txtLog = "Crossvalidation with " + trialData.Count + " trials"; - Log.Debug(txtLog); + _logger?.LogDebug("Crossvalidation with {Count} trials", trialData.Count); scores = _CrossValidationObj.CrossValidate(_DimReductRDAObj, trialData, trialTargetness); // Calculate performance - txtLog = "Calculating AUC for " + scores.Count + " trials"; - Log.Debug(txtLog); + _logger?.LogDebug("Calculating AUC for {Count} trials", scores.Count); meanAUC = ClassifierUtils.CalculateAUC(scores, trialTargetnessArray, out double[] TPrate, out double[] FPrate); - txtLog = "AUC " + meanAUC; - Log.Debug(txtLog); + _logger?.LogDebug("AUC {MeanAUC}", meanAUC); // 3.3 Train RDA with all data (scores for target/nontarget class distributions are calculated with crossV) _DimReductRDAObj.Learn(trialData, trialTargetness.ToList()); @@ -452,7 +450,7 @@ public float Learn(String sessionID) } catch (Exception e) { - Log.Exception(e.Message); + _logger?.LogError(e, e.Message); meanAUC = -1; // Save Error in file @@ -475,26 +473,26 @@ public List Reduce(List inputData) { // ===================== 2. Preprocessing ========================== // 2.1 Select subset of channels (if applicable) - Log.Debug("Reducing number of channels for " + inputData.Count + " trials"); + _logger?.LogDebug("Reducing number of channels for {Count} trials", inputData.Count); _DimReductChannelSelectionObj.Reduce(inputData, out inputData); - Log.Debug("Number of channels reduced to " + _DimReductChannelSelectionObj.channelSubset.Length); + _logger?.LogDebug("Number of channels reduced to {Length}", _DimReductChannelSelectionObj.channelSubset.Length); // 2.2 Downsample - Log.Debug("Downsampling"); + _logger?.LogDebug("Downsampling"); _DimReductDownSampleObj.Reduce(inputData, out inputData); - Log.Debug("Data downsampled by " + _DimReductDownSampleObj.downsampleRate + " for " + inputData.Count + " trials"); + _logger?.LogDebug("Data downsampled by {Rate} for {Count} trials", _DimReductDownSampleObj.downsampleRate, inputData.Count); // ===================== 3. Feature selection ========================== // PCA (reduce dimensions)" - Log.Debug("Starting PCA.reduce for " + inputData.Count + " trials"); + _logger?.LogDebug("Starting PCA.reduce for {Count} trials", inputData.Count); _DimReductPCAObj.Reduce(inputData, out List trialData); - Log.Debug("PCA reduced for " + trialData.Count); + _logger?.LogDebug("PCA reduced for {Count}", trialData.Count); // RDA (obtain 1-dimensional scores) - Log.Debug("Starting RDA.reduce for " + trialData.Count + " trials"); + _logger?.LogDebug("Starting RDA.reduce for {Count} trials", trialData.Count); _DimReductRDAObj.Reduce(trialData, out List scores); - Log.Debug("RDA reduced " + scores.Count + " scores"); + _logger?.LogDebug("RDA reduced {Count} scores", scores.Count); return scores; } @@ -514,18 +512,18 @@ public List Reduce(double[,] allData, List markerValues, Dictionary int numSamples = allData.GetLength(1); int numColumns = allData.GetLength(0); incompleteData = null; - Log.Debug("Parsing data from brainflow " + numSamples + " samples and " + numColumns + " columns"); + _logger?.LogDebug("Parsing data from brainflow {NumSamples} samples and {NumColumns} columns", numSamples, numColumns); _DataParserObj.ParseDataFromBrainflow(allData, out double[,] rawData, out int[] triggerSignal, out _); numSamples = rawData.GetLength(1); - Log.Debug("Data parsed " + numSamples + " samples."); + _logger?.LogDebug("Data parsed {NumSamples} samples.", numSamples); _BandPassFilter.FilterData(rawData, triggerSignal, out double[,] filteredData, out int[] delayedTriggerSignal); // 1.2 Parse file - Log.Debug("Parsing data"); + _logger?.LogDebug("Parsing data"); _DataParserObj.ParseData(filteredData, delayedTriggerSignal, markerValues, symbolsInGroups, out List trialData, out _, out _, out List trialMarkers, out _, out int incompleteSampleIdx, out incompleteMarkerValues); - Log.Debug("Data parsed for " + trialMarkers.Count + " markers and" + trialData.Count + " trials"); + _logger?.LogDebug("Data parsed for {MarkersCount} markers and {TrialsCount} trials", trialMarkers.Count, trialData.Count); // trialLabels: if singleBox paradigm: trialLabels[trial1][boxID] // if RC paradigm: trialLabels[trial1][box1 box2 box3] containing all highlighted boxes @@ -534,13 +532,13 @@ public List Reduce(double[,] allData, List markerValues, Dictionary { int startSampleIdx = incompleteSampleIdx - _BandPassFilter.GetGroupDelay(); incompleteData = _DataParserObj.GetRemaining(allData, startSampleIdx); - Log.Debug("Incomplete data remaining with " + incompleteData.GetLength(1) + " columns and " + incompleteData.GetLength(0) + " samples for " + trialMarkers.Count + " markers"); + _logger?.LogDebug("Incomplete data remaining with {Columns} columns and {Samples} samples for {MarkersCount} markers", incompleteData.GetLength(1), incompleteData.GetLength(0), trialMarkers.Count); } if (trialData.Count > 0 && trialData.Count == trialMarkers.Count) { trialScores = Reduce(trialData); - Log.Debug("Reduced " + trialScores.Count + " trials found"); + _logger?.LogDebug("Reduced {Count} trials found", trialScores.Count); } return trialScores; // will return null if can't be computed } diff --git a/src/Extensions/BCI/Actuators/EEGProcessing/Utilities/FileReader.cs b/src/Extensions/BCI/Actuators/EEGProcessing/Utilities/FileReader.cs index e09fdccb..f768e215 100644 --- a/src/Extensions/BCI/Actuators/EEGProcessing/Utilities/FileReader.cs +++ b/src/Extensions/BCI/Actuators/EEGProcessing/Utilities/FileReader.cs @@ -30,7 +30,7 @@ internal class FileReader /// public FileReader(ILogger logger = null) { - _logger = logger ?? LoggerFactory.GetLogger(); + _logger = logger ?? LoggingConfiguration.CreateLogger(); } /// diff --git a/src/Extensions/BCI/Actuators/EEGUtilities/SerialComm.cs b/src/Extensions/BCI/Actuators/EEGUtilities/SerialComm.cs index a8b7ca69..e6eb455e 100644 --- a/src/Extensions/BCI/Actuators/EEGUtilities/SerialComm.cs +++ b/src/Extensions/BCI/Actuators/EEGUtilities/SerialComm.cs @@ -30,7 +30,7 @@ internal class SerialComm public SerialComm(String portName, ILogger logger = null) { - _logger = logger ?? LoggerFactory.GetLogger(); + _logger = logger ?? LoggingConfiguration.CreateLogger(); _portName = portName; } diff --git a/src/Extensions/BCI/Actuators/gTec_SensorUI/SensorForm.cs b/src/Extensions/BCI/Actuators/gTec_SensorUI/SensorForm.cs index 0b3449ea..d18ba71d 100644 --- a/src/Extensions/BCI/Actuators/gTec_SensorUI/SensorForm.cs +++ b/src/Extensions/BCI/Actuators/gTec_SensorUI/SensorForm.cs @@ -134,7 +134,7 @@ public SensorForm(DAQ_gTecBCI gTecBCI, ILogger logger) _userControlBCIErrorgTecBoard.buttonRetry_userControlBCIErrorgTecBoard.Click += new EventHandler(this.buttonRetest_Click); _userControlBCIErrorgTecBoard.Dock = DockStyle.Fill; - _userControlErrorBluetoothDisconnected = new UserControlErrorBluetoothDisconnected(); + _userControlErrorBluetoothDisconnected = new UserControlErrorBluetoothDisconnected(null); _userControlErrorBluetoothDisconnected.buttonExit_userControlErrorBluetoothDisconnected.Click += new EventHandler(this.buttonExit_Click); _userControlErrorBluetoothDisconnected.buttonNext_userControlErrorBluetoothDisconnected.Click += new EventHandler(this.buttonNext_Click); _userControlErrorBluetoothDisconnected.Dock = DockStyle.Fill; @@ -154,7 +154,7 @@ public SensorForm(DAQ_gTecBCI gTecBCI, ILogger logger) _userControlPromptBCIFIlterSettings.buttonNext_userControlPromptBCIFIlterSettings.Click += new EventHandler(this.buttonNext_Click); _userControlPromptBCIFIlterSettings.Dock = DockStyle.Fill; - _userControlBCISignalCheck = new UserControlBCISignalCheck(); + _userControlBCISignalCheck = new UserControlBCISignalCheck(null); _userControlBCISignalCheck.buttonExit_userControlBCISignalCheck.Click += new EventHandler(this.buttonExit_Click); _userControlBCISignalCheck.buttonNext_userControlBCISignalCheck.Click += new EventHandler(this.buttonNext_Click); _userControlBCISignalCheck.Dock = DockStyle.Fill; @@ -362,8 +362,8 @@ public void TaskStartStopDataProcessing(OnboardingUserState state) /// private void startStopProcessDataTimer(bool startProcessDataTimer, OnboardingUserState state) { - Log.Debug("startStopProcessDataTimer | startProcessDataTimer: " + startProcessDataTimer.ToString() + - " | state: " + state.ToString()); + _logger.LogDebug("startStopProcessDataTimer | startProcessDataTimer: {StartProcessDataTimer} | state: {State}", + startProcessDataTimer, state); if (startProcessDataTimer) { diff --git a/src/Extensions/BCI/Actuators/gTec_SensorUI/UserControlBCISignalCheck.cs b/src/Extensions/BCI/Actuators/gTec_SensorUI/UserControlBCISignalCheck.cs index 6a82ceb6..d59965dd 100644 --- a/src/Extensions/BCI/Actuators/gTec_SensorUI/UserControlBCISignalCheck.cs +++ b/src/Extensions/BCI/Actuators/gTec_SensorUI/UserControlBCISignalCheck.cs @@ -318,9 +318,9 @@ public void updateSignalStatus(double[,] latestUnfilteredData, double[,] latestF public void initializeBCISignalCheck(DAQ_gTecBCI gtecbci, bool maxTimeHasElapsed, double maxTimeMins, double minElapsedPrevSignalQualityCheck, bool userPassedLastSignalQualityCheck) { gTecBCI = gtecbci; - Log.Debug(String.Format("initializeBCISignalCheck | maxTimeHasElapsed: {0}, " + - "minElapsedPrevSignalQualityCheck: {1}, userPassedLastSignalQualityCheck: {2}", - maxTimeHasElapsed.ToString(), minElapsedPrevSignalQualityCheck.ToString(), userPassedLastSignalQualityCheck.ToString())); + _logger?.LogDebug("initializeBCISignalCheck | maxTimeHasElapsed: {MaxTimeHasElapsed}, " + + "minElapsedPrevSignalQualityCheck: {MinElapsedPrevSignalQualityCheck}, userPassedLastSignalQualityCheck: {UserPassedLastSignalQualityCheck}", + maxTimeHasElapsed, minElapsedPrevSignalQualityCheck, userPassedLastSignalQualityCheck); // Get / inititalize variables related to board config used in data processing _indEegChannels = gTecBCI.indEegChannels; @@ -338,10 +338,10 @@ public void initializeBCISignalCheck(DAQ_gTecBCI gtecbci, bool maxTimeHasElapsed for (int i = 0; i < _indEegChannels.Length; i++) _indEegChannels_str += (_indEegChannels[i].ToString() + ", "); - Log.Debug(String.Format("initializeBCISignalCheck | _numChannels: {0}, " + "_samplingRate: {1}, " + - "_scaleIdx: {2}, _bufSize: {3}\n" + - "_indEegChannels_str: {4}", - _numChannels.ToString(), _samplingRate.ToString(), _scaleIdx.ToString(), _bufSize.ToString(), _indEegChannels_str)); + _logger?.LogDebug("initializeBCISignalCheck | _numChannels: {NumChannels}, " + "_samplingRate: {SamplingRate}, " + + "_scaleIdx: {ScaleIdx}, _bufSize: {BufSize}\n" + + "_indEegChannels_str: {IndEegChannelsStr}", + _numChannels, _samplingRate, _scaleIdx, _bufSize, _indEegChannels_str); // Set some text fields to smaller font size for 125 scaling (100 scaling is default) var tuple = DualMonitor.GetDisplayWidthAndScaling(); @@ -623,9 +623,9 @@ private static bool AppendDataToBuffer2(double[,] data, double[,] inBuffer, int result = true; } - catch (Exception e) + catch (Exception) { - _logger.LogError(e, "Exception in removeColumnsFromChan: {Message}", e.Message); + // Exception will propagate to calling method for proper logging } return result; } @@ -643,7 +643,7 @@ private void tabControlElectrodeQuality_SelectedIndexChanged(object sender, Even highlightSelectedTab(0); } - Log.Debug("tabControlElectrodeQuality_SelectedIndexChanged" + " | _currentBCISignalCheckMode: " + _currentBCISignalCheckMode.ToString()); + _logger?.LogDebug("tabControlElectrodeQuality_SelectedIndexChanged | _currentBCISignalCheckMode: {CurrentBCISignalCheckMode}", _currentBCISignalCheckMode); } /// @@ -696,7 +696,7 @@ private void GetGraphYLims(int scaleIdx, out int yLimMin, out int yLimMax) } catch (Exception e) { - Log.Exception(e.Message); + _logger?.LogError(e, "Exception in GetGraphYLims"); } yLimMax = scale; @@ -774,7 +774,7 @@ public void handle125Scaling() } catch (Exception ex) { - _logger.LogError(e, "Exception in ProcessDataSignalCheck: {Message}", e.Message); + _logger.LogError(ex, "Exception in ProcessDataSignalCheck: {Message}", ex.Message); } } } diff --git a/src/Extensions/BCI/Actuators/gTec_SensorUI/UserControlErrorBluetoothDisconnected.cs b/src/Extensions/BCI/Actuators/gTec_SensorUI/UserControlErrorBluetoothDisconnected.cs index ab0f015a..95a5282c 100644 --- a/src/Extensions/BCI/Actuators/gTec_SensorUI/UserControlErrorBluetoothDisconnected.cs +++ b/src/Extensions/BCI/Actuators/gTec_SensorUI/UserControlErrorBluetoothDisconnected.cs @@ -190,7 +190,7 @@ public void bluetoothResultHandler(DAQ_gTecBCI.BluetoothEvent bluetoothEvent, Di } catch (Exception ex) { - Log.Exception("UserControlErrorBluetoothDisconnected | bluetoothResultHandler | Exception: " + ex.Message); + _logger.LogError(ex, "UserControlErrorBluetoothDisconnected | bluetoothResultHandler | Exception"); } })); diff --git a/src/Extensions/BCI/Actuators/gTec_SensorUI/Utils.cs b/src/Extensions/BCI/Actuators/gTec_SensorUI/Utils.cs index db86bac5..3ed57db4 100644 --- a/src/Extensions/BCI/Actuators/gTec_SensorUI/Utils.cs +++ b/src/Extensions/BCI/Actuators/gTec_SensorUI/Utils.cs @@ -9,7 +9,7 @@ namespace ACAT.Extensions.BCI.Actuators.gTecSensorUI { internal class Utils { - private static readonly ILogger _logger = LoggerFactory.GetLogger(); + private static readonly ILogger _logger = LoggingConfiguration.CreateLogger(); internal static void HandleHelpNavigaion(WebBrowserNavigatingEventArgs e) { diff --git a/src/Extensions/BCI/Actuators/gTec_SensorUI/gTecDeviceTester.cs b/src/Extensions/BCI/Actuators/gTec_SensorUI/gTecDeviceTester.cs index 75d56ebd..600b1f58 100644 --- a/src/Extensions/BCI/Actuators/gTec_SensorUI/gTecDeviceTester.cs +++ b/src/Extensions/BCI/Actuators/gTec_SensorUI/gTecDeviceTester.cs @@ -173,7 +173,7 @@ public void initialize() _endSignalCheckTimer = false; // Create main form - _mainForm = new SensorForm(gTecBCI); + _mainForm = new SensorForm(gTecBCI, null); // Set handlers for main events if (_Testing_useSensor) @@ -459,7 +459,7 @@ private void buttonNextHandler(String buttonNextName) if (!userPassedLastSignalQualityCheck) { // Exit anyways regardless of signal quality result - Log.Debug("User did not pass signal quality check but set testing parameter to ignore result. Exiting as if user did pass the check"); + _logger.LogDebug("User did not pass signal quality check but set testing parameter to ignore result. Exiting as if user did pass the check"); } } @@ -494,7 +494,7 @@ private void buttonNextHandler(String buttonNextName) else { // Display message to user prompting them to improve signal quality before moving on - Log.Debug("Not exiting | Did not pass signal quality criteria"); + _logger.LogDebug("Not exiting | Did not pass signal quality criteria"); bool confirmed = ConfirmBoxOneOption.ShowDialog(StringResources.SignalQualityChecksFailed + "\n" + StringResources.Youneedtocompleteboth + "\n“ +Impedance” tests and get good signals to" + "\n" + "proceed" + "\n" + StringResources.Pleaserefertotheuserguideforhelp, "", StringResources.OK, _mainForm, false); @@ -512,7 +512,7 @@ private void buttonNextHandler(String buttonNextName) /// private void runSignalCheckIfRequired() { - Log.Debug("gTecDeviceTester | runSignalCheckIfRequired"); + _logger.LogDebug("gTecDeviceTester | runSignalCheckIfRequired"); // Always check time last impedance test was run (all electrodes tested) and update UI accordingly long timestampPrevImpedanceTest = BCIActuatorSettings.Settings.SignalQuality_TimeOfLastImpedanceCheck; @@ -523,8 +523,8 @@ private void runSignalCheckIfRequired() bool maxTimeHasElapsed = false; if (minElapsedPrevSignalQualityCheck >= maxTimeMins) maxTimeHasElapsed = true; - Log.Debug(String.Format("runSignalCheckIfRequired | timestampPrevImpedanceTest: {0}, timestampNow: {1}, secDiff: {2}", timestampPrevImpedanceTest.ToString(), timestampNow.ToString(), secDiff.ToString())); - Log.Debug(String.Format("minElapsedPrevSignalQualityCheck: {0}, maxTimeMins: {1}, maxTimeHasElapsed: {2}", minElapsedPrevSignalQualityCheck.ToString(), maxTimeMins.ToString(), maxTimeHasElapsed.ToString())); + _logger.LogDebug("runSignalCheckIfRequired | timestampPrevImpedanceTest: {TimestampPrevImpedanceTest}, timestampNow: {TimestampNow}, secDiff: {SecDiff}", timestampPrevImpedanceTest, timestampNow, secDiff); + _logger.LogDebug("minElapsedPrevSignalQualityCheck: {MinElapsedPrevSignalQualityCheck}, maxTimeMins: {MaxTimeMins}, maxTimeHasElapsed: {MaxTimeHasElapsed}", minElapsedPrevSignalQualityCheck, maxTimeMins, maxTimeHasElapsed); // Always check if user passed the last overall signal quality check that was executed // If max time has not passed, but user did not pass their most recent overall signal quality check, diff --git a/src/Extensions/BCI/Actuators/openBCI_SensorUI/OpenBCIDeviceTester.cs b/src/Extensions/BCI/Actuators/openBCI_SensorUI/OpenBCIDeviceTester.cs index 539e8e63..f7b1b1b0 100644 --- a/src/Extensions/BCI/Actuators/openBCI_SensorUI/OpenBCIDeviceTester.cs +++ b/src/Extensions/BCI/Actuators/openBCI_SensorUI/OpenBCIDeviceTester.cs @@ -33,7 +33,7 @@ namespace ACAT.Extensions.BCI.Actuators.openBCISensorUI /// public class OpenBCIDeviceTester { - private readonly ILogger _logger; + private readonly ILogger _logger = LogManager.GetLogger(); /// /// Variables representing all the different states in testing process (state machine) @@ -202,12 +202,12 @@ public OpenBCIDeviceTester() /// public void initialize() { - Log.Debug("OpenBCIDeviceTester | initialize"); + _logger.LogDebug("Initializing OpenBCIDeviceTester"); // Close main form if for some reason it's opened at this point if (_mainForm != null && _mainForm.IsDisposed == false) { - Log.Debug("OpenBCIDeviceTester | _mainForm != null && _mainForm.IsDisposed == false"); + _logger.LogDebug("Main form is open and not disposed, closing it"); _mainForm.Close(); _mainForm.Dispose(); } @@ -219,7 +219,7 @@ public void initialize() } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, "Exception during initialization"); } if (ExitOnboardingEarly) @@ -317,7 +317,7 @@ public void Exit(bool lostConnection) /// private void _mainForm_EvtFormClosed(object sender, FormClosedEventArgs e) { - Log.Debug("OpenBCIDeviceTester | _mainForm_EvtFormClosed | _deviceTestingState: " + _deviceTestingState.ToString()); + _logger.LogDebug("Main form closed with DeviceTestingState: {DeviceTestingState}", _deviceTestingState); if (_deviceTestingState == DeviceTestingState.ReceivedBCIError_LostDataConnection) { @@ -375,9 +375,10 @@ private void startSignalQualityTestingState(DeviceTestingState newDeviceTestingS bool maxTimeHasElapsed = false; if (minElapsedPrevSignalQualityCheck >= maxTimeMins) maxTimeHasElapsed = true; - Log.Debug(String.Format("startSignalQualityTestingState | newDeviceTestingState == DeviceTestingState.BCISignalCheckStartRequired" + - "\ntimestampPrevImpedanceTest: {0}, timestampNow: {1}, secDiff: {2}", timestampPrevImpedanceTest.ToString(), timestampNow.ToString(), secDiff.ToString())); - Log.Debug(String.Format("minElapsedPrevSignalQualityCheck: {0}, maxTimeMins: {1}, maxTimeHasElapsed: {2}", minElapsedPrevSignalQualityCheck.ToString(), maxTimeMins.ToString(), maxTimeHasElapsed.ToString())); + _logger.LogDebug("Signal quality test timing - PrevTest: {PrevTestTimestamp}, Now: {NowTimestamp}, SecDiff: {SecDiff}", + timestampPrevImpedanceTest, timestampNow, secDiff); + _logger.LogDebug("Signal quality elapsed check - MinElapsed: {MinElapsed}min, MaxTime: {MaxTime}min, HasElapsed: {HasElapsed}", + minElapsedPrevSignalQualityCheck, maxTimeMins, maxTimeHasElapsed); // Always check if user passed the last overall signal quality check that was executed // If max time has not passed, but user did not pass their most recent overall signal quality check, @@ -457,7 +458,7 @@ private void startSignalQualityTestingState(DeviceTestingState newDeviceTestingS /// private void finishSignalQualityTestingState(DeviceTestingState currentDeviceTestingState) { - Log.Debug("OpenBCIDeviceTester | finishSignalQualityTestingState | currentDeviceTestingState: " + currentDeviceTestingState.ToString()); + _logger.LogDebug("Finishing signal quality testing with state: {DeviceTestingState}", currentDeviceTestingState); // Next button selected from BCI signal check start required screen if (currentDeviceTestingState == DeviceTestingState.BCISignalCheckStartRequired) @@ -533,20 +534,20 @@ private void finishSignalQualityTestingState(DeviceTestingState currentDeviceTes bool userPassedLastSignalQualityCheck = BCIActuatorSettings.Settings.SignalQuality_PassedLastOverallQualityCheck; if (userPassedLastSignalQualityCheck) { - Log.Debug("User passed most recent signal quality check"); + _logger.LogDebug("User passed most recent signal quality check"); exitBCIOnboarding = true; } // Check if testing parameter set to ignore signal quality check result if (BCIActuatorSettings.Settings.Testing_IgnoreSignalTestResultDuringOnboarding) { - Log.Debug("BCIActuatorSettings.Testing_IgnoreSignalTestResultDuringOnboarding = true"); + _logger.LogDebug("Ignoring signal test result during onboarding (Testing_IgnoreSignalTestResultDuringOnboarding enabled)"); exitBCIOnboarding = true; if (!userPassedLastSignalQualityCheck) { // Exit anyways regardless of signal quality result - Log.Debug("User did not pass signal quality check but set testing parameter to ignore result. Exiting as if user did pass the check"); + _logger.LogDebug("User did not pass signal quality check but testing parameter is set to ignore - exiting anyway"); } } @@ -584,7 +585,7 @@ private void finishSignalQualityTestingState(DeviceTestingState currentDeviceTes else { // Display message to user prompting them to improve signal quality before moving on - Log.Debug("Not exiting | Did not pass signal quality criteria"); + _logger.LogDebug("Not exiting - user did not pass signal quality criteria"); _ = ConfirmBoxOneOption.ShowDialog("Signal Quality Checks Failed or Incomplete" + "\nYou need to complete both “Railing” and\n“Impedance” tests and get good signals to\nproceed" + "\nPlease refer to the user guide for help", "", StringResources.OK, _mainForm, false); @@ -617,7 +618,7 @@ private void _mainForm_EvtButtonRetestClicked(object sender) /// private void retestBCIConnections() { - Log.Debug("retestBCIConnections(). deviceTestingState: " + _deviceTestingState); + _logger.LogDebug("Retesting BCI connections with state: {DeviceTestingState}", _deviceTestingState); // If already on Optical sensor error screen -> retest button does not check all BCI connections from the beginning, tests optical sensor right away // _requestTestTriggerBox goes to correct user control when test completed @@ -666,7 +667,7 @@ private void _mainForm_EvtButtonExitClicked_DEBUG(object sender) try { _Testing_useSensor_TestIndex += 1; - Log.Debug("OpenBCIDeviceTester | _mainForm_EvtButtonExitClicked_DEBUG | _Testing_useSensor_TestIndex: " + _Testing_useSensor_TestIndex.ToString()); + _logger.LogDebug("DEBUG Exit button clicked, test index: {TestIndex}", _Testing_useSensor_TestIndex); if (_Testing_useSensor_TestIndex < _DebugStates.Length) { DeviceTestingState newState = _DebugStates[_Testing_useSensor_TestIndex]; @@ -698,7 +699,7 @@ private void _mainForm_EvtButtonExitClicked_DEBUG(object sender) } catch (Exception e) { - Log.Exception("_mainForm_EvtButtonExitClicked_DEBUG exception: " + e.ToString()); + _logger.LogError(e, "Exception in DEBUG exit button handler"); } } @@ -745,7 +746,7 @@ public async Task startBCIDeviceTesting(int initialDelaySec = 0) } } - Log.Debug("startBCIDeviceTesting | Calling InitDAQ()"); + _logger.LogDebug("Starting BCI device testing - calling InitDAQ()"); // Call async function which connects to BCI sensor + starts task that controls TriggerBox flashing and tests optical sensor by request if (_Testing_useSensor == true) @@ -790,7 +791,7 @@ private void changeTriggerBoxColor(Color color) } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, "Exception in changeTriggerBoxColor"); } } @@ -809,7 +810,7 @@ private void changeDeviceTestingState(DeviceTestingState state) } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, "Exception in changeDeviceTestingState"); } } @@ -820,7 +821,7 @@ private void changeDeviceTestingState(DeviceTestingState state) /// public async Task InitDAQ() // Original function { - Log.Debug("InitDAQ()"); + _logger.LogDebug("Initializing DAQ"); _initDAQTaskStopped = false; while (!_endTasks) @@ -834,31 +835,31 @@ public async Task InitDAQ() // Original function BaseDAQ.ExitCodes exitCode = ((DAQ_OpenBCI)_daqInstance).getUsbDongleConnected(); if (exitCode == BaseDAQ.ExitCodes.UNABLE_TO_OPEN_PORT_ERROR) { - Log.Debug("OpenBCIDeviceTester | _deviceTestingState = DeviceTestingState.ReceivedBCIError_UsbDongle"); + _logger.LogDebug("USB dongle connection error detected, state: ReceivedBCIError_UsbDongle"); _deviceTestingState = DeviceTestingState.ReceivedBCIError_UsbDongle; changeDeviceTestingState(DeviceTestingState.ReceivedBCIError_UsbDongle); } else { - Log.Debug("InitDAQ | exitCode: " + exitCode.ToString()); + _logger.LogDebug("InitDAQ exit code: {ExitCode}", exitCode); bool success = _daqInstance.Start(""); if (success) { - Log.Debug("DAQ_OpenBCI.Start() | true"); + _logger.LogDebug("DAQ_OpenBCI started successfully"); // Check latency setting of port is set correctly bool latencyPortOk = ((DAQ_OpenBCI)_daqInstance).CheckLatencyPort(); if (latencyPortOk) { - Log.Debug("DAQ_OpenBCI.CheckLatencyPort() | true"); + _logger.LogDebug("DAQ_OpenBCI latency port check passed"); if (_daqInstance.deviceInitialized) { - Log.Debug("DAQ_OpenBCI.deviceInitialized | true"); + _logger.LogDebug("DAQ_OpenBCI device initialized successfully"); // BCI impedence / railing integration - debugging option, go straight to signal check screens without checking optical sensor - Log.Debug("_Testing_BCIOnboardingIgnoreOpticalSensorChecks == true"); + _logger.LogDebug("Testing mode enabled - ignoring optical sensor checks during onboarding"); // Go to first stage of signal quality checking process startSignalQualityTestingState(DeviceTestingState.BCISignalCheckStartRequired); @@ -866,12 +867,12 @@ public async Task InitDAQ() // Original function } else { - Log.Debug("DAQ_OpenBCI.deviceInitialized | false"); + _logger.LogDebug("DAQ_OpenBCI device initialization failed"); } } else { - Log.Debug("DAQ_OpenBCI.CheckLatencyPort() | false | _deviceTestingState = DeviceTestingState.ReceivedBCIError_PortConfig"); + _logger.LogDebug("DAQ_OpenBCI latency port check failed, state: ReceivedBCIError_PortConfig"); _daqInstance.Stop(); _deviceTestingState = DeviceTestingState.ReceivedBCIError_PortConfig; changeDeviceTestingState(DeviceTestingState.ReceivedBCIError_PortConfig); @@ -879,7 +880,7 @@ public async Task InitDAQ() // Original function } else { - Log.Debug("OpenBCIDeviceTester | _deviceTestingState = DeviceTestingState.ReceivedBCIError_CytonBoard"); + _logger.LogDebug("Cyton board connection error detected, state: ReceivedBCIError_CytonBoard"); _deviceTestingState = DeviceTestingState.ReceivedBCIError_CytonBoard; changeDeviceTestingState(DeviceTestingState.ReceivedBCIError_CytonBoard); } @@ -890,7 +891,7 @@ public async Task InitDAQ() // Original function } _initDAQTaskStopped = true; - Log.Debug("InitDAQ | hole | _initDAQ_TaskStopped = true"); + _logger.LogDebug("InitDAQ task stopped"); // return; } diff --git a/src/Extensions/BCI/Actuators/openBCI_SensorUI/SensorForm.cs b/src/Extensions/BCI/Actuators/openBCI_SensorUI/SensorForm.cs index a67084fe..3ea87f13 100644 --- a/src/Extensions/BCI/Actuators/openBCI_SensorUI/SensorForm.cs +++ b/src/Extensions/BCI/Actuators/openBCI_SensorUI/SensorForm.cs @@ -20,6 +20,7 @@ using System.Windows.Forms; using static ACAT.Extensions.BCI.Actuators.openBCISensorUI.OpenBCIDeviceTester; using static ACAT.Extensions.BCI.Actuators.openBCISensorUI.UserControlBCISignalCheck; +using Microsoft.Extensions.Logging; namespace ACAT.Extensions.BCI.Actuators.openBCISensorUI { @@ -28,6 +29,8 @@ namespace ACAT.Extensions.BCI.Actuators.openBCISensorUI /// public partial class SensorForm : Form { + private static ILogger _logger => LogManager.GetLogger(); + /// /// User control displayed while trying to connect to sensor /// @@ -210,7 +213,7 @@ public SensorForm(DeviceTestingState initialState) /// public void changeDeviceTestingState(DeviceTestingState state) { - Log.Debug("SensorForm | changeDeviceTestingState | state: " + state.ToString()); + _logger?.LogDebug("SensorForm | changeDeviceTestingState | state: {State}", state); DeviceTestingState prevDeviceTestingState = _mainFormDeviceTestingState; UserControl newUserControl = null; @@ -339,8 +342,8 @@ public void changeDeviceTestingState(DeviceTestingState state) /// private void startStopProcessDataTimer(bool startProcessDataTimer, DeviceTestingState state) { - Log.Debug("startStopProcessDataTimer | startProcessDataTimer: " + startProcessDataTimer.ToString() + - " | state: " + state.ToString()); + _logger?.LogDebug("startStopProcessDataTimer | startProcessDataTimer: {StartTimer} | state: {State}", + startProcessDataTimer, state); if (startProcessDataTimer) { @@ -367,11 +370,11 @@ private void startStopProcessDataTimer(bool startProcessDataTimer, DeviceTesting } timerProcessData.Start(); - Log.Debug("startStopProcessDataTimer | Started timerProcessData"); + _logger?.LogDebug("startStopProcessDataTimer | Started timerProcessData"); } catch (Exception e) { - Log.Exception("startStopProcessDataTimer | Exception: " + e.ToString()); + _logger?.LogError(e, "startStopProcessDataTimer | Exception"); } } else @@ -388,7 +391,7 @@ private void startStopProcessDataTimer(bool startProcessDataTimer, DeviceTesting } catch (Exception e) { - Log.Exception("startStopProcessDataTimer | Exception: " + e.ToString()); + _logger?.LogError(e, "startStopProcessDataTimer | Exception"); } } } @@ -430,7 +433,7 @@ private void ProcessDataSignalCheck_Tick(object sender, EventArgs e) // Check flag to stop this particular timer if (_stopTimers || OpenBCIDeviceTester._endSignalCheckTimer) { - Log.Debug("ProcessDataSignalCheck_Tick | _stopTimers | OpenBCIDeviceTester._endSignalCheckTimer"); + _logger?.LogDebug("ProcessDataSignalCheck_Tick | _stopTimers | OpenBCIDeviceTester._endSignalCheckTimer"); startStopProcessDataTimer(false, DeviceTestingState.ExitBCITesting); return; } @@ -465,7 +468,7 @@ private void Handle_FormCLosing(object sender, FormClosingEventArgs e) // Only exit if ExitOnboardingEarly flag has been set (user selected Exit button) if (!ExitOnboardingEarly) { - Log.Debug("User has requested to close form (Alt + F4) - ignore"); + _logger?.LogDebug("User has requested to close form (Alt + F4) - ignore"); e.Cancel = true; closeReasonIsUserClosing = true; } @@ -543,7 +546,7 @@ private void buttonRetest_Click(object sender, EventArgs e) /// private void modifyUserControlsForDebugMode() { - Log.Debug("SensorForm | modifyUserControlsForDebugMode"); + _logger?.LogDebug("SensorForm | modifyUserControlsForDebugMode"); _userControlTestBCIConnections.buttonExit.AutoSize = true; _userControlTestBCIConnections.buttonExit.Font = new Font("Montserrat Medium", 13F); diff --git a/src/Extensions/BCI/Actuators/openBCI_SensorUI/UserControlBCIErrorCytonBoard.cs b/src/Extensions/BCI/Actuators/openBCI_SensorUI/UserControlBCIErrorCytonBoard.cs index 2f108960..e7913979 100644 --- a/src/Extensions/BCI/Actuators/openBCI_SensorUI/UserControlBCIErrorCytonBoard.cs +++ b/src/Extensions/BCI/Actuators/openBCI_SensorUI/UserControlBCIErrorCytonBoard.cs @@ -69,7 +69,7 @@ private void WebBrowserDesc_DocumentCompleted(object sender, WebBrowserDocumentC private void WebBrowserDesc_Navigating(object sender, WebBrowserNavigatingEventArgs e) { - Utils.HandleHelpNavigaion(e); + Utils.HandleHelpNavigation(e); } } } \ No newline at end of file diff --git a/src/Extensions/BCI/Actuators/openBCI_SensorUI/UserControlBCIErrorOpticalSensor.cs b/src/Extensions/BCI/Actuators/openBCI_SensorUI/UserControlBCIErrorOpticalSensor.cs index 08dc6c4f..d83c2043 100644 --- a/src/Extensions/BCI/Actuators/openBCI_SensorUI/UserControlBCIErrorOpticalSensor.cs +++ b/src/Extensions/BCI/Actuators/openBCI_SensorUI/UserControlBCIErrorOpticalSensor.cs @@ -62,7 +62,7 @@ public partial class UserControlBCIErrorOpticalSensor : UserControl /// public UserControlBCIErrorOpticalSensor(String stepId, ILogger logger = null) { - _logger = logger ?? LoggerFactory.GetLogger(); + _logger = logger ?? LoggingConfiguration.CreateLogger(); InitializeComponent(); _stepId = stepId; @@ -116,7 +116,7 @@ private void WebBrowserDesc_DocumentCompleted(object sender, WebBrowserDocumentC private void WebBrowserDesc_Navigating(object sender, WebBrowserNavigatingEventArgs e) { - Utils.HandleHelpNavigaion(e); + Utils.HandleHelpNavigation(e); } //// diff --git a/src/Extensions/BCI/Actuators/openBCI_SensorUI/UserControlBCIErrorOpticalSensorDetect.cs b/src/Extensions/BCI/Actuators/openBCI_SensorUI/UserControlBCIErrorOpticalSensorDetect.cs index 9606e688..19558a48 100644 --- a/src/Extensions/BCI/Actuators/openBCI_SensorUI/UserControlBCIErrorOpticalSensorDetect.cs +++ b/src/Extensions/BCI/Actuators/openBCI_SensorUI/UserControlBCIErrorOpticalSensorDetect.cs @@ -69,7 +69,7 @@ private void WebBrowserDesc_DocumentCompleted(object sender, WebBrowserDocumentC private void WebBrowserDesc_Navigating(object sender, WebBrowserNavigatingEventArgs e) { - Utils.HandleHelpNavigaion(e); + Utils.HandleHelpNavigation(e); } } } \ No newline at end of file diff --git a/src/Extensions/BCI/Actuators/openBCI_SensorUI/UserControlBCIErrorPortConfig.cs b/src/Extensions/BCI/Actuators/openBCI_SensorUI/UserControlBCIErrorPortConfig.cs index c398a14d..08205e4e 100644 --- a/src/Extensions/BCI/Actuators/openBCI_SensorUI/UserControlBCIErrorPortConfig.cs +++ b/src/Extensions/BCI/Actuators/openBCI_SensorUI/UserControlBCIErrorPortConfig.cs @@ -78,7 +78,7 @@ private void WebBrowserDesc_DocumentCompleted(object sender, WebBrowserDocumentC private void WebBrowserDesc_Navigating(object sender, WebBrowserNavigatingEventArgs e) { - Utils.HandleHelpNavigaion(e); + Utils.HandleHelpNavigation(e); } } } \ No newline at end of file diff --git a/src/Extensions/BCI/Actuators/openBCI_SensorUI/UserControlBCIErrorUsbDongle.cs b/src/Extensions/BCI/Actuators/openBCI_SensorUI/UserControlBCIErrorUsbDongle.cs index d7dd5058..8d20f3e7 100644 --- a/src/Extensions/BCI/Actuators/openBCI_SensorUI/UserControlBCIErrorUsbDongle.cs +++ b/src/Extensions/BCI/Actuators/openBCI_SensorUI/UserControlBCIErrorUsbDongle.cs @@ -56,7 +56,7 @@ private void WebBrowserDesc_DocumentCompleted(object sender, WebBrowserDocumentC private void WebBrowserDesc_Navigating(object sender, WebBrowserNavigatingEventArgs e) { - Utils.HandleHelpNavigaion(e); + Utils.HandleHelpNavigation(e); } } } \ No newline at end of file diff --git a/src/Extensions/BCI/Actuators/openBCI_SensorUI/UserControlBCISignalCheck.cs b/src/Extensions/BCI/Actuators/openBCI_SensorUI/UserControlBCISignalCheck.cs index 3bf3f971..ea256d9c 100644 --- a/src/Extensions/BCI/Actuators/openBCI_SensorUI/UserControlBCISignalCheck.cs +++ b/src/Extensions/BCI/Actuators/openBCI_SensorUI/UserControlBCISignalCheck.cs @@ -23,6 +23,7 @@ using ACAT.Extensions.BCI.Common.BCIControl; using Accord.Math; using brainflow; +using Microsoft.Extensions.Logging; //using SharpDX.Direct2D1; using System; using System.Collections.Generic; @@ -39,6 +40,11 @@ namespace ACAT.Extensions.BCI.Actuators.openBCISensorUI /// public partial class UserControlBCISignalCheck : UserControl { + /// + /// Logger instance for this class + /// + private readonly ILogger _logger; + /// /// The DAQ instance for OpenBCI /// @@ -278,6 +284,9 @@ public UserControlBCISignalCheck(String stepId) { InitializeComponent(); + // Initialize logger + _logger = LoggingConfiguration.CreateLogger(); + // Initialize the DAQ instance _daqInstance = DAQFactory.CreateDAQ(DAQDeviceType.OpenBCI); @@ -614,7 +623,7 @@ public void changeSignalCheckMode(BCISignalCheckMode mode) } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, ex.Message); } } @@ -627,7 +636,7 @@ public void changeSignalCheckMode(BCISignalCheckMode mode) public void initializeBCISignalCheck(bool maxTimeHasElapsed, double maxTimeMins, double minElapsedPrevSignalQualityCheck, bool userPassedLastSignalQualityCheck) { - Log.Debug(String.Format("initializeBCISignalCheck | maxTimeHasElapsed: {0}, " + + _logger.LogDebug(String.Format("initializeBCISignalCheck | maxTimeHasElapsed: {0}, " + "minElapsedPrevSignalQualityCheck: {1}, userPassedLastSignalQualityCheck: {2}", maxTimeHasElapsed.ToString(), minElapsedPrevSignalQualityCheck.ToString(), userPassedLastSignalQualityCheck.ToString())); @@ -669,7 +678,7 @@ public void initializeBCISignalCheck(bool maxTimeHasElapsed, double maxTimeMins, for (int i = 0; i < _indEegChannels.Length; i++) _indEegChannels_str += (_indEegChannels[i].ToString() + ", "); - Log.Debug(String.Format("initializeBCISignalCheck | _numChannels: {0}, " + "_samplingRate: {1}, " + + _logger.LogDebug(String.Format("initializeBCISignalCheck | _numChannels: {0}, " + "_samplingRate: {1}, " + "_scaleIdx: {2}, _bufSize: {3}\n" + "_indEegChannels_str: {4}", _numChannels.ToString(), _samplingRate.ToString(), _scaleIdx.ToString(), _bufSize.ToString(), _indEegChannels_str)); @@ -845,7 +854,7 @@ public void initializeBCISignalCheck(bool maxTimeHasElapsed, double maxTimeMins, //private async Task StartImpedanceTesting() private void StartImpedanceTesting() { - Log.Debug("StartImpedanceTesting"); + _logger.LogDebug("StartImpedanceTesting"); if (!_runImpedanceTestingCycle && _daqInstance.deviceInitialized) { @@ -855,7 +864,7 @@ private void StartImpedanceTesting() ////// Before running impedance tests /////// //// Stop streaming on board, does not consistently register commands while streaming - Log.Debug("Stop streaming"); + _logger.LogDebug("Stop streaming"); ((DAQ_OpenBCI)_daqInstance).Stop_Streaming(); Thread.Sleep(50); @@ -866,7 +875,7 @@ private void StartImpedanceTesting() EEGChannel currentEegChannel = _eegChannels[_currentImpedanceTestElectrodeIndex]; String electrodeName = currentEegChannel._electrodeName; - Log.Debug("StartImpedanceTesting loop | _currentImpedanceTestElectrodeIndex: " + _currentImpedanceTestElectrodeIndex.ToString() + + _logger.LogDebug("StartImpedanceTesting loop | _currentImpedanceTestElectrodeIndex: " + _currentImpedanceTestElectrodeIndex.ToString() + " | electrodeName: " + electrodeName.ToString()); String cmdStartElectrodeImpedanceTest = currentEegChannel.ImpedanceTestingEnableCmd; @@ -884,7 +893,7 @@ private void StartImpedanceTesting() _daqInstance.GetData(); // Clear buffer //// Send enable electrode Impedance testing commands - Log.Debug(String.Format("Sending enable electrode {0} Impedance testing command: {1}", electrodeName, cmdStartElectrodeImpedanceTest)); + _logger.LogDebug(String.Format("Sending enable electrode {0} Impedance testing command: {1}", electrodeName, cmdStartElectrodeImpedanceTest)); ((DAQ_OpenBCI)_daqInstance).Config_Board(cmdStartElectrodeImpedanceTest); Thread.Sleep(750); @@ -892,7 +901,7 @@ private void StartImpedanceTesting() _daqInstance.deviceInitialized = true; //// Send start streaming - Log.Debug("Start streaming"); + _logger.LogDebug("Start streaming"); ((DAQ_OpenBCI)_daqInstance).Start_Streaming(); Thread.Sleep(50); @@ -910,15 +919,15 @@ private void StartImpedanceTesting() _daqInstance.deviceInitialized = false; //// Stop streaming - Log.Debug("Stop streaming"); + _logger.LogDebug("Stop streaming"); ((DAQ_OpenBCI)_daqInstance).Stop_Streaming(); Thread.Sleep(50); // Send command to disable impedance testing for specific electrode - Log.Debug(String.Format("Sending disable electrode {0} impedance testing command: {1}", electrodeName, cmdEndElectrodeImpedanceTest)); + _logger.LogDebug(String.Format("Sending disable electrode {0} impedance testing command: {1}", electrodeName, cmdEndElectrodeImpedanceTest)); ((DAQ_OpenBCI)_daqInstance).Config_Board(cmdEndElectrodeImpedanceTest); Thread.Sleep(750); - Log.Debug("Completed impedance testing electrode: " + _currentImpedanceTestElectrodeIndex.ToString()); + _logger.LogDebug("Completed impedance testing electrode: " + _currentImpedanceTestElectrodeIndex.ToString()); // Reset back color of impedance result button in Impedance testing page to transparent Invoke(new Action(() => @@ -933,7 +942,7 @@ private void StartImpedanceTesting() _currentImpedanceTestElectrodeIndex = 0; if (BCIActuatorSettings.Settings.SignalQuality_StopImpedanceTestAfterOneCycle) { - Log.Debug("SignalQuality_StopImpedanceTestAfterOneCycle = true | Stopping impedance testing"); + _logger.LogDebug("SignalQuality_StopImpedanceTestAfterOneCycle = true | Stopping impedance testing"); try { Invoke(new Action(() => @@ -948,7 +957,7 @@ private void StartImpedanceTesting() } catch (Exception ex) { - Log.Exception(ex.Message); + _logger.LogError(ex, ex.Message); } } } @@ -958,18 +967,18 @@ private void StartImpedanceTesting() //// Do opposite of what was done at the beginning on this function to bring board back to default state // Reset board to default parameters - Log.Debug("Send command to reset board"); + _logger.LogDebug("Send command to reset board"); ((DAQ_OpenBCI)_daqInstance).Reset_Board(); // Run multiple times? Thread.Sleep(750); // Tested 750 - is ok - Log.Debug("Send command to reset board"); + _logger.LogDebug("Send command to reset board"); ((DAQ_OpenBCI)_daqInstance).Reset_Board(); Thread.Sleep(4500); - Log.Debug("Calling Stop()"); + _logger.LogDebug("Calling Stop()"); _daqInstance.Stop(); Thread.Sleep(250); // Tested 250 - is ok - Log.Debug("Calling Start()"); + _logger.LogDebug("Calling Start()"); _daqInstance.Start(); // Also starts streaming // Stopped Impedance testing cycle, update UI accordingly @@ -990,7 +999,7 @@ private void StartImpedanceTesting() // save this time as time of last signal quality check completed if (_AllElectrodesOverallSignalQualityResult.allElectrodesUpdatedWithinSession == true) { - Log.Debug("Saving current time as SignalQuality_TimeOfLastImpedanceCheck"); + _logger.LogDebug("Saving current time as SignalQuality_TimeOfLastImpedanceCheck"); BCIActuatorSettings.Settings.SignalQuality_TimeOfLastImpedanceCheck = DateTimeOffset.Now.ToUnixTimeSeconds(); BCIActuatorSettings.Save(); // Save settings } @@ -1029,7 +1038,7 @@ public void ProcessDataSignalCheck(double[,] data, double[,] filteredData) } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, ex.Message); } // Removed automatic optical sensor checks below for now - it's likely the optical sensor is still @@ -1100,7 +1109,7 @@ private void updateRailingTestResult(int chIdx, int railingResultPercentage, boo } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, ex.Message); } } @@ -1161,7 +1170,7 @@ private void updateImpedanceResult(int chIdx, int impedanceResult, bool update_u } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, ex.Message); } } @@ -1213,7 +1222,7 @@ public bool updateSignalQualityResult(int chIdx) } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, ex.Message); } return ret; @@ -1260,7 +1269,7 @@ private void updateSignalChart(int channelIndex, double[] samples, bool scale_pl } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, ex.Message); } } @@ -1294,9 +1303,9 @@ private static bool AppendDataToBuffer2(double[,] data, double[,] inBuffer, int result = true; } - catch (Exception e) + catch (Exception) { - Log.Exception(e.Message); + // Exception will propagate to calling method for proper logging } return result; } @@ -1339,7 +1348,7 @@ private void tabControlElectrodeQuality_SelectedIndexChanged(object sender, Even } } - Log.Debug("tabControlElectrodeQuality_SelectedIndexChanged" + + _logger.LogDebug("tabControlElectrodeQuality_SelectedIndexChanged" + " | _impedanceTestingRunning: " + _impedanceTestingRunning.ToString() + " | _currentBCISignalCheckMode: " + _currentBCISignalCheckMode.ToString()); } @@ -1375,7 +1384,7 @@ private void highlightSelectedTab(int tabControlIndex) } catch (Exception e) { - Log.Exception(e.Message); + _logger.LogError(e, e.Message); } } @@ -1420,7 +1429,7 @@ private void GetGraphYLimits(int scaleIdx, out int yLimMin, out int yLimMax) } catch (Exception e) { - Log.Exception(e.Message); + _logger.LogError(e, e.Message); } yLimMax = scale; @@ -1434,13 +1443,13 @@ private void GetGraphYLimits(int scaleIdx, out int yLimMin, out int yLimMax) /// private void buttonTestImpedance_Click(object sender, EventArgs e) { - Log.Debug("buttonTestImpedance_Click | _currentImpedanceTestElectrodeIndex: " + _currentImpedanceTestElectrodeIndex.ToString()); + _logger.LogDebug("buttonTestImpedance_Click | _currentImpedanceTestElectrodeIndex: " + _currentImpedanceTestElectrodeIndex.ToString()); if (_runImpedanceTestingCycle) { try { - Log.Debug("Impedance cyclical testing running. Stopping process..."); + _logger.LogDebug("Impedance cyclical testing running. Stopping process..."); buttonTestImpedance.Enabled = false; buttonTestImpedance.BackColor = Color.Gray; updateImpedanceTestingStateLabels(ImpedanceTestingState.STOP_IN_PROGRESS); @@ -1450,7 +1459,7 @@ private void buttonTestImpedance_Click(object sender, EventArgs e) } catch (Exception ex) { - Log.Exception(ex.Message); + _logger.LogError(ex, ex.Message); } } else if (!_runImpedanceTestingCycle) @@ -1458,7 +1467,7 @@ private void buttonTestImpedance_Click(object sender, EventArgs e) // Start impedance testing try { - Log.Debug("Impedances testing not running. Starting process..."); + _logger.LogDebug("Impedances testing not running. Starting process..."); buttonTestImpedance.Text = "Stop"; buttonNext.Enabled = false; buttonNext.BackColor = Color.Gray; @@ -1468,7 +1477,7 @@ private void buttonTestImpedance_Click(object sender, EventArgs e) } catch (Exception ex) { - Log.Exception(ex.Message); + _logger.LogError(ex, ex.Message); } // Start thread doing impedance testing @@ -1566,7 +1575,7 @@ private void updateImpedanceTestingStateLabels(ImpedanceTestingState impedanceTe } catch (Exception ex) { - Log.Exception(ex.Message); + _logger.LogError(ex, ex.Message); } } @@ -1607,7 +1616,7 @@ private void WebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompl private void WebBrowserDesc_Navigating(object sender, WebBrowserNavigatingEventArgs e) { - Utils.HandleHelpNavigaion(e); + Utils.HandleHelpNavigation(e); } /// @@ -1641,7 +1650,7 @@ public void handle125Scaling() } catch (Exception ex) { - Log.Exception(ex.Message); + _logger.LogError(ex, ex.Message); } } } diff --git a/src/Extensions/BCI/Actuators/openBCI_SensorUI/Utils.cs b/src/Extensions/BCI/Actuators/openBCI_SensorUI/Utils.cs index 9ab1872a..cb9484cd 100644 --- a/src/Extensions/BCI/Actuators/openBCI_SensorUI/Utils.cs +++ b/src/Extensions/BCI/Actuators/openBCI_SensorUI/Utils.cs @@ -9,9 +9,9 @@ namespace ACAT.Extensions.BCI.Actuators.openBCISensorUI { internal class Utils { - private static readonly ILogger _logger = LoggerFactory.GetLogger(); + private static readonly ILogger _logger = LoggingConfiguration.CreateLogger(); - internal static void HandleHelpNavigaion(WebBrowserNavigatingEventArgs e) + internal static void HandleHelpNavigation(WebBrowserNavigatingEventArgs e) { var str = e.Url.ToString(); diff --git a/src/Extensions/BCI/Common/AnimationSharp/AnimationSharpManagerV2.cs b/src/Extensions/BCI/Common/AnimationSharp/AnimationSharpManagerV2.cs index d703bedc..1323ecae 100644 --- a/src/Extensions/BCI/Common/AnimationSharp/AnimationSharpManagerV2.cs +++ b/src/Extensions/BCI/Common/AnimationSharp/AnimationSharpManagerV2.cs @@ -41,7 +41,7 @@ namespace ACAT.Extensions.BCI.Common.AnimationSharp /// public class AnimationSharpManagerV2 { - private readonly ILogger _logger; + private readonly ILogger _logger = LogManager.GetLogger(); /// /// Current active Keyboard Layout /// diff --git a/src/Extensions/BCI/Common/AnimationSharp/Utility/AnimationManagerUtils.cs b/src/Extensions/BCI/Common/AnimationSharp/Utility/AnimationManagerUtils.cs index 139c08b4..cacd0fbe 100644 --- a/src/Extensions/BCI/Common/AnimationSharp/Utility/AnimationManagerUtils.cs +++ b/src/Extensions/BCI/Common/AnimationSharp/Utility/AnimationManagerUtils.cs @@ -27,7 +27,7 @@ namespace ACAT.Extensions.BCI.Common.AnimationSharp.Utility /// public class AnimationManagerUtils { - private static readonly ILogger _logger = LoggerFactory.GetLogger(); + private static readonly ILogger _logger = LoggingConfiguration.CreateLogger(); /// /// String messages for BCI /// diff --git a/src/Extensions/BCI/Common/AnimationSharp/Utility/BCIUtils.cs b/src/Extensions/BCI/Common/AnimationSharp/Utility/BCIUtils.cs index 8d3379ca..92db816e 100644 --- a/src/Extensions/BCI/Common/AnimationSharp/Utility/BCIUtils.cs +++ b/src/Extensions/BCI/Common/AnimationSharp/Utility/BCIUtils.cs @@ -18,11 +18,10 @@ 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(); + _logger = logger ?? LoggingConfiguration.CreateLogger(); } /// diff --git a/src/Extensions/BCI/Common/AnimationSharp/Utility/CachedLogBCI.cs b/src/Extensions/BCI/Common/AnimationSharp/Utility/CachedLogBCI.cs index 56bd830a..32fa6ef2 100644 --- a/src/Extensions/BCI/Common/AnimationSharp/Utility/CachedLogBCI.cs +++ b/src/Extensions/BCI/Common/AnimationSharp/Utility/CachedLogBCI.cs @@ -39,7 +39,7 @@ public class CachedLogBCI public CachedLogBCI(string baseFileName, string baseDirPath = null, ILogger logger = null) { - _logger = logger ?? LoggerFactory.GetLogger(); + _logger = logger ?? LoggingConfiguration.CreateLogger(); if (!string.IsNullOrEmpty(baseFileName)) { LogFileName = baseFileName + ".csv"; diff --git a/src/Extensions/BCI/Common/AnimationSharp/Utility/SharpDXUtils.cs b/src/Extensions/BCI/Common/AnimationSharp/Utility/SharpDXUtils.cs index 7ed4ff2f..b4af1cb9 100644 --- a/src/Extensions/BCI/Common/AnimationSharp/Utility/SharpDXUtils.cs +++ b/src/Extensions/BCI/Common/AnimationSharp/Utility/SharpDXUtils.cs @@ -24,7 +24,7 @@ namespace ACAT.Extensions.BCI.Common.AnimationSharp.Utility { public class SharpDXUtils { - private static readonly ILogger _logger = LoggerFactory.GetLogger(); + private static readonly ILogger _logger = LoggingConfiguration.CreateLogger(); /// /// Get the border color from the Theme xml file /// diff --git a/src/Extensions/BCI/Common/BCIInterfaceUtilities/CalibrationEyesForm.cs b/src/Extensions/BCI/Common/BCIInterfaceUtilities/CalibrationEyesForm.cs index 68dee729..e145438f 100644 --- a/src/Extensions/BCI/Common/BCIInterfaceUtilities/CalibrationEyesForm.cs +++ b/src/Extensions/BCI/Common/BCIInterfaceUtilities/CalibrationEyesForm.cs @@ -309,7 +309,7 @@ private void SetEnableStateButtons(bool enable) /// private void ShowCalibrationEyesSettingsForm() { - CalibrationEyesSettingsForm calibrationEyesSettingsForm = new(); + CalibrationEyesSettingsForm calibrationEyesSettingsForm = new(null); calibrationEyesSettingsForm.ShowDialog(); var parameters = calibrationEyesSettingsForm.ResultParameters; calibrationEyesSettingsForm.Dispose(); diff --git a/src/Extensions/BCI/Common/BCIInterfaceUtilities/CalibrationEyesSettingsForm.cs b/src/Extensions/BCI/Common/BCIInterfaceUtilities/CalibrationEyesSettingsForm.cs index fd8b6127..84f9aa27 100644 --- a/src/Extensions/BCI/Common/BCIInterfaceUtilities/CalibrationEyesSettingsForm.cs +++ b/src/Extensions/BCI/Common/BCIInterfaceUtilities/CalibrationEyesSettingsForm.cs @@ -79,7 +79,7 @@ public CalibrationEyesSettingsForm(ILogger logger) public static ResultParams ShowDialog(string label, Form parent = null, bool setTopMost = false) { - var confirmBox = new CalibrationEyesSettingsForm(); + var confirmBox = new CalibrationEyesSettingsForm(null); confirmBox.ShowDialog(parent); ResultParams retVal = confirmBox.ResultParameters; confirmBox.Dispose(); diff --git a/src/Extensions/BCI/Common/BCIInterfaceUtilities/ConfirmBoxCalibrationModes.cs b/src/Extensions/BCI/Common/BCIInterfaceUtilities/ConfirmBoxCalibrationModes.cs index 6f913e18..d62582c6 100644 --- a/src/Extensions/BCI/Common/BCIInterfaceUtilities/ConfirmBoxCalibrationModes.cs +++ b/src/Extensions/BCI/Common/BCIInterfaceUtilities/ConfirmBoxCalibrationModes.cs @@ -92,7 +92,7 @@ public ConfirmBoxCalibrationModes(ILogger logger) public static Tuple ShowDialog(BCICalibrationStatus actuatorResponse, bool enableBeginBtn, Form parent = null, bool setTopMost = false) { - var confirmBox = new ConfirmBoxCalibrationModes(); + var confirmBox = new ConfirmBoxCalibrationModes(null); //To always display the form in the main screen confirmBox.StartPosition = FormStartPosition.Manual; confirmBox.Location = confirmBox.primaryScreen.WorkingArea.Location; diff --git a/src/Extensions/BCI/Common/BCIInterfaceUtilities/ConfirmBoxTriggerBoxSettings.cs b/src/Extensions/BCI/Common/BCIInterfaceUtilities/ConfirmBoxTriggerBoxSettings.cs index ea79754b..dee4b22e 100644 --- a/src/Extensions/BCI/Common/BCIInterfaceUtilities/ConfirmBoxTriggerBoxSettings.cs +++ b/src/Extensions/BCI/Common/BCIInterfaceUtilities/ConfirmBoxTriggerBoxSettings.cs @@ -60,7 +60,7 @@ public partial class ConfirmBoxTriggerBoxSettings : Form /// public ConfirmBoxTriggerBoxSettings(ILogger logger = null) { - _logger = logger ?? LoggerFactory.GetLogger(); + _logger = logger ?? LoggingConfiguration.CreateLogger(); InitializeComponent(); label1.Text = StringResources.CalibrationIsEssential; Load += ConfirmBox_Load; diff --git a/src/Extensions/BCI/Common/BCIInterfaceUtilities/OtherTestForm.cs b/src/Extensions/BCI/Common/BCIInterfaceUtilities/OtherTestForm.cs index cb0fcf88..7e8e0393 100644 --- a/src/Extensions/BCI/Common/BCIInterfaceUtilities/OtherTestForm.cs +++ b/src/Extensions/BCI/Common/BCIInterfaceUtilities/OtherTestForm.cs @@ -41,7 +41,7 @@ public partial class OtherTestForm : Form /// public OtherTestForm(ILogger logger = null) { - _logger = logger ?? LoggerFactory.GetLogger(); + _logger = logger ?? LoggingConfiguration.CreateLogger(); InitializeComponent(); Load += ConfirmBox_Load; } diff --git a/src/Extensions/BCI/Common/BCIInterfaceUtilities/RemapCalibrationForm.cs b/src/Extensions/BCI/Common/BCIInterfaceUtilities/RemapCalibrationForm.cs index 6dfd39ad..a343512b 100644 --- a/src/Extensions/BCI/Common/BCIInterfaceUtilities/RemapCalibrationForm.cs +++ b/src/Extensions/BCI/Common/BCIInterfaceUtilities/RemapCalibrationForm.cs @@ -74,7 +74,7 @@ public RemapCalibrationForm(ILogger logger) public static bool ShowFormDialog(Form parent = null, bool setTopMost = false) { - var confirmBox = new RemapCalibrationForm(); + var confirmBox = new RemapCalibrationForm(null); //To always display the form in the main screen confirmBox.StartPosition = FormStartPosition.Manual; confirmBox.Location = confirmBox.primaryScreen.WorkingArea.Location; diff --git a/src/Extensions/Default/Actuators/CameraActuator/AutoCalibrateForm.cs b/src/Extensions/Default/Actuators/CameraActuator/AutoCalibrateForm.cs index 01be5ae6..efb679a2 100644 --- a/src/Extensions/Default/Actuators/CameraActuator/AutoCalibrateForm.cs +++ b/src/Extensions/Default/Actuators/CameraActuator/AutoCalibrateForm.cs @@ -13,6 +13,7 @@ using ACAT.Core.PanelManagement.Utils; using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Windows.Forms; @@ -20,6 +21,7 @@ namespace ACAT.Extensions.Actuators.CameraActuator { internal partial class AutoCalibrateForm : Form { + private static readonly ILogger _logger = LoggingConfiguration.CreateLogger(); private VideoWindowFinder _videoWindowFinder; private readonly CameraActuator _visionActuator; @@ -63,7 +65,7 @@ private void AutoCalibrateForm_Resize(object sender, EventArgs e) private void AutoCalibrateForm_Shown(object sender, EventArgs e) { - _videoWindowFinder = new VideoWindowFinder(); + _videoWindowFinder = new VideoWindowFinder(null); _videoWindowFinder.EvtVideoWindowDisplayed += _videoWindowFinder_EvtVideoWindowDisplayed; _videoWindowFinder.Start(); } @@ -92,11 +94,11 @@ private void EndCalibration() _videoWindowFinder.Dispose(); } - Log.Debug("Hiding video window"); + _logger.LogDebug("Hiding video window"); CameraSensor.hideVideoWindow(); - Log.Debug("Closing calibform"); + _logger.LogDebug("Closing calibform"); Windows.CloseForm(this); } diff --git a/src/Extensions/Default/Actuators/CameraActuator/CameraActuator.cs b/src/Extensions/Default/Actuators/CameraActuator/CameraActuator.cs index 2146f3c3..71169306 100644 --- a/src/Extensions/Default/Actuators/CameraActuator/CameraActuator.cs +++ b/src/Extensions/Default/Actuators/CameraActuator/CameraActuator.cs @@ -227,6 +227,11 @@ public override bool Init() return true; } + public CameraActuator() + { + _logger = LoggingConfiguration.CreateLogger(); + } + /// /// Pause the actuator /// @@ -297,7 +302,7 @@ public override void StartCalibration(RequestCalibrationReason reason) { try { - Log.Debug("Calling UpdateCalibrationstatus"); + _logger.LogDebug("Calling UpdateCalibrationstatus"); if (_autoCalibrateForm != null) { @@ -305,16 +310,16 @@ public override void StartCalibration(RequestCalibrationReason reason) _autoCalibrateForm = null; } - Log.Debug("Calling NotifyStartCalibration"); + _logger.LogDebug("Calling NotifyStartCalibration"); Context.AppActuatorManager.NotifyStartCalibration(new CalibrationNotifyEventArgs(true, false)); if (reason == RequestCalibrationReason.SensorInitiated) { - Log.Debug("Calling new Calibform"); + _logger.LogDebug("Calling new Calibform"); _autoCalibrateForm = new AutoCalibrateForm(this); - Log.Debug("Calling new Calibform show dialog"); + _logger.LogDebug("Calling new Calibform show dialog"); var form = Context.AppPanelManager.GetCurrentForm() as Form; if (form != null) @@ -328,7 +333,7 @@ public override void StartCalibration(RequestCalibrationReason reason) { _autoCalibrateForm.ShowDialog(); } - Log.Debug("Returned from Calibform show dialog"); + _logger.LogDebug("Returned from Calibform show dialog"); _autoCalibrateForm = null; } @@ -342,10 +347,10 @@ public override void StartCalibration(RequestCalibrationReason reason) } } - Log.Debug("Calling NotifyEndCalibration"); + _logger.LogDebug("Calling NotifyEndCalibration"); Context.AppActuatorManager.NotifyEndCalibration(); - Log.Debug("Calling OnEndCalibration"); + _logger.LogDebug("Calling OnEndCalibration"); OnEndCalibration(); if (_cameraActuatorInitInProgress) @@ -357,7 +362,7 @@ public override void StartCalibration(RequestCalibrationReason reason) } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex, ex.Message); } } @@ -453,21 +458,21 @@ internal void setHeadMovementSensitivity(int value) internal void setVisionSettings() { - Log.Debug("Setting vision parameters..."); + _logger.LogDebug("Setting vision parameters..."); - Log.Debug("HeadMovementSensitivity: " + CameraActuatorSettings.HeadMovementSensitivity); + _logger.LogDebug("HeadMovementSensitivity: {HeadMovementSensitivity}", CameraActuatorSettings.HeadMovementSensitivity); setHeadMovementSensitivity(CameraActuatorSettings.HeadMovementSensitivity); - Log.Debug("CheekTwitchSensitivity: " + CameraActuatorSettings.CheekTwitchSensitivity); + _logger.LogDebug("CheekTwitchSensitivity: {CheekTwitchSensitivity}", CameraActuatorSettings.CheekTwitchSensitivity); setCheekTwitchSensitivity(CameraActuatorSettings.CheekTwitchSensitivity); - Log.Debug("EyebrowRaiseSensitivity: " + CameraActuatorSettings.EyebrowRaiseSensitivity); + _logger.LogDebug("EyebrowRaiseSensitivity: {EyebrowRaiseSensitivity}", CameraActuatorSettings.EyebrowRaiseSensitivity); setEyebrowRaiseSensitivity(CameraActuatorSettings.EyebrowRaiseSensitivity); - Log.Debug("CheekTwitchHoldTime: " + CameraActuatorSettings.CheekTwitchHoldTime); + _logger.LogDebug("CheekTwitchHoldTime: {CheekTwitchHoldTime}", CameraActuatorSettings.CheekTwitchHoldTime); setCheekTwitchHoldTime(CameraActuatorSettings.CheekTwitchHoldTime); - Log.Debug("EyebrowRaiseHoldTime: " + CameraActuatorSettings.EyebrowRaiseHoldTime); + _logger.LogDebug("EyebrowRaiseHoldTime: {EyebrowRaiseHoldTime}", CameraActuatorSettings.EyebrowRaiseHoldTime); setEyebrowRaiseHoldTime(CameraActuatorSettings.EyebrowRaiseHoldTime); } @@ -481,7 +486,7 @@ protected override void Dispose(bool disposing) { try { - Log.Verbose(); + _logger.LogTrace("Dispose"); if (disposing) { @@ -562,7 +567,7 @@ private void callbackFromVision(string text) { var gesture = String.Empty; - Log.Debug("Received msg: " + text); + _logger.LogDebug("Received msg: {Message}", text); IActuatorSwitch actuatorSwitch = parseActuatorMsgAndGetSwitch(text, ref gesture); @@ -593,27 +598,27 @@ private void callbackFromVision(string text) { IsCalibrating = true; - Log.Debug("Received CALIB_START"); + _logger.LogDebug("Received CALIB_START"); EvtCalibrationStart?.Invoke(this, new EventArgs()); if (!_cameraActuatorInitInProgress && !_calibrateAndTestInProgress) { - Log.Debug("Calling RequestCalibration"); + _logger.LogDebug("Calling RequestCalibration"); RequestCalibration(_calibrateAndTestInProgress ? RequestCalibrationReason.AppRequested : RequestCalibrationReason.SensorInitiated); - Log.Debug("Returned from RequestCalibration"); + _logger.LogDebug("Returned from RequestCalibration"); } } catch (Exception ex) { - Log.Exception("Exception " + ex); + _logger.LogError(ex, ex.Message); } } else if (gesture == "CALIB_END") // end camera calibration { - Log.Debug("CALIB_END"); + _logger.LogDebug("CALIB_END"); IsCalibrating = false; @@ -708,7 +713,7 @@ private void showCalibrationAndTestForm() _calibrateAndTestInProgress = true; - _configureActuatorForm = new ConfigureActuatorForm(this); + _configureActuatorForm = new ConfigureActuatorForm(this, null); CameraSensor.showVideoWindow(); @@ -785,21 +790,18 @@ private void visionThread() } catch (SEHException seh) { - Log.Exception("acatVision threw a SEHException: " + seh.ToString()); - Log.Exception(seh); + _logger.LogError(seh, "acatVision threw a SEHException"); } catch (AccessViolationException ave) { - Log.Exception("acatVision threw an AccessViolationException: " + ave.ToString()); - Log.Exception(ave); + _logger.LogError(ave, "acatVision threw an AccessViolationException"); } catch (Exception ex) { - Log.Exception("acatVision threw an exception: " + ex.ToString()); - Log.Exception(ex); + _logger.LogError(ex, "acatVision threw an exception"); } - Log.Debug("ACATvision quit"); + _logger.LogDebug("ACATvision quit"); } public bool CalibrationDoneAtleastOnce diff --git a/src/Extensions/Default/Actuators/CameraActuator/ConfigureActuatorForm.cs b/src/Extensions/Default/Actuators/CameraActuator/ConfigureActuatorForm.cs index baf65862..0276bb5a 100644 --- a/src/Extensions/Default/Actuators/CameraActuator/ConfigureActuatorForm.cs +++ b/src/Extensions/Default/Actuators/CameraActuator/ConfigureActuatorForm.cs @@ -312,7 +312,7 @@ private void CameraActuator_EvtChangeCameraStart(String camera) form.Invoke(new MethodInvoker(delegate { labelPrompt.Text = String.Empty; - Log.Debug("Calling startTimer()"); + _logger.LogDebug("Calling startTimer()"); startTimer(_switchingCamera); })); } @@ -348,7 +348,7 @@ private void ConfigureActuatorForm_Load(object sender, EventArgs e) Resize += CalibrateForm_Resize; - _webcamGestureSelectUserControl = new WebcamGestureSelectUserControl(_cameraActuator); + _webcamGestureSelectUserControl = new WebcamGestureSelectUserControl(_cameraActuator, null); _webcamGestureSettingsUserControl = new WebcamGestureSettingsUserControl(_cameraActuator); _webcamGestureSettingsUserControl.EvtPause += _webcamGestureSettingsUserControl_EvtPause; @@ -372,7 +372,7 @@ private void ConfigureActuatorForm_Shown(object sender, EventArgs e) }; _textTimer.Tick += _textTimer_Tick; - _videoWindowFinder = new VideoWindowFinder(); + _videoWindowFinder = new VideoWindowFinder(null); _videoWindowFinder.EvtVideoWindowDisplayed += _videoWindowFinder_EvtVideoWindowDisplayed; _videoWindowFinder.EvtVideoWindowFindStart += _videoWindowFinder_EvtVideoWindowFindStart; diff --git a/src/Extensions/Default/AppAgents/ACATAgent/ACATAgent.cs b/src/Extensions/Default/AppAgents/ACATAgent/ACATAgent.cs index 4eb5f313..64513f68 100644 --- a/src/Extensions/Default/AppAgents/ACATAgent/ACATAgent.cs +++ b/src/Extensions/Default/AppAgents/ACATAgent/ACATAgent.cs @@ -20,5 +20,8 @@ namespace ACAT.Extensions.AppAgents.AcatAgent "Application Agent for the executing assembly")] internal class ACATAgent : ACATAgentBase { + public ACATAgent() : base(null) + { + } } } \ No newline at end of file diff --git a/src/Extensions/Default/AppAgents/TalkApplicationScannerAgent/TalkApplicationScannerAgent.cs b/src/Extensions/Default/AppAgents/TalkApplicationScannerAgent/TalkApplicationScannerAgent.cs index bc285394..d2f304f9 100644 --- a/src/Extensions/Default/AppAgents/TalkApplicationScannerAgent/TalkApplicationScannerAgent.cs +++ b/src/Extensions/Default/AppAgents/TalkApplicationScannerAgent/TalkApplicationScannerAgent.cs @@ -28,17 +28,7 @@ namespace ACAT.Extensions.AppAgents.TalkApplicationScannerAgent 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 + /// The text control agent responsible for handling /// editing and caret movement functions /// private TextControlAgentBase _textInterface; @@ -56,12 +46,10 @@ internal class TalkApplicationScannerAgent : AgentBase /// /// Initializes a new instance of the TalkApplicationScannerAgent class /// - public TalkApplicationScannerAgent(ILogger logger, ILoggerFactory loggerFactory) + public TalkApplicationScannerAgent(ILogger logger) : base(logger) { - _logger = logger ?? throw new ArgumentNullException(nameof(logger)); - _loggerFactory = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory)); } - private Control textBoxControl; + //private Control textBoxControl; /// /// Gets the list of process supported by this agent @@ -189,7 +177,7 @@ private void createTalkWindowTextInterface(IntPtr handle, AutomationElement auto bool handled = false; //_textInterface = new EditTextControlAgent(handle, automationElement, ref handled); - var textControlLogger = _loggerFactory.CreateLogger(); + var textControlLogger = LoggingConfiguration.CreateLogger(); _textInterface = new TalkApplicationTextControlAgent(textControlLogger, textBoxControl, handle, automationElement, ref handled); _textInterface.EvtTextChanged += _textInterface_EvtTextChanged; setTextInterface(_textInterface); diff --git a/src/Extensions/Default/FunctionalAgents/LaunchAppAgent/LaunchAppAgent.cs b/src/Extensions/Default/FunctionalAgents/LaunchAppAgent/LaunchAppAgent.cs index 3af60ecd..2038fbfc 100644 --- a/src/Extensions/Default/FunctionalAgents/LaunchAppAgent/LaunchAppAgent.cs +++ b/src/Extensions/Default/FunctionalAgents/LaunchAppAgent/LaunchAppAgent.cs @@ -64,8 +64,6 @@ internal class LaunchAppAgent : FunctionalAgentBase /// private const string SettingsFileName = "LaunchAppSettings.xml"; - private readonly ILogger _logger; - /// /// The usercontrol that displays the list of applications /// @@ -89,9 +87,8 @@ internal class LaunchAppAgent : FunctionalAgentBase /// /// Initializes a new instance of the class. /// - public LaunchAppAgent(ILogger logger) + public LaunchAppAgent(ILogger logger = null) : base(logger) { - _logger = logger; LaunchAppSettings.PreferencesFilePath = UserManager.GetFullPath(SettingsFileName); Settings = LaunchAppSettings.Load(); } diff --git a/src/Extensions/Default/FunctionalAgents/SwitchWindowsAgent/SwitchWindowsAgent.cs b/src/Extensions/Default/FunctionalAgents/SwitchWindowsAgent/SwitchWindowsAgent.cs index 927c2438..eb10dac6 100644 --- a/src/Extensions/Default/FunctionalAgents/SwitchWindowsAgent/SwitchWindowsAgent.cs +++ b/src/Extensions/Default/FunctionalAgents/SwitchWindowsAgent/SwitchWindowsAgent.cs @@ -50,8 +50,6 @@ internal class SwitchWindowsAgent : FunctionalAgentBase /// private static SwitchWindowsScanner _switchWindowsScanner; - private readonly ILogger _logger; - /// /// Meta data for window selected /// @@ -60,9 +58,8 @@ internal class SwitchWindowsAgent : FunctionalAgentBase /// /// Initializes a new instance of the class. /// - public SwitchWindowsAgent(ILogger logger) + public SwitchWindowsAgent(ILogger logger = null) : base(logger) { - _logger = logger; Name = ClassDescriptorAttribute.GetDescriptor(GetType()).Name; } diff --git a/src/Extensions/Default/FunctionalAgents/SwitchWindowsAgent/SwitchWindowsScanner.cs b/src/Extensions/Default/FunctionalAgents/SwitchWindowsAgent/SwitchWindowsScanner.cs index b5d82058..2f0fb65b 100644 --- a/src/Extensions/Default/FunctionalAgents/SwitchWindowsAgent/SwitchWindowsScanner.cs +++ b/src/Extensions/Default/FunctionalAgents/SwitchWindowsAgent/SwitchWindowsScanner.cs @@ -49,7 +49,8 @@ namespace ACAT.Extensions.FunctionalAgents.SwitchWindowsAgent "SwitchWindowsScanner", "Switch Windows Scanner")] public partial class SwitchWindowsScanner : GenericScannerForm - { private readonly ILogger _logger; + { + private readonly ILogger _logger; /// /// Enables invoking methods and properties in this form /// @@ -121,6 +122,7 @@ public partial class SwitchWindowsScanner : GenericScannerForm /// public SwitchWindowsScanner() : base() { + _logger = LoggingConfiguration.CreateLogger(); InitializeComponent(); } diff --git a/src/Extensions/Default/TTSEngines/SAPIEngine/SAPIEngine.cs b/src/Extensions/Default/TTSEngines/SAPIEngine/SAPIEngine.cs index d0d7ec9a..7c349ae3 100644 --- a/src/Extensions/Default/TTSEngines/SAPIEngine/SAPIEngine.cs +++ b/src/Extensions/Default/TTSEngines/SAPIEngine/SAPIEngine.cs @@ -96,7 +96,7 @@ public class SAPIEngine : ExtensionInvoker, ITTSEngine, ISupportsPreferences /// /// Initializes a new instance of the class. /// - public SAPIEngine(ILogger logger) + public SAPIEngine(ILogger logger = null) { _logger = logger; SAPISettings.PreferencesFilePath = UserManager.GetFullPath(SettingsFileName); diff --git a/src/Extensions/Default/TTSEngines/TTSClient/TTSClient.cs b/src/Extensions/Default/TTSEngines/TTSClient/TTSClient.cs index c2e4f0c4..79800e4d 100644 --- a/src/Extensions/Default/TTSEngines/TTSClient/TTSClient.cs +++ b/src/Extensions/Default/TTSEngines/TTSClient/TTSClient.cs @@ -629,7 +629,7 @@ private String getTempFileName(String extension) catch (Exception ex) { _logger.LogError(ex, "Could not create temp directory for TTSClient. {Exception}", ex); - path = ".\\\ + path = ".\\"; } path = path + "\\TTS_" + Guid.NewGuid() + extension; diff --git a/src/Extensions/Default/TTSEngines/TTSClient/Transport.cs b/src/Extensions/Default/TTSEngines/TTSClient/Transport.cs index 2cbe8319..6fd0442e 100644 --- a/src/Extensions/Default/TTSEngines/TTSClient/Transport.cs +++ b/src/Extensions/Default/TTSEngines/TTSClient/Transport.cs @@ -27,7 +27,7 @@ public class Transport : ITTSTransport public Transport() { _settings = TTSClientSettings.Load(); - _transportHttp = new TransportHttp(); + _transportHttp = new TransportHttp(null); } public TTSFormat Format diff --git a/src/Extensions/Default/WordPredictors/ConvAssist/ConvAssistUtils.cs b/src/Extensions/Default/WordPredictors/ConvAssist/ConvAssistUtils.cs index 1f715f07..8a31efef 100644 --- a/src/Extensions/Default/WordPredictors/ConvAssist/ConvAssistUtils.cs +++ b/src/Extensions/Default/WordPredictors/ConvAssist/ConvAssistUtils.cs @@ -128,7 +128,7 @@ public static List> ToList(List predictions } newList = sentences.ToList(); } - catch (Exception es) + catch { // Log exception but continue - return empty list // Note: Static method cannot use injected logger diff --git a/src/Extensions/Default/WordPredictors/ConvAssist/ConvAssistWordPredictor.cs b/src/Extensions/Default/WordPredictors/ConvAssist/ConvAssistWordPredictor.cs index 8fee7da0..7230a25e 100644 --- a/src/Extensions/Default/WordPredictors/ConvAssist/ConvAssistWordPredictor.cs +++ b/src/Extensions/Default/WordPredictors/ConvAssist/ConvAssistWordPredictor.cs @@ -11,6 +11,7 @@ //////////////////////////////////////////////////////////////////////////// //#define DEBUG_CONVASSIST +using ACAT.Core.PanelManagement; using ACAT.Core.PreferencesManagement; using ACAT.Core.PreferencesManagement.Interfaces; using ACAT.Core.UserManagement; @@ -92,20 +93,28 @@ public class ConvAssistWordPredictor : ConvAssistWordPredictorBase private bool pipeCreated; private Task wordPredictionTask; + /// + /// Initializes an instance of the class with default logger + /// + public ConvAssistWordPredictor() : this(Context.ServiceProvider?.GetService(typeof(ILogger)) as ILogger + ?? LoggingConfiguration.CreateLogger()) + { + } + /// /// Initializes and instance of the class /// public ConvAssistWordPredictor(ILogger logger) { - _logger = logger; + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); Settings.PreferencesFilePath = getUserRelativePath(CultureInfo.CurrentCulture.TwoLetterISOLanguageName, SettingsFileName, true); settings = Settings.Load(); convAssistSettings = settings; - _wordPredictionsRequestHandler = new WordPredictionsRequestHandler(this); - _sentencePredictionsRequestHandler = new SentencePredictionsRequestHandler(this); + _wordPredictionsRequestHandler = new WordPredictionsRequestHandler(this, null); + _sentencePredictionsRequestHandler = new SentencePredictionsRequestHandler(this, null); wpStack = new Stack(); sentenceStack = new Stack(); @@ -202,7 +211,7 @@ public override bool Init(CultureInfo ci) // 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"); - namedPipe = new NamedPipeServerConvAssist(PipeName, PipeDirection.InOut, convAssistSettings); + namedPipe = new NamedPipeServerConvAssist(PipeName, PipeDirection.InOut, convAssistSettings, LoggingConfiguration.CreateLogger()); pipeCreated = namedPipe.CreatePipeServer(send_params); if (pipeCreated) @@ -250,7 +259,7 @@ public override bool PredictAsync(WordPredictionRequest req) } /// - /// Send a request message Syncronously + /// Send a request message Synchronously /// /// Text to send to the client /// Sentences predictions @@ -263,7 +272,7 @@ public string ConvAssistLearn(string text, WordPredictorMessageTypes requestType } /// - /// Send a request message Syncronously + /// Send a request message Synchronously /// /// Text to send to the client /// Sentences predictions diff --git a/src/Extensions/Default/WordPredictors/ConvAssist/SentencePredictionsRequestHandler.cs b/src/Extensions/Default/WordPredictors/ConvAssist/SentencePredictionsRequestHandler.cs index e5a2dfeb..a97dce9b 100644 --- a/src/Extensions/Default/WordPredictors/ConvAssist/SentencePredictionsRequestHandler.cs +++ b/src/Extensions/Default/WordPredictors/ConvAssist/SentencePredictionsRequestHandler.cs @@ -59,7 +59,7 @@ public WordPredictionResponse ProcessPredictionRequest(WordPredictionRequest req WordPredictionResponse response; try { - _logger.LogDebug("_prevMode: {PrevMode}, currentMode: {CurrentMode}", _prevMode, _wordPredictor.GetMode()); + _logger?.LogDebug("_prevMode: {PrevMode}, currentMode: {CurrentMode}", _prevMode, _wordPredictor.GetMode()); if (_prevMode != _wordPredictor.GetMode() || _prevPrevWords == null || _prevCurrentWord == null || @@ -96,7 +96,7 @@ public WordPredictionResponse ProcessPredictionRequest(WordPredictionRequest req { predictedSentences = _wordPredictor.SendMessageConvAssistSentencePrediction(preceedingWords.ToString(), request.WordPredictionMode); - _logger.LogDebug("ConvAssist sentences response: {PredictedSentences}", predictedSentences); + _logger?.LogDebug("ConvAssist sentences response: {PredictedSentences}", predictedSentences); } else { @@ -133,13 +133,13 @@ public WordPredictionResponse ProcessPredictionRequest(WordPredictionRequest req } else { - _logger.LogDebug("Nothing changed. returning previous"); + _logger?.LogDebug("Nothing changed. returning previous"); response = new WordPredictionResponse(request, _prevSentencePredictionResults, true); } } catch (Exception ex) { - _logger.LogError(ex, "ConvAssist Predict Exception"); + _logger?.LogError(ex, "ConvAssist Predict Exception"); _prevSentencePredictionResults = new List(); response = new WordPredictionResponse(request, new List(), false); @@ -208,7 +208,7 @@ private List ProcessSentencesPredictions(string predictions, string curr } catch (Exception sentencesLetters) { - _logger.LogError(sentencesLetters, "ConvAssist Predict 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 f8815425..dd65707f 100644 --- a/src/Extensions/Default/WordPredictors/ConvAssist/WordPredictionsRequestHandler.cs +++ b/src/Extensions/Default/WordPredictors/ConvAssist/WordPredictionsRequestHandler.cs @@ -71,7 +71,7 @@ public WordPredictionsRequestHandler(ConvAssistWordPredictor wordPredictor, ILog /// A list of predicted words public WordPredictionResponse ProcessPredictionRequest(WordPredictionRequest request) { - _logger.LogDebug("Predict for: {PrevWords} {CurrentWord}", request.PrevWords, request.CurrentWord); + _logger?.LogDebug("Predict for: {PrevWords} {CurrentWord}", request.PrevWords, request.CurrentWord); StringBuilder preceedingWords = new(); if (request.PredictionType != PredictionTypes.Words) @@ -109,13 +109,13 @@ public WordPredictionResponse ProcessPredictionRequest(WordPredictionRequest req List result; try { - _logger.LogDebug("ConvAssist Mode: {WordPredictionMode}", request.WordPredictionMode); + _logger?.LogDebug("ConvAssist Mode: {WordPredictionMode}", request.WordPredictionMode); string predictedWords = String.Empty; predictedWords = WordPredictor.SendMessageConvAssistWordPrediction(preceedingWords.ToString(), request.WordPredictionMode); - _logger.LogDebug("ConvAssist Words response: {PredictedWords}", predictedWords); + _logger?.LogDebug("ConvAssist Words response: {PredictedWords}", predictedWords); try { @@ -133,7 +133,7 @@ public WordPredictionResponse ProcessPredictionRequest(WordPredictionRequest req PrevWordPredictionResults = result; } - _logger.LogDebug("Entered prediction {PrevWords} {CurrentWord}", prevWords, currentWord); + _logger?.LogDebug("Entered prediction {PrevWords} {CurrentWord}", prevWords, currentWord); response = new WordPredictionResponse(request, result, true); } @@ -144,7 +144,7 @@ public WordPredictionResponse ProcessPredictionRequest(WordPredictionRequest req } catch (Exception ex) { - _logger.LogError(ex, "ConvAssist Predict Exception"); + _logger?.LogError(ex, "ConvAssist Predict Exception"); response = new WordPredictionResponse(request, new List(), false); } finally @@ -234,7 +234,7 @@ private List ProcessWordPredictions(ConvAssistWordPredictor wordPredicto } catch (Exception words) { - _logger.LogError(words, "ConvAssist Predict Words"); + _logger?.LogError(words, "ConvAssist Predict Words"); } // Keyword to split between predictions retVal.Add("&LETTERS"); @@ -262,7 +262,7 @@ private List ProcessWordPredictions(ConvAssistWordPredictor wordPredicto } catch (Exception letters) { - _logger.LogError(letters, "ConvAssist Predict letters"); + _logger?.LogError(letters, "ConvAssist Predict letters"); } return retVal; } diff --git a/src/Libraries/ACATCore/ACAT.Core.csproj b/src/Libraries/ACATCore/ACAT.Core.csproj index 6ada2584..115aaacd 100644 --- a/src/Libraries/ACATCore/ACAT.Core.csproj +++ b/src/Libraries/ACATCore/ACAT.Core.csproj @@ -240,7 +240,9 @@ WebBrowserForm.cs + + diff --git a/src/Libraries/ACATCore/AbbreviationsManagement/Abbreviation.cs b/src/Libraries/ACATCore/AbbreviationsManagement/Abbreviation.cs index 82ea4dca..1a76d5c0 100644 --- a/src/Libraries/ACATCore/AbbreviationsManagement/Abbreviation.cs +++ b/src/Libraries/ACATCore/AbbreviationsManagement/Abbreviation.cs @@ -23,6 +23,7 @@ namespace ACAT.Core.AbbreviationsManagement { public class Abbreviation : IDisposable { + private static readonly ILogger _staticLogger = LoggingConfiguration.CreateLogger(); private readonly ILogger _logger; /// @@ -95,7 +96,7 @@ public static AbbreviationMode Convert(String mode) } catch (Exception ex) { - _logger?.LogError(ex, "Exception converting abbreviation mode"); + _staticLogger?.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 d2e5e13e..39edfe96 100644 --- a/src/Libraries/ACATCore/AbbreviationsManagement/Abbreviations.cs +++ b/src/Libraries/ACATCore/AbbreviationsManagement/Abbreviations.cs @@ -174,7 +174,7 @@ public bool Load(String abbreviationsFile = null) } else { - Log.Debug("Abbreviation file " + abbreviationsFile + " does not exist"); + _logger?.LogDebug("Abbreviation file {AbbreviationsFile} does not exist", abbreviationsFile); } } catch (Exception ex) @@ -199,7 +199,7 @@ public Abbreviation Lookup(String mnemonic) // do we detect something? if (_abbreviationList.ContainsKey(lookupString)) { - Log.Debug("Yes. Abbreviation list contains : " + lookupString); + _logger?.LogDebug("Yes. Abbreviation list contains : {LookupString}", lookupString); return _abbreviationList[lookupString]; } @@ -258,7 +258,7 @@ public bool Save(String abbreviationsFile) } catch (IOException ex) { - Log.Exception(ex); + _logger?.LogError(ex, ex.Message); retVal = false; } @@ -300,7 +300,7 @@ protected virtual void Dispose(bool disposing) // Check to see if Dispose has already been called. if (!_disposed) { - Log.Verbose(); + _logger?.LogTrace(""); if (disposing) { @@ -332,7 +332,7 @@ private void closeAbbreviationFile(XmlWriter xmlTextWriter) } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger?.LogError(ex, ex.Message); } } @@ -355,7 +355,7 @@ private XmlTextWriter createAbbreviationsFile(String fileName) } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger?.LogError(ex, ex.Message); xmlTextWriter = null; } diff --git a/src/Libraries/ACATCore/AbbreviationsManagement/AbbreviationsManager.cs b/src/Libraries/ACATCore/AbbreviationsManagement/AbbreviationsManager.cs index 2a2c9a41..2fdb361b 100644 --- a/src/Libraries/ACATCore/AbbreviationsManagement/AbbreviationsManager.cs +++ b/src/Libraries/ACATCore/AbbreviationsManagement/AbbreviationsManager.cs @@ -15,6 +15,7 @@ using ACAT.Core.PanelManagement; using ACAT.Core.PanelManagement.Common; using ACAT.Core.Utility; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using System; @@ -25,9 +26,15 @@ public class AbbreviationsManager : IDisposable private readonly ILogger _logger; /// - /// Static singleton instance + /// Static singleton instance - lazy initialized to get logger from DI container /// - private static readonly AbbreviationsManager _instance = new(); + private static readonly Lazy _instance = new Lazy(() => + { + // Get logger from DI container if available, otherwise create standalone logger + ILogger logger = Context.ServiceProvider?.GetService(typeof(ILogger)) as ILogger + ?? LoggingConfiguration.CreateLogger(); + return new AbbreviationsManager(logger); + }); /// /// Has this object been disposed @@ -37,9 +44,9 @@ public class AbbreviationsManager : IDisposable /// /// Initializes a new instance of the class. /// - private AbbreviationsManager(ILogger logger = null) + private AbbreviationsManager(ILogger logger) { - _logger = logger; + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); Context.EvtCultureChanged += Context_EvtCultureChanged; } @@ -48,7 +55,7 @@ private AbbreviationsManager(ILogger logger = null) /// public static AbbreviationsManager Instance { - get { return _instance; } + get { return _instance.Value; } } /// @@ -90,8 +97,6 @@ protected virtual void Dispose(bool disposing) // Check to see if Dispose has already been called. if (!_disposed) { - Log.Verbose(); - if (disposing) { Context.EvtCultureChanged -= Context_EvtCultureChanged; diff --git a/src/Libraries/ACATCore/ActuatorManagement/ActuatorBase.cs b/src/Libraries/ACATCore/ActuatorManagement/ActuatorBase.cs index 011834fc..28fda26d 100644 --- a/src/Libraries/ACATCore/ActuatorManagement/ActuatorBase.cs +++ b/src/Libraries/ACATCore/ActuatorManagement/ActuatorBase.cs @@ -278,25 +278,25 @@ public bool Load(IEnumerable switchSettings) // enumerate the switches in this actuator and create // each switch object using the switch ClassFactory - Log.Debug("Loading switches"); + _logger?.LogDebug("Loading switches"); foreach (var switchSetting in switchSettings) { var actuatorSwitch = CreateSwitch(); if (actuatorSwitch != null) { - Log.Debug("name=" + switchSetting.Name); + _logger?.LogDebug("Loading switch: {SwitchName}", switchSetting.Name); if (!_switches.ContainsKey(switchSetting.Name)) { if (actuatorSwitch.Load(switchSetting) && actuatorSwitch.Init()) { - Log.Debug("Adding switch " + actuatorSwitch.Name); + _logger?.LogDebug("Adding switch {SwitchName}", actuatorSwitch.Name); actuatorSwitch.Actuator = this; _switches.Add(actuatorSwitch.Name, actuatorSwitch); } } else { - Log.Warn("Warning. Switch " + actuatorSwitch.Name + " defined more than once"); + _logger?.LogWarning("Warning. Switch {SwitchName} defined more than once", actuatorSwitch.Name); } } } @@ -426,7 +426,7 @@ protected virtual void Dispose(bool disposing) // Check to see if Dispose has already been called. if (!_disposed) { - Log.Verbose(); + _logger?.LogTrace("Disposing ActuatorBase"); if (disposing) { @@ -454,8 +454,7 @@ protected SwitchAction getSwitchAction(String action) } catch (Exception e) { - Log.Warn("VisionAcutator switch, invalid action specified " + action); - Log.Exception(e); + _logger?.LogWarning(e, "VisionActuator switch, invalid action specified {Action}", action); } return retVal; @@ -477,7 +476,7 @@ protected IActuatorSwitch getSwitchForGesture( var imageSwitch = switchObj; if (String.Compare(imageSwitch.Source, gesture, true) == 0) { - Log.Debug("Found switch object " + switchObj.Name + " for gesture" + gesture); + _logger?.LogDebug("Found switch object {SwitchName} for gesture {Gesture}", switchObj.Name, gesture); return CreateSwitch(switchObj); } } @@ -577,7 +576,7 @@ protected IActuatorSwitch parseActuatorMsgAndGetSwitch(String strData, ref Strin bool actuate = true; parsedGesture = String.Empty; - Log.Debug(strData); + _logger?.LogDebug("Parsing actuator message: {Data}", strData); var tokens = strData.Split(';'); foreach (var token in tokens) @@ -696,7 +695,7 @@ protected bool ShowDefaultTryoutDialog() /// should the configure button b e enabled protected void UpdateCalibrationStatus(String caption, String prompt, int timeout = 0, bool enableConfigure = true, string buttonText = "") { - Log.Debug("Calling ActuatorManager.Instance.UpdateCalibrationStatus"); + _logger?.LogDebug("Calling ActuatorManager.Instance.UpdateCalibrationStatus"); ActuatorManager.Instance.UpdateCalibrationStatus(this, caption, prompt, timeout, enableConfigure, buttonText); } @@ -714,7 +713,7 @@ private long parseLong(String val) } catch (Exception e) { - Log.Exception(e); + _logger?.LogError(e, "Exception parsing long value"); } return retVal; diff --git a/src/Libraries/ACATCore/ActuatorManagement/ActuatorEx.cs b/src/Libraries/ACATCore/ActuatorManagement/ActuatorEx.cs index 91ceda9c..aca1893b 100644 --- a/src/Libraries/ACATCore/ActuatorManagement/ActuatorEx.cs +++ b/src/Libraries/ACATCore/ActuatorManagement/ActuatorEx.cs @@ -113,11 +113,11 @@ public void Init() { SourceActuator.Init(); - Log.Debug("Before Wait"); + _logger?.LogDebug("Waiting for initialization to complete"); WaitForInit(); - Log.Debug("After Wait"); + _logger?.LogDebug("Initialization wait completed"); } /// @@ -129,7 +129,7 @@ public void Init() /// should the config button be enabled public void OnEndCalibration(String errorMessage = "", bool enableConfigure = true) { - Log.Verbose(); + _logger?.LogTrace("Ending calibration"); if (!String.IsNullOrEmpty((errorMessage))) { @@ -138,7 +138,7 @@ public void OnEndCalibration(String errorMessage = "", bool enableConfigure = tr OnError(errorMessage, enableConfigure); } - Log.Debug("Calling closeCalibrationForm()"); + _logger?.LogDebug("Closing calibration form"); closeCalibrationForm(); _calibrationDoneEvent.Set(); @@ -189,11 +189,11 @@ public void PostInit() PostInitError = true; } - Log.Debug("Before Wait"); + _logger?.LogDebug("Waiting for post-initialization to complete"); WaitForPostInit(); - Log.Debug("After Wait"); + _logger?.LogDebug("Post-initialization wait completed"); } /// @@ -239,17 +239,17 @@ public void UpdateCalibrationStatus(Windows.WindowPosition position, String capt /// public void WaitForCalibration() { - Log.Debug("Waiting for calibration"); + _logger?.LogDebug("Waiting for calibration to complete"); _calibrationDoneEvent.WaitOne(); - Log.Debug("Calibration event is done"); + _logger?.LogDebug("Calibration event completed"); - Log.Debug("Waiting for calibration configure dialog"); + _logger?.LogDebug("Waiting for calibration configure dialog"); _bgTaskDoneEvent.WaitOne(); - Log.Debug("Calibration configure dialog event is done"); + _logger?.LogDebug("Calibration configure dialog completed"); } /// @@ -257,16 +257,16 @@ public void WaitForCalibration() /// public void WaitForInit() { - Log.Debug("Waiting for initdone"); + _logger?.LogDebug("Waiting for initialization done event"); initDoneEvent.WaitOne(); - Log.Debug("initdone is done"); + _logger?.LogDebug("Initialization done event signaled"); } public void WaitForPostInit() { - Log.Debug("Waiting for postinitdone"); + _logger?.LogDebug("Waiting for post-initialization done event"); postInitDoneEvent.WaitOne(); - Log.Debug("postinitdone is done"); + _logger?.LogDebug("Post-initialization done event signaled"); } /// @@ -293,9 +293,9 @@ private void bgWorker_DoWork(object sender, DoWorkEventArgs e) _formCreatedEvent.Set(); if (calibrationForm != null) { - Log.Debug("Calling calibrationform.ShowDialog"); + _logger?.LogDebug("Showing calibration form dialog"); DialogResult result = calibrationForm.ShowDialog(); - Log.Debug("Result: " + result); + _logger?.LogDebug("Calibration form closed with result: {Result}", result); // user closed the calibration form if (result == DialogResult.Cancel) @@ -306,7 +306,7 @@ private void bgWorker_DoWork(object sender, DoWorkEventArgs e) } else { - Log.Debug("calibration form IS NULL!!!"); + _logger?.LogWarning("Calibration form is null"); } if (calibrationForm != null) @@ -323,7 +323,7 @@ private void bgWorker_DoWork(object sender, DoWorkEventArgs e) /// event args private void bgWorker_RunCompleted(object sender, RunWorkerCompletedEventArgs e) { - Log.Verbose(); + _logger?.LogTrace("Background worker run completed"); _bgTaskDoneEvent.Set(); } @@ -336,7 +336,7 @@ private void closeCalibrationForm() { if (calibrationForm != null) { - Log.Debug("Closing calibration form, calling Dismiss()"); + _logger?.LogDebug("Closing calibration form"); calibrationForm.Dismiss(); calibrationForm = null; } diff --git a/src/Libraries/ACATCore/ActuatorManagement/ActuatorManager.cs b/src/Libraries/ACATCore/ActuatorManagement/ActuatorManager.cs index a3a223df..07f8bc00 100644 --- a/src/Libraries/ACATCore/ActuatorManagement/ActuatorManager.cs +++ b/src/Libraries/ACATCore/ActuatorManagement/ActuatorManager.cs @@ -123,11 +123,11 @@ public class ActuatorManager : IDisposable /// private ActuatorManager(ILogger logger = null) { - _logger = logger; + _logger = logger ?? LoggingConfiguration.CreateLogger(); _activeSwitches = new Dictionary(); - // _nonActuateSwitches = new Dictionary(); - // _syncObjectSwitches = new object(); - //} + _nonActuateSwitches = new Dictionary(); + _syncObjectSwitches = new object(); + } /// /// Deleagate for notification of start of calibration by an actuator @@ -358,7 +358,7 @@ public void OnCalibrationCanceled(IActuator source) { source.OnCalibrationCanceled(); - Log.Debug("Entered ActuatorManger.OnCalibrationCanceled"); + _logger.LogDebug("Entered ActuatorManger.OnCalibrationCanceled"); if (isCalibratingActuator(source)) { source.OnCalibrationCanceled(); @@ -387,14 +387,14 @@ public void OnCalibrationPeriodExpired(IActuator source) /// should the "configure" be enabled public void OnEndCalibration(IActuator source, String errorMessage = "", bool enableConfigure = true) { - Log.Verbose(); - Log.Debug("Calling isCalibratingActuator"); + _logger.LogTrace(string.Empty); + _logger.LogDebug("Calling isCalibratingActuator"); if (isCalibratingActuator(source)) { _calibratingActuatorEx.OnEndCalibration(errorMessage, enableConfigure); - Log.Debug("Setting calibratingActuatorEx to null"); + _logger.LogDebug("Setting calibratingActuatorEx to null"); _calibratingActuatorEx = null; } } @@ -481,17 +481,17 @@ public IActuator GetCalibrationSupportedActuator() /// the requesting actuator public void RequestCalibration(IActuator source, RequestCalibrationReason reason) { - Log.Debug("Entered RequestCalibration for " + source.Name); + _logger.LogDebug("Entered RequestCalibration for " + source.Name); if (!source.SupportsCalibration()) { - Log.Debug(source.Name + ": Does not support calibration. returning"); + _logger.LogDebug(source.Name + ": Does not support calibration. returning"); return; } if (calibrationQueue.Contains(source) || isCalibratingActuator(source)) { - Log.Debug("Already queued up or currently processing. Will not enqueue for " + source.Name); + _logger.LogDebug("Already queued up or currently processing. Will not enqueue for " + source.Name); return; } @@ -500,7 +500,7 @@ public void RequestCalibration(IActuator source, RequestCalibrationReason reason if (aex != null) { aex.RequestCalibration(reason); - Log.Debug("Enqueing calibration request for " + source.Name); + _logger.LogDebug("Enqueing calibration request for " + source.Name); calibrationQueue.Enqueue(aex); } @@ -616,15 +616,15 @@ public bool UnregisterSwitch(IActuator actuator, String switchName) /// text of the calibration button public void UpdateCalibrationStatus(IActuator source, String caption, String prompt, int timeout = 0, bool enableConfigure = true, String buttonText = "") { - Log.Debug("Checking if isCalibrationg for " + source.Name); + _logger.LogDebug("Checking if isCalibrationg for " + source.Name); if (isCalibratingActuator(source)) { - Log.Debug("UpdateCalibStatus: Yes it is!!. Calling calibratingActuatorEx.UpdateCalibrationStatus for " + source.Name); + _logger.LogDebug("UpdateCalibStatus: Yes it is!!. Calling calibratingActuatorEx.UpdateCalibrationStatus for " + source.Name); _calibratingActuatorEx.UpdateCalibrationStatus(getCalibrationFormPosition(), caption, prompt, timeout, enableConfigure, buttonText); } else { - Log.Debug("isCalibrating returned False. Actuator is NOT calibrating for " + source.Name); + _logger.LogDebug("isCalibrating returned False. Actuator is NOT calibrating for " + source.Name); } } @@ -762,7 +762,7 @@ protected virtual void Dispose(bool disposing) // Check to see if Dispose has already been called. if (!_disposed) { - Log.Verbose(); + _logger.LogTrace(string.Empty); if (disposing) { @@ -776,11 +776,11 @@ protected virtual void Dispose(bool disposing) if (_thread != null) { - Log.Debug("Calling thread.join"); + _logger.LogDebug("Calling thread.join"); _thread.Join(2000); } - Log.Debug("Exited thread"); + _logger.LogDebug("Exited thread"); if (_actuators != null) { @@ -845,7 +845,7 @@ private void act(IActuatorSwitch switchObj) if (!handled) { - Log.Debug("ACT on Switch " + switchObj.Name); + _logger.LogDebug("ACT on Switch " + switchObj.Name); notifySwitchActivated(switchObj); } } @@ -858,7 +858,7 @@ private void act(IActuatorSwitch switchObj) /// event args private void actuator_EvtSwitchActivated(object sender, ActuatorSwitchEventArgs e) { - Log.Debug("Switch " + e.SwitchObj.Name + " activated"); + _logger.LogDebug("Switch " + e.SwitchObj.Name + " activated"); disambiguateAndAct(e.SwitchObj.Actuate ? _activeSwitches : _nonActuateSwitches, e.SwitchObj); } @@ -870,7 +870,7 @@ private void actuator_EvtSwitchActivated(object sender, ActuatorSwitchEventArgs /// event args private void actuator_EvtSwitchDeactivated(object sender, ActuatorSwitchEventArgs e) { - Log.Debug("Switch " + e.SwitchObj.Name + " deactivated"); + _logger.LogDebug("Switch " + e.SwitchObj.Name + " deactivated"); //disambiguateAndAct(e.SwitchObj); disambiguateAndAct(e.SwitchObj.Actuate ? _activeSwitches : _nonActuateSwitches, e.SwitchObj); } @@ -882,7 +882,7 @@ private void actuator_EvtSwitchDeactivated(object sender, ActuatorSwitchEventArg /// event args private void actuator_EvtSwitchTriggered(object sender, ActuatorSwitchEventArgs e) { - Log.Debug("Switch " + e.SwitchObj.Name + " triggered"); + _logger.LogDebug("Switch " + e.SwitchObj.Name + " triggered"); //disambiguateAndAct(e.SwitchObj); disambiguateAndAct(e.SwitchObj.Actuate ? _activeSwitches : _nonActuateSwitches, e.SwitchObj); } @@ -905,9 +905,9 @@ private void calibrationHandlerThread() { while (!_exitThread) { - Log.Debug("Waiting for item"); + _logger.LogDebug("Waiting for item"); var obj = calibrationQueue.Dequeue(); - Log.Debug("Got item"); + _logger.LogDebug("Got item"); if (obj is String) { @@ -917,12 +917,12 @@ private void calibrationHandlerThread() if (obj is ActuatorEx) { _calibratingActuatorEx = obj as ActuatorEx; - Log.Debug("Before start calib"); + _logger.LogDebug("Before start calib"); var actuator = _calibratingActuatorEx; actuator.StartCalibration(); - Log.Debug("after start calib"); + _logger.LogDebug("after start calib"); - Log.Debug("Waiting for calib for " + actuator.SourceActuator.Name); + _logger.LogDebug("Waiting for calib for " + actuator.SourceActuator.Name); actuator.WaitForCalibration(); } @@ -946,7 +946,7 @@ private void disambiguateAndAct(Dictionary switches, IA if (!switchObj.Enabled) { - Log.Debug("Switch " + switchObj.Name + " is not enabled. Will be ignored"); + _logger.LogDebug("Switch " + switchObj.Name + " is not enabled. Will be ignored"); return; } @@ -957,7 +957,7 @@ private void disambiguateAndAct(Dictionary switches, IA { if (!switches.ContainsKey(switchObj.Name)) { - Log.Debug("SWITCH DOWN switches does not contain " + switchObj.Name + ". adding it"); + _logger.LogDebug("SWITCH DOWN switches does not contain " + switchObj.Name + ". adding it"); // add it to the current list of active switches switches.Add(switchObj.Name, switchObj); @@ -968,7 +968,7 @@ private void disambiguateAndAct(Dictionary switches, IA } else { - Log.Debug("SWITCH DOWN switches already contains " + switchObj.Name); + _logger.LogDebug("SWITCH DOWN switches already contains " + switchObj.Name); } } @@ -981,7 +981,7 @@ private void disambiguateAndAct(Dictionary switches, IA switchObj.RegisterSwitchUp(); if (switches.ContainsKey(switchObj.Name)) { - Log.Debug("SWITCH UP switches contains " + switchObj.Name); + _logger.LogDebug("SWITCH UP switches contains " + switchObj.Name); var activeSwitch = switches[switchObj.Name]; elapsedTime = (activeSwitch != null && activeSwitch.AcceptTimer.IsRunning) ? @@ -989,13 +989,13 @@ private void disambiguateAndAct(Dictionary switches, IA bool accepted = false; - Log.Debug("SWITCH UP Acauate: " + switchObj.Actuate); - Log.Debug("SWITCH UP Acticeswitch != null is " + (activeSwitch != null)); + _logger.LogDebug("SWITCH UP Acauate: " + switchObj.Actuate); + _logger.LogDebug("SWITCH UP Acticeswitch != null is " + (activeSwitch != null)); if (activeSwitch != null) { - Log.Debug("SWITCH UP Accepttimer is running " + activeSwitch.AcceptTimer.IsRunning); - Log.Debug("SWITCH UP Elapsed milli: " + activeSwitch.AcceptTimer.ElapsedMilliseconds); + _logger.LogDebug("SWITCH UP Accepttimer is running " + activeSwitch.AcceptTimer.IsRunning); + _logger.LogDebug("SWITCH UP Elapsed milli: " + activeSwitch.AcceptTimer.ElapsedMilliseconds); } if (switchObj.Actuate && @@ -1003,13 +1003,13 @@ private void disambiguateAndAct(Dictionary switches, IA activeSwitch.AcceptTimer.IsRunning && activeSwitch.AcceptTimer.ElapsedMilliseconds >= CoreGlobals.AppPreferences.MinActuationHoldTime) { - Log.Debug("SWITCH UP Switch accepted! ElapsedMilliseconds: " + activeSwitch.AcceptTimer.ElapsedMilliseconds); + _logger.LogDebug("SWITCH UP Switch accepted! ElapsedMilliseconds: " + activeSwitch.AcceptTimer.ElapsedMilliseconds); accepted = true; switchActivated = switchObj; } else { - Log.Debug("SWITCH UP Switch not found or actuate is false or timer not running or elapsedTime < accept time"); + _logger.LogDebug("SWITCH UP Switch not found or actuate is false or timer not running or elapsedTime < accept time"); } switches.Remove(switchObj.Name); @@ -1027,7 +1027,7 @@ private void disambiguateAndAct(Dictionary switches, IA } else { - Log.Debug("SWITCH UP switches does not contain " + switchObj.Name); + _logger.LogDebug("SWITCH UP switches does not contain " + switchObj.Name); } } @@ -1150,15 +1150,15 @@ private bool init() /// private bool isCalibratingActuator(IActuator actuator) { - Log.Debug("isCalibrating: " + actuator.Name + " calibratingActuatorEx is null:" + (_calibratingActuatorEx == null)); + _logger.LogDebug("isCalibrating: " + actuator.Name + " calibratingActuatorEx is null:" + (_calibratingActuatorEx == null)); if (_calibratingActuatorEx != null) { - Log.Debug("calibratingActuatorEx.SourceActuator: " + _calibratingActuatorEx.SourceActuator.Name); + _logger.LogDebug("calibratingActuatorEx.SourceActuator: " + _calibratingActuatorEx.SourceActuator.Name); } bool retVal = _calibratingActuatorEx != null && _calibratingActuatorEx.SourceActuator == actuator; - Log.Debug("isCalibrating: returning " + retVal); + _logger.LogDebug("isCalibrating: returning " + retVal); return retVal; } @@ -1183,7 +1183,7 @@ private void notifySwitchActivated(IActuatorSwitch switchObj) if (EvtSwitchActivated == null) { - Log.Debug("No subscribers. Returning"); + _logger.LogDebug("No subscribers. Returning"); return; } @@ -1191,7 +1191,7 @@ private void notifySwitchActivated(IActuatorSwitch switchObj) foreach (var del in delegates) { var switchActivated = (ActuatorSwitchEvent)del; - Log.Debug("Calling begininvoke for " + switchObj.Name); + _logger.LogDebug("Calling begininvoke for " + switchObj.Name); switchActivated.BeginInvoke(this, new ActuatorSwitchEventArgs(switchObj), null, null); } } @@ -1223,7 +1223,7 @@ private void notifySwitchHooks(IActuatorSwitch switchObj, ref bool handled) return; } - Log.Verbose(); + _logger.LogTrace(string.Empty); var delegates = EvtSwitchHook.GetInvocationList(); foreach (var del in delegates) diff --git a/src/Libraries/ACATCore/ActuatorManagement/ActuatorSwitchBase.cs b/src/Libraries/ACATCore/ActuatorManagement/ActuatorSwitchBase.cs index 2419f73e..a811cce3 100644 --- a/src/Libraries/ACATCore/ActuatorManagement/ActuatorSwitchBase.cs +++ b/src/Libraries/ACATCore/ActuatorManagement/ActuatorSwitchBase.cs @@ -399,8 +399,6 @@ protected virtual void Dispose(bool disposing) // Check to see if Dispose has already been called. if (!_disposed) { - Log.Verbose(); - if (disposing) { if (_timer != null) diff --git a/src/Libraries/ACATCore/ActuatorManagement/Actuators.cs b/src/Libraries/ACATCore/ActuatorManagement/Actuators.cs index 77b92f5a..aac216b5 100644 --- a/src/Libraries/ACATCore/ActuatorManagement/Actuators.cs +++ b/src/Libraries/ACATCore/ActuatorManagement/Actuators.cs @@ -148,7 +148,7 @@ public IActuator Find(String name) } } - Log.Warn("Could not find actuator by name " + name); + _logger?.LogWarning("Could not find actuator by name {Name}", name); return null; } @@ -163,12 +163,12 @@ public IActuator Find(Type actuatorType) { if (actuatorType.FullName == actuatorEx.SourceActuator.GetType().FullName) { - Log.Debug("Found actuator of type " + actuatorType.Name); + _logger?.LogDebug("Found actuator of type {TypeName}", actuatorType.Name); return actuatorEx.SourceActuator; } } - Log.Warn("Could not find actuator of type " + actuatorType.Name); + _logger?.LogWarning("Could not find actuator of type {TypeName}", actuatorType.Name); return null; } @@ -244,7 +244,7 @@ public bool Load(IEnumerable extensionDirs, String configFile, bool load } catch (Exception ex) { - Log.Exception(ex); + _logger?.LogError(ex, "Exception loading actuator"); } } @@ -281,7 +281,7 @@ public bool Load(IEnumerable extensionDirs, String configFile, bool load } catch (Exception ex) { - Log.Exception(ex); + _logger?.LogError(ex, "Exception adding actuator"); } } } @@ -374,7 +374,7 @@ protected virtual void Dispose(bool disposing) // Check to see if Dispose has already been called. if (!_disposed) { - Log.Verbose(); + _logger?.LogTrace("Disposing actuators"); if (disposing) { @@ -409,7 +409,7 @@ private void onFileFound(String dllName) } catch (Exception ex) { - Log.Exception($"Error loading actuator from {dllName}: {ex.Message}"); + _logger?.LogError(ex, "Error loading actuator from {DllName}", dllName); _DLLError = true; } } diff --git a/src/Libraries/ACATCore/ActuatorManagement/BaseActuators/KeyboardActuator.cs b/src/Libraries/ACATCore/ActuatorManagement/BaseActuators/KeyboardActuator.cs index d402cab6..505315db 100644 --- a/src/Libraries/ACATCore/ActuatorManagement/BaseActuators/KeyboardActuator.cs +++ b/src/Libraries/ACATCore/ActuatorManagement/BaseActuators/KeyboardActuator.cs @@ -14,6 +14,7 @@ using ACAT.Core.ActuatorManagement.Interfaces; using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Windows.Forms; @@ -25,6 +26,8 @@ namespace ACAT.Core.ActuatorManagement.BaseActuators "Handles Keyboard and Mouse input")] public class KeyboardActuator : ActuatorBase { + private static readonly ILogger _logger = LoggingConfiguration.CreateLogger(); + /// /// Indicated whetherthis object been disposed /// @@ -106,7 +109,7 @@ public override bool SupportsTryout /// The keyboard switch object public override IActuatorSwitch CreateSwitch() { - return new KeyboardSwitch(); + return new KeyboardSwitch(LoggingConfiguration.CreateLogger()); } //public override IOnboardingExtension GetOnboardingExtension() @@ -193,7 +196,7 @@ protected override void Dispose(bool disposing) { try { - Log.Verbose(); + _logger.LogTrace(""); if (disposing) { @@ -230,14 +233,14 @@ private IActuatorSwitch findActuatorSwitch(string hotKey) { if (string.Compare(keySwitch.HotKey, hotKey, true) == 0) { - return new KeyboardSwitch(keySwitch); + return new KeyboardSwitch(keySwitch, LoggingConfiguration.CreateLogger()); } } } } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex, ex.Message); } return null; @@ -257,7 +260,7 @@ private void KeyboardHook_KeyDown(object sender, KeyEventArgs e) return; } - Log.Debug("Keydown: " + e.KeyCode.ToString()); + _logger.LogDebug("Keydown: {KeyCode}", e.KeyCode); // check if this is one of the keys we recognize. If so, trigger // a switch-activated event @@ -286,7 +289,7 @@ private void KeyboardHook_KeyDown(object sender, KeyEventArgs e) hotKey += "+" + e.KeyCode; } - Log.Debug("KeyStateTracker.KeyString: " + hotKey); + _logger.LogDebug("KeyStateTracker.KeyString: {HotKey}", hotKey); // check which switch handles this hotkey and trigger it actuatorSwitch = findActuatorSwitch(hotKey); @@ -316,7 +319,7 @@ private void KeyboardHook_KeyPress(object sender, KeyPressEventArgs e) } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex, ex.Message); } } @@ -333,7 +336,7 @@ private void KeyboardHook_KeyUp(object sender, KeyEventArgs e) } var s = string.Format("Keyup{0}. Alt: {1} Ctrl: {2}", e.KeyCode, e.Alt, e.Control); - Log.Debug(s); + _logger.LogDebug("{Message}", s); KeyStateTracker.KeyUp(e.KeyCode); diff --git a/src/Libraries/ACATCore/ActuatorManagement/UI/ConfigureSwitchesForm.cs b/src/Libraries/ACATCore/ActuatorManagement/UI/ConfigureSwitchesForm.cs index 789ce5d5..cfea127c 100644 --- a/src/Libraries/ACATCore/ActuatorManagement/UI/ConfigureSwitchesForm.cs +++ b/src/Libraries/ACATCore/ActuatorManagement/UI/ConfigureSwitchesForm.cs @@ -15,6 +15,7 @@ using ACAT.Core.ActuatorManagement.Interfaces; using ACAT.Core.ActuatorManagement.Settings; using ACAT.Core.PanelManagement; +using ACAT.Core.Utility; using ACATResources; using System; using System.Windows.Forms; @@ -200,7 +201,7 @@ private void dataGridView2_CellContentClick(object sender, DataGridViewCellEvent Hide(); // var switchCommandMapForm = new SwitchCommandMapForm {Title = "Map Command to Switch " + switchName}; - var switchCommandMapForm = new SwitchCommandMapForm { Title = "Map Command to Switch " + switchName }; + var switchCommandMapForm = new SwitchCommandMapForm(LoggingConfiguration.CreateLogger()) { Title = "Map Command to Switch " + switchName }; switchCommandMapForm.ShowDialog(); Show(); diff --git a/src/Libraries/ACATCore/ActuatorManagement/UI/EditKeyboardActuatorSwitchForm.cs b/src/Libraries/ACATCore/ActuatorManagement/UI/EditKeyboardActuatorSwitchForm.cs index 648e6899..0275a2a9 100644 --- a/src/Libraries/ACATCore/ActuatorManagement/UI/EditKeyboardActuatorSwitchForm.cs +++ b/src/Libraries/ACATCore/ActuatorManagement/UI/EditKeyboardActuatorSwitchForm.cs @@ -11,6 +11,7 @@ //////////////////////////////////////////////////////////////////////////// using ACAT.Core.PanelManagement; +using ACAT.Core.Utility; using ACATResources; using System; using System.Windows.Forms; @@ -77,7 +78,7 @@ private void buttonCommand_Click(object sender, EventArgs e) Hide(); // var switchCommandMapForm = new SwitchCommandMapForm { Title = "Map command to keyboard shortcut" }; - var switchCommandMapForm = new SwitchCommandMapForm { Title = "Map command to keyboard shortcut" }; + var switchCommandMapForm = new SwitchCommandMapForm(LoggingConfiguration.CreateLogger()) { Title = "Map command to keyboard shortcut" }; switchCommandMapForm.ShowDialog(); Show(); diff --git a/src/Libraries/ACATCore/ActuatorManagement/WinsockActuators/WinsockServerActuator/SocketServer.cs b/src/Libraries/ACATCore/ActuatorManagement/WinsockActuators/WinsockServerActuator/SocketServer.cs index da256580..e0dd50e4 100644 --- a/src/Libraries/ACATCore/ActuatorManagement/WinsockActuators/WinsockServerActuator/SocketServer.cs +++ b/src/Libraries/ACATCore/ActuatorManagement/WinsockActuators/WinsockServerActuator/SocketServer.cs @@ -13,6 +13,7 @@ //////////////////////////////////////////////////////////////////////////// using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Collections.Specialized; using System.Net; @@ -28,6 +29,8 @@ namespace ACAT.Core.ActuatorManagement.WinsockActuators.WinsockServerActuator /// public class SocketServer { + private readonly ILogger _logger; + /// /// List of clients connected to this socket server /// @@ -75,8 +78,9 @@ public SocketServer(int listenPort) /// /// Default constructor. /// - public SocketServer(string listenAddress, int listenPort) + public SocketServer(string listenAddress, int listenPort, ILogger logger = null) { + _logger = logger; ipToBind = listenAddress; portToBind = listenPort; parentThread = Thread.CurrentThread; @@ -192,7 +196,7 @@ public Thread Start() } catch (Exception exc) { - Log.Error("Couldn't start the SocketServer main working thread." + exc.StackTrace); + _logger?.LogError(exc, "Couldn't start the SocketServer main working thread"); workerThread = null; } @@ -204,18 +208,18 @@ public Thread Start() /// public void Stop() { - Log.Debug("SERVER: Stopping listeners until service is started again"); + _logger?.LogDebug("SERVER: Stopping listeners until service is started again"); try { tcpListener.Stop(); } catch (SocketException se) { - Log.Exception(se.ToString()); + _logger?.LogError(se, "Socket exception while stopping TCP listener"); } catch (Exception e) { - Log.Exception(e.ToString()); + _logger?.LogError(e, "Exception while stopping TCP listener"); } if (listenThread != null) { @@ -265,18 +269,14 @@ private void connHandler_OnPacketReceived(byte[] packet) /// private void ListenForClients() { - Log.Debug("SocketServer: Listener Thread"); + _logger?.LogDebug("SocketServer: Listener Thread started"); try { tcpListener.Start(); } catch (SocketException se) { - //Log.Error(se.IncludeStackTrace); - Log.Error(se.StackTrace); - // se.ErrorCode == 10048, this condition means that more than one process is attempting to bind to same port, disallowed. - // Log.Write(String.Format("SocketException: NativeError:{0} ErrorCode:{1}, Msg:{2}", se.NativeErrorCode, se.ErrorCode, se.Message)); - // Log.Debug("Socket Exception Listening for clients", se); + _logger?.LogError(se, "Socket exception while starting TCP listener (ErrorCode: {ErrorCode})", se.ErrorCode); listenThread.Abort(); return; } @@ -292,12 +292,12 @@ private void ListenForClients() IPAddress addr = IPAddress.Parse(ipe.Address.ToString()); string strAddr = addr.ToString(); - Log.Debug("Client " + strAddr + " has connected"); + _logger?.LogDebug("Client {ClientAddress} has connected", strAddr); // Create a thread to handle communication with a connected client. // The ClientConnHandler is an object that allows a way to pass data to a thread. The TcpClient is passed to the // object constructor and a thread is started with the objects worker method... allowing the thread access to the client. - var connHandler = new ClientConnHandler(client); + var connHandler = new ClientConnHandler(client, LoggingConfiguration.CreateLogger()); connHandler.OnPacketReceived += connHandler_OnPacketReceived; if (!string.IsNullOrEmpty(connHandler.ID)) { @@ -308,7 +308,7 @@ private void ListenForClients() } catch (SocketException se) { - Log.Error(se.StackTrace); + _logger?.LogError(se, "Socket exception while accepting client connection"); } } } @@ -328,7 +328,7 @@ private void serverThreadMethod() } catch (SocketException se) { - Log.Error("SERVER: Couldn't start TCP Listener, exiting the app. " + se.StackTrace); + _logger?.LogError(se, "SERVER: Couldn't start TCP Listener, exiting the app"); return; } catch (Exception ex) @@ -339,7 +339,7 @@ private void serverThreadMethod() string startMessage = string.Format("SERVER: Listener Started on {0}:{1}", ((IPEndPoint)tcpListener.LocalEndpoint).Address, ((IPEndPoint)tcpListener.LocalEndpoint).Port); - Log.Debug(startMessage); + _logger?.LogDebug("{StartMessage}", startMessage); parentThread.Join(); // A way to get current thread to wait until a thread is complete before continuing. } diff --git a/src/Libraries/ACATCore/ActuatorManagement/WinsockActuators/WinsockServerActuator/WinsockServerActuatorBase.cs b/src/Libraries/ACATCore/ActuatorManagement/WinsockActuators/WinsockServerActuator/WinsockServerActuatorBase.cs index f652a410..a71c2d3a 100644 --- a/src/Libraries/ACATCore/ActuatorManagement/WinsockActuators/WinsockServerActuator/WinsockServerActuatorBase.cs +++ b/src/Libraries/ACATCore/ActuatorManagement/WinsockActuators/WinsockServerActuator/WinsockServerActuatorBase.cs @@ -15,6 +15,7 @@ using ACAT.Core.ActuatorManagement.Interfaces; using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System.Text; namespace ACAT.Core.ActuatorManagement.WinsockActuators.WinsockServerActuator @@ -27,6 +28,8 @@ namespace ACAT.Core.ActuatorManagement.WinsockActuators.WinsockServerActuator /// public class WinsockServerActuatorBase : ActuatorBase { + private static ILogger _logger => LogManager.GetLogger(); + /// /// Has this object been disposed? /// @@ -109,7 +112,7 @@ protected override void Dispose(bool disposing) { try { - Log.Verbose(); + _logger?.LogTrace("Disposing WinsockServerActuatorBase"); if (disposing) { @@ -152,7 +155,7 @@ protected virtual void onClientDisconnected(WinsockClientConnectEventArgs e) protected virtual void onDataReceived(byte[] packet) { string strData = Encoding.ASCII.GetString(packet, 0, packet.Length); - Log.Debug("Received data: " + strData); + _logger?.LogDebug("Received data: {Data}", strData); // parse the string, find the switch that causes the trigger IActuatorSwitch switchObj = WinsockCommon.parseAndGetSwitch(strData, Switches, CreateSwitch); @@ -191,7 +194,7 @@ protected void triggerEvent(IActuatorSwitch switchObj) /// event arg private void _socketServer_OnClientConnected(object sender, WinsockClientConnectEventArgs e) { - Log.Debug("ImageActuator: Client disconnected " + e.IPAddress); + _logger?.LogDebug("ImageActuator: Client disconnected {IPAddress}", e.IPAddress); onClientConnected(e); } @@ -202,7 +205,7 @@ private void _socketServer_OnClientConnected(object sender, WinsockClientConnect /// event argument private void _socketServer_OnClientDisconnected(object sender, WinsockClientConnectEventArgs e) { - Log.Debug("ImageActuator: Client connected " + e.IPAddress); + _logger?.LogDebug("ImageActuator: Client connected {IPAddress}", e.IPAddress); onClientDisconnected(e); } @@ -232,7 +235,7 @@ private void initSocketInterface() } else { - Log.Debug("Listen error. Listen port not set"); + _logger?.LogDebug("Listen error. Listen port not set"); } } diff --git a/src/Libraries/ACATCore/AgentManagement/AgentBase.cs b/src/Libraries/ACATCore/AgentManagement/AgentBase.cs index bd5d0eb9..b2e6fb7f 100644 --- a/src/Libraries/ACATCore/AgentManagement/AgentBase.cs +++ b/src/Libraries/ACATCore/AgentManagement/AgentBase.cs @@ -29,7 +29,7 @@ public abstract class AgentBase : IApplicationAgent /// /// Logger instance for this class /// - private readonly ILogger _logger; + protected readonly ILogger _logger; /// /// Used to invoke methods/properties in the agent @@ -457,8 +457,6 @@ private void dispose(bool disposing) { if (!_disposed) { - Log.Verbose(); - if (disposing) { _nullTextInterface?.Dispose(); diff --git a/src/Libraries/ACATCore/AgentManagement/AgentManager.cs b/src/Libraries/ACATCore/AgentManagement/AgentManager.cs index e3c10443..6bc031b3 100644 --- a/src/Libraries/ACATCore/AgentManagement/AgentManager.cs +++ b/src/Libraries/ACATCore/AgentManagement/AgentManager.cs @@ -14,6 +14,7 @@ using ACAT.Core.PanelManagement.CommandDispatcher; using ACAT.Core.PanelManagement.Common; using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Diagnostics; @@ -137,9 +138,20 @@ public class AgentManager : IDisposable private const string NullAgentName = "**nullagent**"; /// - /// Singleton instance of the Agent manager + /// Singleton instance of the Agent manager - lazy initialized to get logger from DI container /// - private static readonly AgentManager _instance = new(); + private static readonly Lazy _instance = new Lazy(() => + { + // Get logger from DI container if available, otherwise use LogManager + ILogger logger = Context.ServiceProvider?.GetService(typeof(ILogger)) as ILogger + ?? LogManager.GetLogger(); + return new AgentManager(logger); + }); + + /// + /// Logger instance + /// + private readonly ILogger _logger; /// /// Name of the executing assembly @@ -235,8 +247,10 @@ public class AgentManager : IDisposable /// /// Initializes a new instance of the class. /// - private AgentManager() + private AgentManager(ILogger logger) { + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + _currentProcessName = Process.GetCurrentProcess().ProcessName.ToLower(); _textChangedNotifications = new TriggerLock(); @@ -286,7 +300,7 @@ private AgentManager() /// public static AgentManager Instance { - get { return _instance; } + get { return _instance.Value; } } /// @@ -416,12 +430,12 @@ public async Task ActivateAgent(IApplicationAgent caller, IFunctionalAgent agent setAgent(agent); } - Log.Debug("Calling activateAgent: " + agent.Name); + _logger?.LogDebug("Calling activateAgent: " + agent.Name); await activateAgent(agent); CompletionCode exitCode = agent.ExitCode; - Log.Debug("Returned from activateAgent: " + agent.Name); + _logger?.LogDebug("Returned from activateAgent: " + agent.Name); setAgent(null); if (agent.ExitCommand != null) @@ -454,7 +468,7 @@ public async Task ActivateAgent(IFunctionalAgent agent) { if (_currentAgent is IFunctionalAgent) { - Log.Debug("Cannot activate functional agent " + agent.Name + ", functional agent " + _currentAgent.Name + " is currently active"); + _logger?.LogDebug("Cannot activate functional agent " + agent.Name + ", functional agent " + _currentAgent.Name + " is currently active"); return; } @@ -484,7 +498,7 @@ public AgentContext ActiveContext() /// agent to add public void AddAgent(IntPtr handle, IApplicationAgent agent) { - Log.Debug("hwnd: " + handle + ", " + agent.Name); + _logger?.LogDebug("hwnd: " + handle + ", " + agent.Name); agent.EvtPanelRequest += agent_EvtPanelRequest; _agentsCache.AddAgent(handle, agent); @@ -523,7 +537,7 @@ public void CheckCommandEnabled(CommandEnabledArg arg) if (_currentAgent is IFunctionalAgent && ((FunctionalAgentBase)_currentAgent).IsClosing) { - Log.Debug("Functional agent is closing. returning"); + _logger?.LogDebug("Functional agent is closing. returning"); return; } @@ -656,7 +670,9 @@ public bool LoadExtensions(IEnumerable extensionDirs) { if (_agentsCache == null) { - _agentsCache = new AgentsCache(); + var agentsCacheLogger = Context.ServiceProvider?.GetService(typeof(ILogger)) as ILogger + ?? LoggingConfiguration.CreateLogger(); + _agentsCache = new AgentsCache(agentsCacheLogger); _agentsCache.EvtAgentAdded += _agentsCache_EvtAgentAdded; return _agentsCache.Init(extensionDirs); } @@ -672,9 +688,9 @@ public bool LoadExtensions(IEnumerable extensionDirs) [EnvironmentPermission(SecurityAction.LinkDemand, Unrestricted = true)] public void OnPanelClosed(String panelClass) { - Log.Verbose(); - Log.Debug("panelClass : " + panelClass); - Log.Debug(" currentAgent: " + _currentAgent); + _logger.LogTrace("OnPanelClosed"); + _logger.LogDebug("panelClass : " + panelClass); + _logger.LogDebug(" currentAgent: " + _currentAgent); if (_currentAgent != null) { var currentWindow = WindowActivityMonitor.CurrentWindowInfo(); @@ -768,7 +784,7 @@ public void RunCommand(String command, ref bool handled) { if (_currentAgent != null) { - Log.Debug("Calling runcommand agent : " + _currentAgent.Name + ", command: " + command); + _logger?.LogDebug("Calling runcommand agent : " + _currentAgent.Name + ", command: " + command); var cmd = (command[0] == '@') ? command.Substring(1) : command; _currentAgent.OnRunCommand(cmd, null, ref handled); @@ -786,7 +802,7 @@ public void RunCommand(String command, object arg, ref bool handled) { if (_currentAgent != null) { - Log.Debug("Calling runcommand agent : " + _currentAgent.Name + ", command: " + command); + _logger?.LogDebug("Calling runcommand agent : " + _currentAgent.Name + ", command: " + command); String cmd = (command[0] == '@') ? command.Substring(1) : command; _currentAgent.OnRunCommand(cmd, arg, ref handled); } @@ -943,30 +959,30 @@ private async Task activateAgent(IFunctionalAgent agent) var funcAgent = (FunctionalAgentBase)agent; Task task = Task.Factory.StartNew(() => { - Log.Debug("Calling funcAgent.activate: " + agent.Name); + _logger?.LogDebug("Calling funcAgent.activate: " + agent.Name); //funcAgent.IsClosing = false; funcAgent.ExitCommand = null; form.Invoke(new MethodInvoker(delegate { Context.AppPanelManager.NewStack(); - Log.Debug("Before activate " + funcAgent.Name); + _logger?.LogDebug("Before activate " + funcAgent.Name); funcAgent.Activate(); - Log.Debug("Returned from activate " + funcAgent.Name + ", calling closestack"); + _logger?.LogDebug("Returned from activate " + funcAgent.Name + ", calling closestack"); Context.AppPanelManager.CloseStack(); })); // This event is triggered by the functional agent when it exits - Log.Debug("Waiting on CloseEvent...: " + agent.Name); + _logger?.LogDebug("Waiting on CloseEvent...: " + agent.Name); funcAgent.CloseEvent.WaitOne(); - Log.Debug("Returned from CloseEvent: " + agent.Name); + _logger?.LogDebug("Returned from CloseEvent: " + agent.Name); funcAgent.PostClose(); }); - Log.Debug("Before await task"); + _logger?.LogDebug("Before await task"); await task; - Log.Debug("After await task"); + _logger?.LogDebug("After await task"); Windows.CloseForm(form); } @@ -985,27 +1001,27 @@ private void activateAppAgent(WindowActivityMonitorInfo monitorInfo) { if (inActivateAppAgent) { - Log.Warn("Already inside. returning"); + _logger?.LogWarning("Already inside. returning"); return; } - Log.Verbose("Before syncsetagent"); + _logger?.LogTrace("Before syncsetagent"); lock (_syncActivateAgent) { inActivateAppAgent = true; - Log.Verbose("After syncsetagent"); + _logger?.LogTrace("After syncsetagent"); try { bool handled = false; - //Log.Debug(monitorInfo.ToString()); + //_logger?.LogDebug(monitorInfo.ToString()); // did a request for displaying the contextual // menu come in? If so handle it. bool getContextMenu = _getContextMenu; - Log.Verbose("getContextMenu: " + getContextMenu); + _logger?.LogTrace("getContextMenu: " + getContextMenu); _getContextMenu = false; @@ -1013,12 +1029,12 @@ private void activateAppAgent(WindowActivityMonitorInfo monitorInfo) // first check if there is an ad-hoc agent, if so, // activate it - Log.Verbose("Looking for adhoc agent for " + monitorInfo.FgHwnd); + _logger?.LogTrace("Looking for adhoc agent for " + monitorInfo.FgHwnd); IApplicationAgent agent = _agentsCache.GetAgent(monitorInfo.FgHwnd); if (agent == null) { // check if a dialog or menu is active - Log.Verbose("Adhoc agent not present for " + monitorInfo.FgHwnd); + _logger?.LogTrace("Adhoc agent not present for " + monitorInfo.FgHwnd); IntPtr parent = User32Interop.GetParent(monitorInfo.FgHwnd); if (parent != IntPtr.Zero) @@ -1027,13 +1043,13 @@ private void activateAppAgent(WindowActivityMonitorInfo monitorInfo) (String.Compare(processName, _currentProcessName, true) != 0) && isDialog(monitorInfo)) { - Log.Verbose("Fg window is a dialog. Setting agent to dialog agent"); + _logger?.LogTrace("Fg window is a dialog. Setting agent to dialog agent"); agent = _dialogAgent; } else if (EnableContextualMenusForMenus && isMenu(monitorInfo)) { - Log.Verbose("Fg window is a menu. Setting agent to menu agent"); + _logger?.LogTrace("Fg window is a menu. Setting agent to menu agent"); agent = _menuControlAgent; } } @@ -1042,23 +1058,23 @@ private void activateAppAgent(WindowActivityMonitorInfo monitorInfo) { if (Windows.IsMinimized(monitorInfo.FgHwnd)) { - Log.Verbose("Window is minimized. Use generic agent"); + _logger?.LogTrace("Window is minimized. Use generic agent"); agent = _genericAppAgent; } else { // check if there is a dedicated agent for this process - Log.Verbose("Getting agent for " + processName); + _logger?.LogTrace("Getting agent for " + processName); agent = _agentsCache.GetAgent(monitorInfo.FgProcess); } } } else { - Log.Verbose("Adhoc agent IS present for " + monitorInfo.FgHwnd); + _logger?.LogTrace("Adhoc agent IS present for " + monitorInfo.FgHwnd); } - Log.Verbose("Current agent: " + ((_currentAgent != null) ? + _logger?.LogTrace("Current agent: " + ((_currentAgent != null) ? _currentAgent.Name : "null") + ", agent: " + ((agent != null) ? agent.Name : "null")); @@ -1068,7 +1084,7 @@ private void activateAppAgent(WindowActivityMonitorInfo monitorInfo) if (_currentAgent != null && _currentAgent != agent) { bool allowSwitch = _currentAgent.QueryAgentSwitch(agent); - Log.Verbose("CurrentAgent is " + _currentAgent.Name + ", queryAgentSwitch: " + allowSwitch); + _logger?.LogTrace("CurrentAgent is " + _currentAgent.Name + ", queryAgentSwitch: " + allowSwitch); if (!allowSwitch) { _currentAgent.OnFocusChanged(monitorInfo, ref handled); @@ -1085,7 +1101,7 @@ private void activateAppAgent(WindowActivityMonitorInfo monitorInfo) { agent ??= _genericAppAgent; - Log.Verbose("agent : " + agent.Name); + _logger?.LogTrace("agent : " + agent.Name); agent.OnContextMenuRequest(monitorInfo); return; } @@ -1095,9 +1111,9 @@ private void activateAppAgent(WindowActivityMonitorInfo monitorInfo) // is appropriated for the context. if (agent != null) { - Log.Verbose("Trying agent " + agent.Name); + _logger?.LogTrace("Trying agent " + agent.Name); agent.OnFocusChanged(monitorInfo, ref handled); - Log.Verbose("Returned from agent.OnFOcus"); + _logger?.LogTrace("Returned from agent.OnFOcus"); } // If we have reached here, it means there was no @@ -1105,8 +1121,8 @@ private void activateAppAgent(WindowActivityMonitorInfo monitorInfo) // if it will handle it if (!handled) { - Log.Verbose("Did not find agent for " + processName + ". trying generic app agent"); - Log.Verbose("_genericAppAgent is " + ((_genericAppAgent != null) ? "not null" : "null")); + _logger?.LogTrace("Did not find agent for " + processName + ". trying generic app agent"); + _logger?.LogTrace("_genericAppAgent is " + ((_genericAppAgent != null) ? "not null" : "null")); agent = _genericAppAgent; try { @@ -1114,16 +1130,16 @@ private void activateAppAgent(WindowActivityMonitorInfo monitorInfo) } catch (Exception ex) { - Log.Exception(ex); + _logger?.LogError(ex, ex.Message); } } // even the generic agent refused. Use the null agent // as the last resort - Log.Verbose("handled " + handled); + _logger?.LogTrace("handled " + handled); if (!handled) { - Log.Verbose("generic app agent refused. Using null agent"); + _logger?.LogTrace("generic app agent refused. Using null agent"); agent = _nullAgent; agent.OnFocusChanged(monitorInfo, ref handled); } @@ -1132,7 +1148,7 @@ private void activateAppAgent(WindowActivityMonitorInfo monitorInfo) } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger?.LogError(ex.ToString()); } finally { @@ -1140,7 +1156,7 @@ private void activateAppAgent(WindowActivityMonitorInfo monitorInfo) } } - Log.Verbose("Return"); + _logger?.LogTrace("Return"); } /// @@ -1172,7 +1188,7 @@ private void agent_EvtAgentClose(object sender, AgentCloseEventArgs e) /// event arg private void agent_EvtPanelRequest(object sender, PanelRequestEventArgs arg) { - Log.Debug("Panel request for " + arg.PanelClass); + _logger?.LogDebug("Panel request for " + arg.PanelClass); triggerPanelRequest(sender, arg); } @@ -1213,7 +1229,7 @@ private void disallowContextSwitch(WindowActivityMonitorInfo monitorInfo) agent ??= _genericAppAgent; - Log.Debug("agent : " + agent.Name); + _logger?.LogDebug("agent : " + agent.Name); if (_getContextMenu) { @@ -1241,7 +1257,7 @@ private void Dispose(bool disposing) // Check to see if Dispose has already been called. if (!_disposed) { - Log.Verbose(); + _logger.LogTrace("Dispose"); if (disposing) { @@ -1304,24 +1320,24 @@ private bool isDialog(WindowActivityMonitorInfo monitorInfo) bool retVal = false; AutomationElement window = AutomationElement.FromHandle(monitorInfo.FgHwnd); - Log.Debug("controltype: " + window.Current.ControlType.ProgrammaticName); + _logger?.LogDebug("controltype: " + window.Current.ControlType.ProgrammaticName); if (Equals(window.Current.ControlType, ControlType.Menu)) { - Log.Debug("**** controltype: IT IS MENU"); + _logger?.LogDebug("**** controltype: IT IS MENU"); retVal = true; } else if (window.TryGetCurrentPattern(WindowPattern.Pattern, out object objPattern)) { var windowPattern = objPattern as WindowPattern; retVal = (!windowPattern.Current.CanMinimize && !windowPattern.Current.CanMaximize) || windowPattern.Current.IsModal; - Log.Debug("CanMinimize: " + windowPattern.Current.CanMinimize + ", canMaximize: " + windowPattern.Current.CanMaximize + ", isModal: " + windowPattern.Current.IsModal); - Log.Debug("retVal: " + retVal); + _logger?.LogDebug("CanMinimize: " + windowPattern.Current.CanMinimize + ", canMaximize: " + windowPattern.Current.CanMaximize + ", isModal: " + windowPattern.Current.IsModal); + _logger?.LogDebug("retVal: " + retVal); retVal = retVal && !Windows.IsMinimized(monitorInfo.FgHwnd); } - Log.Debug("returning " + retVal); + _logger?.LogDebug("returning " + retVal); return retVal; } @@ -1360,7 +1376,7 @@ private void keyboardActuator_EvtKeyDown(object sender, KeyEventArgs keyEventArg _currentEditingMode = EditingMode.Edit; } - Log.Debug("_currentEditingMode: " + _currentEditingMode); + _logger?.LogDebug("_currentEditingMode: " + _currentEditingMode); if (_currentAgent != null && _currentAgent.TextControlAgent != null) { @@ -1394,19 +1410,19 @@ private void keyboardActuator_EvtKeyUp(object sender, KeyEventArgs keyEventArgs) private bool notifyTextChanged(ITextControlAgent textInterface) { uint threadId = GetCurrentThreadId(); - Log.Debug("Entered notifyTextChanged: " + threadId); + _logger?.LogDebug("Entered notifyTextChanged: " + threadId); // Use the semaphore to see if this is blocked if (TextChangedNotifications.OnHold()) { - Log.Debug("NotificationsOnHold. Exit ThreadID: " + threadId); + _logger?.LogDebug("NotificationsOnHold. Exit ThreadID: " + threadId); return false; } // try to acquire a lock if (!tryLock(_syncTextChangeNotifyObj)) { - Log.Debug("_lock is true. returning on thread : " + threadId); + _logger?.LogDebug("_lock is true. returning on thread : " + threadId); return false; } @@ -1418,13 +1434,13 @@ private bool notifyTextChanged(ITextControlAgent textInterface) // the same thread trying to re-enter the function if (_notifyTextChangedLock) { - Log.Debug("REENTRANCY DETECTED. RETURNING"); + _logger?.LogDebug("REENTRANCY DETECTED. RETURNING"); return true; } if (textInterface != _textControlAgent) { - Log.Debug("event source is not the current agent. returning..."); + _logger?.LogDebug("event source is not the current agent. returning..."); return false; } @@ -1434,34 +1450,34 @@ private bool notifyTextChanged(ITextControlAgent textInterface) { if (EvtTextChanged != null) { - Log.Debug("Calling EvtTextChanged"); + _logger?.LogDebug("Calling EvtTextChanged"); EvtTextChanged(this, EventArgs.Empty); - Log.Debug("Returned from EvtTextChanged"); + _logger?.LogDebug("Returned from EvtTextChanged"); } else { - Log.Debug("EvtTextChanged is null"); + _logger?.LogDebug("EvtTextChanged is null"); } } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger?.LogError(ex.ToString()); } _notifyTextChangedLock = false; - Log.Debug("Exit End of function ThreadID: " + threadId); + _logger?.LogDebug("Exit End of function ThreadID: " + threadId); } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger?.LogError(ex.ToString()); } finally { release(_syncTextChangeNotifyObj); } - Log.Debug("Returning"); + _logger?.LogDebug("Returning"); return true; } @@ -1474,13 +1490,13 @@ private void onFocusChanged(WindowActivityMonitorInfo monitorInfo) { if (monitorInfo.FgHwnd == IntPtr.Zero) { - Log.Debug("hWnd is null"); + _logger?.LogDebug("hWnd is null"); return; } - //Log.Debug(monitorInfo.ToString()); + //_logger?.LogDebug(monitorInfo.ToString()); - //Log.Debug(" hwnd: " + hWnd + " Title: [" + title + "] process: " + process.ProcessName + + //_logger?.LogDebug(" hwnd: " + hWnd + " Title: [" + title + "] process: " + process.ProcessName + // ". focusedElement: [" + // ((focusedElement != null) ? focusedElement.Current.ClassName : "null") + "]"); @@ -1490,7 +1506,7 @@ private void onFocusChanged(WindowActivityMonitorInfo monitorInfo) { var functionalAgent = _currentAgent as IFunctionalAgent; - Log.Debug(_currentAgent.Name + ", IsActive: " + functionalAgent.IsActive + ", IsClosing: " + functionalAgent.IsClosing); + _logger?.LogDebug(_currentAgent.Name + ", IsActive: " + functionalAgent.IsActive + ", IsClosing: " + functionalAgent.IsClosing); if (functionalAgent.IsActive && !functionalAgent.IsClosing) { @@ -1516,7 +1532,7 @@ private void onFocusChanged(WindowActivityMonitorInfo monitorInfo) if (_currentAgent != null) { - Log.Debug("CurrentAgent is " + _currentAgent.GetType()); + _logger?.LogDebug("CurrentAgent is " + _currentAgent.GetType()); } if (EvtFocusChanged != null) @@ -1525,7 +1541,7 @@ private void onFocusChanged(WindowActivityMonitorInfo monitorInfo) } else { - Log.Debug("EVTFocusChanged is null!"); + _logger?.LogDebug("EVTFocusChanged is null!"); } } @@ -1541,7 +1557,7 @@ private void release(object sync) } catch (Exception ex) { - Log.Exception(ex); + _logger?.LogError(ex, ex.Message); } } @@ -1551,7 +1567,7 @@ private void release(object sync) /// sets the agent private void setAgent(IApplicationAgent agent) { - Log.Debug("Setting agent to " + ((agent != null) ? agent.Name : "null")); + _logger?.LogDebug("Setting agent to " + ((agent != null) ? agent.Name : "null")); _currentAgent = agent; } @@ -1564,31 +1580,31 @@ private void setAgent(IApplicationAgent agent) private void TextChangedNotifications_EvtUnlocked() { uint threadId = GetCurrentThreadId(); - Log.Debug("Enter ID. calling notifytextchanged on threadID: " + threadId); + _logger?.LogDebug("Enter ID. calling notifytextchanged on threadID: " + threadId); int ii = 0; while (true) { - Log.Debug("UNLOCKED! Calling NotifyTextChanged"); + _logger?.LogDebug("UNLOCKED! Calling NotifyTextChanged"); if (notifyTextChanged(_textControlAgent)) { - Log.Debug("Returned from NotifyTextChanged()"); + _logger?.LogDebug("Returned from NotifyTextChanged()"); break; } - Log.Debug("wait for _lock to release " + ii); + _logger?.LogDebug("wait for _lock to release " + ii); Application.DoEvents(); if (ii > 500) { - Log.Debug("TIMED OUT WAITING FOR LOCK"); + _logger?.LogDebug("TIMED OUT WAITING FOR LOCK"); break; } ii++; } - Log.Debug("Leave ThreadID: " + threadId); + _logger?.LogDebug("Leave ThreadID: " + threadId); } /// @@ -1600,10 +1616,10 @@ private void TextChangedNotifications_EvtUnlocked() /// panel request info private void triggerPanelRequest(object sender, PanelRequestEventArgs arg) { - Log.Debug("PanelClass: " + arg.PanelClass); + _logger?.LogDebug("PanelClass: " + arg.PanelClass); if (_panelChangeNotifications.OnHold()) { - Log.Debug("Panel change request paused. will not change panel"); + _logger?.LogDebug("Panel change request paused. will not change panel"); return; } @@ -1613,7 +1629,7 @@ private void triggerPanelRequest(object sender, PanelRequestEventArgs arg) } else { - Log.Debug("EvtPanelrequest is null"); + _logger?.LogDebug("EvtPanelrequest is null"); } } diff --git a/src/Libraries/ACATCore/AgentManagement/AgentUtils.cs b/src/Libraries/ACATCore/AgentManagement/AgentUtils.cs index b4f608b8..deeb2203 100644 --- a/src/Libraries/ACATCore/AgentManagement/AgentUtils.cs +++ b/src/Libraries/ACATCore/AgentManagement/AgentUtils.cs @@ -18,12 +18,7 @@ namespace ACAT.Core.AgentManagement /// public class AgentUtils { - private static ILogger _logger; - - public static void SetLogger(ILogger logger) - { - _logger = logger; - } + private static readonly ILogger _logger = LoggingConfiguration.CreateLogger(); /// /// Finds a descendent of the focused element that has the specified /// className, controlType and automationID @@ -350,8 +345,8 @@ public static bool IsElementOrAncestorByAutomationId(AutomationElement focusedEl while (parent != null) { - Log.Debug("parent.ClassName: " + parent.Current.ClassName + ", parent.COntrolType: " + - parent.Current.ControlType.ProgrammaticName + ", parent.AutoId: " + parent.Current.AutomationId); + _logger?.LogDebug("parent.ClassName: {ClassName}, parent.ControlType: {ControlType}, parent.AutoId: {AutoId}", + parent.Current.ClassName, parent.Current.ControlType.ProgrammaticName, parent.Current.AutomationId); if (String.Compare(parent.Current.ClassName, className, true) == 0 && String.Compare(parent.Current.ControlType.ProgrammaticName, controlType, true) == 0 && diff --git a/src/Libraries/ACATCore/AgentManagement/Agents/AgentsCache.cs b/src/Libraries/ACATCore/AgentManagement/Agents/AgentsCache.cs index 2622110a..90118f32 100644 --- a/src/Libraries/ACATCore/AgentManagement/Agents/AgentsCache.cs +++ b/src/Libraries/ACATCore/AgentManagement/Agents/AgentsCache.cs @@ -7,8 +7,11 @@ //////////////////////////////////////////////////////////////////////////// using ACAT.Core.AgentManagement.Interfaces; +using ACAT.Core.PanelManagement; using ACAT.Core.Utility; using ACAT.Core.Utility.TypeLoader; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; using System; using System.Collections; using System.Collections.Generic; @@ -26,6 +29,8 @@ namespace ACAT.Core.AgentManagement.Agents /// internal class AgentsCache : IDisposable { + private readonly ILogger _logger; + /// /// Adhoc agents are those that can be added at runtime. Adhoc /// agents are attached to a window handle and activated when that @@ -59,9 +64,10 @@ internal class AgentsCache : IDisposable /// /// Initializes a new instance of the class. /// - public AgentsCache() + public AgentsCache(ILogger logger = null) { - Log.Verbose(); + _logger = logger ?? LoggingConfiguration.CreateLogger(); + _logger?.LogTrace("AgentsCache created"); _agentCache = new List(); _agentLookupTableByProcessName = new Hashtable(); @@ -220,9 +226,12 @@ public IApplicationAgent GetAgent(Process process) /// Application agent object public IApplicationAgent GetAgentByCategory(string category) { + _logger?.LogDebug("GetAgentByCategory called for: {Category}. AgentCache count: {Count}", category, _agentCache.Count); + var retVal = _preferredAgents.GetPreferredAgentByCategory(category); if (retVal == null) { + _logger?.LogDebug("No preferred agent found for category {Category}, searching in cache", category); foreach (var agent in _agentCache) { if (string.Compare(category, agent.Descriptor.Category, true) == 0) @@ -233,6 +242,11 @@ public IApplicationAgent GetAgentByCategory(string category) } } + if (retVal == null) + { + _logger?.LogWarning("No agent found for category: {Category}", category); + } + return retVal; } @@ -243,9 +257,12 @@ public IApplicationAgent GetAgentByCategory(string category) /// Application agent object public IApplicationAgent GetAgentByName(string name) { + _logger?.LogDebug("GetAgentByName called for: {Name}. AgentCache count: {Count}", name, _agentCache.Count); + var retVal = _preferredAgents.GetPreferredAgentByName(name); if (retVal == null) { + _logger?.LogDebug("No preferred agent found for {Name}, searching in cache", name); foreach (var agent in _agentCache) { if (string.Compare(name, agent.Name, true) == 0) @@ -255,6 +272,15 @@ public IApplicationAgent GetAgentByName(string name) } } } + else + { + _logger?.LogDebug("Found preferred agent for {Name}: {AgentName}", name, retVal.Name); + } + + if (retVal == null) + { + _logger?.LogWarning("No agent found for name: {Name}", name); + } return retVal; } @@ -276,13 +302,16 @@ public IEnumerable GetExtensions() /// true on success public bool Init(IEnumerable extensionDirs) { - Log.Verbose(); + _logger?.LogTrace("Initializing AgentsCache"); loadCache(extensionDirs); + _logger?.LogDebug("Loaded {Count} agents into cache before loading preferred agents", _agentCache.Count); + _logger?.LogDebug("AgentLookupTableById has {Count} entries", _agentLookupTableById.Count); + _preferredAgents.Load(_agentLookupTableById); - Log.Debug("Done loading cache"); + _logger?.LogDebug("Done loading cache with {Count} total agents", _agentCache.Count); populateLookupTableByProcess(); @@ -318,8 +347,29 @@ private void addAgent(Type agentType) { try { - var agent = (IApplicationAgent)Activator.CreateInstance(agentType); - Log.Debug("Adding agent " + agentType.FullName); + IApplicationAgent agent = null; + + // Try to create instance using DI container first (if available) + if (Context.ServiceProvider != null) + { + try + { + agent = ActivatorUtilities.CreateInstance(Context.ServiceProvider, agentType) as IApplicationAgent; + _logger?.LogDebug("Adding agent {AgentType} with dependency injection", agentType.FullName); + } + catch + { + // DI creation failed, will try parameterless constructor + } + } + + // Fall back to parameterless constructor + if (agent == null) + { + agent = (IApplicationAgent)Activator.CreateInstance(agentType); + _logger?.LogDebug("Adding agent {AgentType} (parameterless constructor)", agentType.FullName); + } + _agentCache.Add(agent); _agentLookupTableById.Add(agent.Descriptor.Id, agent); @@ -329,7 +379,7 @@ private void addAgent(Type agentType) } catch (Exception ex) { - Log.Exception("Could not load agent " + agentType + ", exception: " + ex); + _logger?.LogError(ex, "Could not load agent {AgentType}", agentType); } } @@ -343,9 +393,11 @@ private void loadCache(IEnumerable extensionDirs) //TODO: Fix this hack foreach (string dir in extensionDirs) { + _logger?.LogDebug("Loading agents from directory: {Directory}", dir); loadAgentsFromDir(dir, "ACAT.Extensions.AppAgents.*.dll"); loadAgentsFromDir(dir, "ACAT.Extensions.FunctionalAgents.*.dll"); } + _logger?.LogDebug("TypeLoader has {Count} loaded types", _agentTypeLoader.LoadedTypes.Count); foreach (var agent in _agentTypeLoader.LoadedTypes) { addAgent(agent.Value); @@ -376,7 +428,7 @@ private void onAgentFound(string agentName) } catch (Exception ex) { - Log.Exception($"Error loading agent from {agentName}: {ex.Message}"); + _logger?.LogError(ex, "Error loading agent from {AgentName}", agentName); } } diff --git a/src/Libraries/ACATCore/AgentManagement/Agents/PreferredAgents.cs b/src/Libraries/ACATCore/AgentManagement/Agents/PreferredAgents.cs index e560092e..f791d152 100644 --- a/src/Libraries/ACATCore/AgentManagement/Agents/PreferredAgents.cs +++ b/src/Libraries/ACATCore/AgentManagement/Agents/PreferredAgents.cs @@ -8,6 +8,7 @@ using ACAT.Core.AgentManagement.Interfaces; using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Collections; using System.Diagnostics; @@ -36,6 +37,8 @@ namespace ACAT.Core.AgentManagement.Agents /// internal class PreferredAgents : IDisposable { + private readonly ILogger _logger; + /// /// Name of the preferences file /// @@ -51,7 +54,7 @@ internal class PreferredAgents : IDisposable /// public PreferredAgents() { - Log.Verbose(); + _logger = LoggingConfiguration.CreateLogger(); _preferredAgents = new Hashtable(); } @@ -193,7 +196,7 @@ public void Load(Hashtable agentsTable) } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex, "Exception loading preferred agents"); } } } diff --git a/src/Libraries/ACATCore/AgentManagement/FunctionalAgentBase.cs b/src/Libraries/ACATCore/AgentManagement/FunctionalAgentBase.cs index 92f3b6d6..3710b046 100644 --- a/src/Libraries/ACATCore/AgentManagement/FunctionalAgentBase.cs +++ b/src/Libraries/ACATCore/AgentManagement/FunctionalAgentBase.cs @@ -9,6 +9,7 @@ using ACAT.Core.PanelManagement.Common; using ACAT.Core.UserControlManagement.Interfaces; using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System.Threading; namespace ACAT.Core.AgentManagement @@ -21,7 +22,7 @@ public abstract class FunctionalAgentBase : GenericAppAgentBase, IFunctionalAgen /// /// Initializes a new instance of the class. /// - protected FunctionalAgentBase() + protected FunctionalAgentBase(ILogger logger = null) : base(logger) { CloseEvent = new AutoResetEvent(false); ExitCode = CompletionCode.None; diff --git a/src/Libraries/ACATCore/AgentManagement/GenericAppAgentBase.cs b/src/Libraries/ACATCore/AgentManagement/GenericAppAgentBase.cs index b6df6013..76e1400c 100644 --- a/src/Libraries/ACATCore/AgentManagement/GenericAppAgentBase.cs +++ b/src/Libraries/ACATCore/AgentManagement/GenericAppAgentBase.cs @@ -23,13 +23,17 @@ namespace ACAT.Core.AgentManagement /// public abstract class GenericAppAgentBase : AgentBase { + protected GenericAppAgentBase(ILogger logger = null) : base(logger ?? LoggingConfiguration.CreateLogger()) + { + } + /// /// Gets or sets the text control agent object /// protected TextControlAgentBase appTextInterface { get; set; } /// - /// Implement this to display a contexutal menu for + /// Implement this to display a contextual menu for /// the currently active process /// /// Info about the active process/window @@ -155,7 +159,7 @@ private TextControlAgentBase createEditControlTextInterface( private void disposeAndCreateTextInterface(WindowActivityMonitorInfo monitorInfo) { disposeTextInterface(); - Log.Debug("Calling createEditControlTextInterface"); + _logger.LogDebug("Calling createEditControlTextInterface"); var textInterface = createEditControlTextInterface(monitorInfo.FgHwnd, monitorInfo.FocusedElement) ?? createKeyLoggerTextInterface(monitorInfo.FgHwnd, monitorInfo.FocusedElement); diff --git a/src/Libraries/ACATCore/AgentManagement/Keyboard.cs b/src/Libraries/ACATCore/AgentManagement/Keyboard.cs index debd8194..a8499b18 100644 --- a/src/Libraries/ACATCore/AgentManagement/Keyboard.cs +++ b/src/Libraries/ACATCore/AgentManagement/Keyboard.cs @@ -143,7 +143,7 @@ public void Send(Keys extendedKey, int count) } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, "Error sending extended key"); } finally { @@ -290,7 +290,7 @@ public void Send(String str) } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, "Error sending string"); } finally { @@ -307,7 +307,7 @@ protected virtual void Dispose(bool disposing) // Check to see if Dispose has already been called. if (!_disposed) { - Log.Verbose(); + _logger.LogTrace("Disposing Keyboard"); if (disposing) { @@ -369,7 +369,7 @@ private void sendChar(char ch) private bool shiftNeeded(char c) { short virtualKey = User32Interop.VkKeyScanEx(c, _keyboardLayout); - Log.Debug("virtualKey for [" + c + "] is " + virtualKey); + _logger.LogDebug("virtualKey for [{Char}] is {VirtualKey}", c, virtualKey); if ((virtualKey & 0x100) == 0x100) { _logger.LogDebug("Shift needs to be pressed for [{Char}]", c); diff --git a/src/Libraries/ACATCore/AgentManagement/NullAgent.cs b/src/Libraries/ACATCore/AgentManagement/NullAgent.cs index d9bb3364..f058e165 100644 --- a/src/Libraries/ACATCore/AgentManagement/NullAgent.cs +++ b/src/Libraries/ACATCore/AgentManagement/NullAgent.cs @@ -22,6 +22,10 @@ namespace ACAT.Core.AgentManagement "No-op agent")] public class NullAgent : AgentBase { + public NullAgent() : base(LoggingConfiguration.CreateLogger()) + { + } + /// /// The text interface /// @@ -47,8 +51,6 @@ public override void OnContextMenuRequest(WindowActivityMonitorInfo monitorInfo) /// set to true if handled public override void OnFocusChanged(WindowActivityMonitorInfo monitorInfo, ref bool handled) { - Log.Verbose(); - setTextInterface(_textInterface); handled = true; diff --git a/src/Libraries/ACATCore/AgentManagement/TextControlAgents/EditTextControlAgent.cs b/src/Libraries/ACATCore/AgentManagement/TextControlAgents/EditTextControlAgent.cs index f1963b14..77a9edf1 100644 --- a/src/Libraries/ACATCore/AgentManagement/TextControlAgents/EditTextControlAgent.cs +++ b/src/Libraries/ACATCore/AgentManagement/TextControlAgents/EditTextControlAgent.cs @@ -9,6 +9,7 @@ using System; using System.Windows.Automation; using System.Windows.Forms; +using Microsoft.Extensions.Logging; namespace ACAT.Core.AgentManagement.TextControlAgents { @@ -22,6 +23,8 @@ namespace ACAT.Core.AgentManagement.TextControlAgents /// public class EditTextControlAgent : TextControlAgentBase { + private static ILogger _logger => LogManager.GetLogger(); + /// /// Handle of the active target window (eg the Notepad window) /// @@ -209,7 +212,7 @@ private void onTextChanged(object sender, AutomationEventArgs e) triggerTextChanged(this); CoreGlobals.Stopwatch2.Stop(); - Log.Debug("onTextChanged() TimeElapsed: " + CoreGlobals.Stopwatch2.ElapsedMilliseconds); + _logger?.LogDebug("onTextChanged() TimeElapsed: {ElapsedMs}ms", CoreGlobals.Stopwatch2.ElapsedMilliseconds); } /// @@ -227,7 +230,7 @@ private bool trackTextChanges(IntPtr handleMainWindow, AutomationElement textEle if (!retVal) { - Log.Debug("Text element is null"); + _logger?.LogDebug("Text element is null"); return false; } @@ -244,7 +247,7 @@ private bool trackTextChanges(IntPtr handleMainWindow, AutomationElement textEle AutomationEventManager.RemoveAutomationEventHandler(handleMainWindow, TextPattern.TextSelectionChangedEvent, textElement); - Log.Debug("Adding onTextChanged event handler"); + _logger?.LogDebug("Adding onTextChanged event handler"); AutomationEventManager.AddAutomationEventHandler(handleMainWindow, TextPattern.TextSelectionChangedEvent, textElement, @@ -252,13 +255,13 @@ private bool trackTextChanges(IntPtr handleMainWindow, AutomationElement textEle if (nativeHandle == 0) { - Log.Debug("handle is zero"); + _logger?.LogDebug("handle is zero"); retVal = false; } } else { - Log.Debug("Focused element does not support textpattern"); + _logger?.LogDebug("Focused element does not support textpattern"); retVal = false; } } @@ -267,7 +270,7 @@ private bool trackTextChanges(IntPtr handleMainWindow, AutomationElement textEle // exception can be thrown by AddAutomationEventHandler to the effect that // WindowClosed event can only be attached to top level windows. // For instance, the "Start" menu would throw this exception. - Log.Exception(ex.ToString()); + _logger?.LogError(ex, "Exception tracking text changes"); retVal = false; } diff --git a/src/Libraries/ACATCore/AgentManagement/TextControlAgents/KeyLogTextControlAgent.cs b/src/Libraries/ACATCore/AgentManagement/TextControlAgents/KeyLogTextControlAgent.cs index 17479fdd..3fc68261 100644 --- a/src/Libraries/ACATCore/AgentManagement/TextControlAgents/KeyLogTextControlAgent.cs +++ b/src/Libraries/ACATCore/AgentManagement/TextControlAgents/KeyLogTextControlAgent.cs @@ -6,6 +6,7 @@ //////////////////////////////////////////////////////////////////////////// using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Windows.Forms; @@ -20,6 +21,8 @@ namespace ACAT.Core.AgentManagement.TextControlAgents /// public class KeyLogTextControlAgent : TextControlAgentBase { + private static ILogger _logger => LogManager.GetLogger(); + /// /// Windows constant /// @@ -83,7 +86,7 @@ public override void ClearText() /// caret position public override int GetCaretPos() { - Log.Verbose(); + _logger?.LogTrace("Getting caret position"); if (isValid(_textBox)) { return Windows.GetCaretPosition(_textBox); @@ -178,8 +181,8 @@ public override void OnKeyDown(KeyEventArgs e) break; } - Log.Debug("Keycode: " + e.KeyCode + - ", cursor: " + (_textBox != null ? _textBox.SelectionStart.ToString() : "-1")); + _logger?.LogDebug("Keycode: {KeyCode}, cursor: {Cursor}", e.KeyCode, + (_textBox != null ? _textBox.SelectionStart.ToString() : "-1")); } /// @@ -197,7 +200,7 @@ public override void OnKeyUp(KeyEventArgs e) if (_textBox != null) { - Log.Debug("keyup: " + e.KeyCode); + _logger?.LogDebug("keyup: {KeyCode}", e.KeyCode); switch (e.KeyCode) { @@ -313,7 +316,7 @@ protected override void OnDispose() /// arg private void _textBox_TextChanged(object sender, EventArgs e) { - Log.Verbose(); + _logger?.LogTrace("TextBox text changed"); onTextChanged(); } @@ -325,7 +328,7 @@ private void createTextBox() if (_textBox == null) { var name = string.Format("NullAgent_TB_" + _textBoxNameCounter++); - Log.Debug("Creating textbox window " + name); + _logger?.LogDebug("Creating textbox window {Name}", name); _textBox = new TextBox { Name = name, Multiline = true }; _textBox.TextChanged += _textBox_TextChanged; } @@ -340,7 +343,7 @@ private void createTextBox() /// private void disposeTextInterface() { - Log.Verbose(); + _logger?.LogTrace("Disposing text interface"); if (isValid(_textBox)) { _textBox.TextChanged -= _textBox_TextChanged; @@ -367,9 +370,8 @@ private void onTextChanged() { if (_textBox != null) { - Log.Debug("textbox changed. Name: " + _textBox.Name + - ", caretPos = " + _textBox.SelectionStart + - ", _textBox: " + (_textBox == null ? "null" : _textBox.Text)); + _logger?.LogDebug("textbox changed. Name: {Name}, caretPos: {CaretPos}, text: {Text}", + _textBox.Name, _textBox.SelectionStart, _textBox.Text); } triggerTextChanged(this); diff --git a/src/Libraries/ACATCore/AgentManagement/TextControlAgents/TextControlAgentBase.cs b/src/Libraries/ACATCore/AgentManagement/TextControlAgents/TextControlAgentBase.cs index 5bcdf843..8a89ef54 100644 --- a/src/Libraries/ACATCore/AgentManagement/TextControlAgents/TextControlAgentBase.cs +++ b/src/Libraries/ACATCore/AgentManagement/TextControlAgents/TextControlAgentBase.cs @@ -10,6 +10,7 @@ using ACAT.Core.Utility; using ACAT.Core.WordPredictorManagement; using ACAT.Core.WordPredictorManagement.Interfaces; +using Microsoft.Extensions.Logging; using System; using System.Linq; using System.Text; @@ -28,7 +29,12 @@ public class TextControlAgentBase : ITextControlAgent /// Keyboard interface to send keystrokes to the target /// text window /// - private static readonly Keyboard _keyboard = new(); + private static readonly Keyboard _keyboard = new(LoggingConfiguration.CreateLogger()); + + /// + /// Logger for the class + /// + private readonly ILogger _logger; /// /// Text manipulation features supported by the base class @@ -79,8 +85,9 @@ public class TextControlAgentBase : ITextControlAgent /// /// Initializes a new instance of the class /// - public TextControlAgentBase() + public TextControlAgentBase(ILogger logger = null) { + _logger = logger; _selectMode = false; Context.AppAgentMgr.EvtNonScannerMouseDown += AppAgentMgr_EvtNonScannerMouseDown; } @@ -168,7 +175,7 @@ public virtual void Delete(int offset, int count) { AgentManager.Instance.TextChangedNotifications.Hold(); - Log.Debug("offset: " + offset + ", count: " + count); + _logger?.LogDebug("offset: {Offset}, count: {Count}", offset, count); SetCaretPos(offset + count); int ii = offset + count; @@ -180,7 +187,7 @@ public virtual void Delete(int offset, int count) } catch (Exception ex) { - Log.Exception(ex); + _logger?.LogError(ex, ex.Message); } finally { @@ -554,7 +561,7 @@ public virtual bool GetCharLeftOfCaret(out char value) } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger?.LogError(ex.ToString()); value = '\0'; } @@ -637,7 +644,7 @@ public virtual void GetPrefixAndWordAtCaret(out string prefix, out string word) string text = GetText(); int caretPos = GetCaretPos(); ////Log.Debug("**** text: [" + text + "], caretPos: " + caretPos); - Log.Debug("caretPos: " + caretPos); + _logger?.LogDebug("caretPos: {CaretPos}", caretPos); TextUtils.GetPrefixAndWordAtCaret(text, caretPos, out prefix, out word); } @@ -867,7 +874,7 @@ public virtual void Insert(int offset, string word) } catch (Exception ex) { - Log.Exception(ex); + _logger?.LogError(ex, ex.Message); } finally { @@ -980,7 +987,7 @@ public virtual bool Redo() /// Word to insert at the 'offset' public virtual void Replace(int offset, int count, string word) { - Log.Debug("HARRIS offset = " + offset + " count " + count + " word " + word); + _logger?.LogDebug("HARRIS offset = {Offset} count {Count} word {Word}", offset, count, word); try { @@ -996,7 +1003,7 @@ public virtual void Replace(int offset, int count, string word) Keyboard.Send(Keys.Delete); } - Log.Debug("HARRIS Sending back"); + _logger?.LogDebug("HARRIS Sending back"); SendKeys.SendWait("{BACKSPACE " + count + "}"); @@ -1005,13 +1012,13 @@ public virtual void Replace(int offset, int count, string word) word = word.ToUpper(); } - Log.Debug("Sending word " + word); + _logger?.LogDebug("Sending word {Word}", word); sendWait(word); } catch (Exception ex) { - Log.Exception(ex); + _logger?.LogError(ex, ex.Message); } finally { @@ -1211,7 +1218,7 @@ protected int GetCaretPos(IntPtr handleText) } catch (Exception e) { - Log.Exception(e); + _logger?.LogError(e, e.Message); } return caretPos; @@ -1274,7 +1281,7 @@ protected string GetSelectedText(IntPtr handleText) } catch (Exception e) { - Log.Exception(e); + _logger?.LogError(e, e.Message); } return selectedText; @@ -1288,7 +1295,7 @@ protected string GetText(IntPtr handleText) { string str = string.Empty; - Log.Verbose(); + _logger?.LogDebug("GetText called"); if (handleText == IntPtr.Zero) { @@ -1301,7 +1308,7 @@ protected string GetText(IntPtr handleText) } catch (Exception e) { - Log.Exception(e); + _logger?.LogError(e, e.Message); } return str; @@ -1314,7 +1321,7 @@ protected string GetText(IntPtr handleText) /// protected void learn() { - Log.Verbose(); + _logger?.LogDebug("learn called"); if (!WordPredictionManager.Instance.ActiveWordPredictor.SupportsLearning) { @@ -1325,11 +1332,11 @@ protected void learn() var trimmed = str.Trim(); if (string.IsNullOrEmpty(trimmed)) { - Log.Debug("Nothing to learn. sentence is empty"); + _logger?.LogDebug("Nothing to learn. sentence is empty"); return; } - Log.Debug("Learn : [" + trimmed + "]"); + _logger?.LogDebug("Learn : [{Trimmed}]", trimmed); WordPredictionManager.Instance.ActiveWordPredictor.Learn(trimmed, WordPredictorMessageTypes.None); } @@ -1370,7 +1377,7 @@ protected bool SetCaretPos(IntPtr handleText, int pos) } catch (Exception e) { - Log.Exception(e); + _logger?.LogError(e, e.Message); } return true; @@ -1384,7 +1391,7 @@ protected bool SetFocus(IntPtr handleText) { int ret = 0; - Log.Verbose(); + _logger?.LogDebug("SetFocus called"); if (handleText == IntPtr.Zero) { @@ -1397,7 +1404,7 @@ protected bool SetFocus(IntPtr handleText) } catch (Exception e) { - Log.Exception(e); + _logger?.LogError(e, e.Message); } return ret != 0; @@ -1457,7 +1464,7 @@ private void dispose(bool disposing) { if (!_disposed) { - Log.Verbose(); + _logger?.LogDebug("dispose called"); if (disposing) { diff --git a/src/Libraries/ACATCore/AgentManagement/UnsupportedAppAgent.cs b/src/Libraries/ACATCore/AgentManagement/UnsupportedAppAgent.cs index 8fb71896..fe750fe1 100644 --- a/src/Libraries/ACATCore/AgentManagement/UnsupportedAppAgent.cs +++ b/src/Libraries/ACATCore/AgentManagement/UnsupportedAppAgent.cs @@ -7,6 +7,7 @@ using ACAT.Core.PanelManagement.Common; using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; @@ -77,7 +78,7 @@ public override void OnContextMenuRequest(WindowActivityMonitorInfo monitorInfo) /// true if handled public override void OnFocusChanged(WindowActivityMonitorInfo monitorInfo, ref bool handled) { - Log.Verbose(); + _logger.LogDebug("OnFocusChanged"); if (ignoreApp(monitorInfo.FgProcess.ProcessName)) { @@ -86,7 +87,7 @@ public override void OnFocusChanged(WindowActivityMonitorInfo monitorInfo, ref b } base.OnFocusChanged(monitorInfo, ref handled); - Log.Debug("IsNew: " + monitorInfo.IsNewWindow + ", scannerShown: " + scannerShown); + _logger.LogDebug("IsNew: {IsNewWindow}, scannerShown: {ScannerShown}", monitorInfo.IsNewWindow, scannerShown); if (monitorInfo.IsNewWindow || !scannerShown) { showPanel(this, new PanelRequestEventArgs(PanelClasses.Alphabet, monitorInfo)); diff --git a/src/Libraries/ACATCore/AnimationManagement/Animation.cs b/src/Libraries/ACATCore/AnimationManagement/Animation.cs index 9e25cad1..af7df28a 100644 --- a/src/Libraries/ACATCore/AnimationManagement/Animation.cs +++ b/src/Libraries/ACATCore/AnimationManagement/Animation.cs @@ -8,6 +8,7 @@ using ACAT.Core.Interpreter; using ACAT.Core.Utility; using ACAT.Core.WidgetManagement; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; @@ -26,6 +27,8 @@ namespace ACAT.Core.AnimationManagement /// public class Animation : IDisposable { + private static ILogger _logger => LogManager.GetLogger(); + /// /// Code to execute when the animation sequence ends without the /// user having selected anything during the sequence @@ -241,7 +244,7 @@ internal void ResolveUIWidgetsReferences(Widget rootWidget, Variables variables) { clearAnimationWidgetList(); - Log.Verbose(rootWidget.Name + ". widgetXMLNodeList count: " + _widgetXMLNodeList.Count); + _logger?.LogTrace("{RootWidgetName}. widgetXMLNodeList count: {Count}", rootWidget.Name, _widgetXMLNodeList.Count); foreach (XmlNode xmlNode in _widgetXMLNodeList) { @@ -259,7 +262,7 @@ protected virtual void Dispose(bool disposing) // Check to see if Dispose has already been called. if (!_disposed) { - Log.Verbose(); + _logger?.LogTrace("Disposing Animation"); if (disposing) { @@ -421,22 +424,22 @@ private void resolveNonWildCardReferences(Widget rootWidget, Variables variables { var name = XmlUtils.GetXMLAttrString(xmlNode, "name"); - Log.Verbose("name=" + name); + _logger?.LogTrace("name={Name}", name); if (!String.IsNullOrEmpty(name) && !name.Contains("*")) { var widgetName = resolveName(variables, name); - Log.Verbose("Resolved name : " + widgetName); + _logger?.LogTrace("Resolved name: {WidgetName}", widgetName); var uiWidget = rootWidget.Finder.FindChild(widgetName); if (uiWidget != null && (uiWidget.UIControl == null || uiWidget.Visible)) { - Log.Verbose("Found child name : " + widgetName); + _logger?.LogTrace("Found child name: {WidgetName}", widgetName); var animationWidget = createAndAddAnimationWidget(uiWidget); animationWidget?.Load(xmlNode); } else { - Log.Debug("Did not find child " + widgetName); + _logger?.LogDebug("Did not find child {WidgetName}", widgetName); } } @@ -458,12 +461,12 @@ private void resolveWildCardReferences(Widget rootWidget, Variables variables, X if (name.Contains("*")) { - Log.Debug("name=" + name); + _logger?.LogDebug("name={Name}", name); var containerWidget = getContainerWidget(rootWidget, variables, name); if (containerWidget != null) { - Log.Debug("containerWidget: " + containerWidget.Name); + _logger?.LogDebug("containerWidget: {ContainerWidgetName}", containerWidget.Name); EvtResolveWidgetChildren?.Invoke(this, new ResolveWidgetChildrenEventArgs(rootWidget, containerWidget, xmlNode)); @@ -471,7 +474,7 @@ private void resolveWildCardReferences(Widget rootWidget, Variables variables, X { if (childWidget.UIControl == null || childWidget.Visible) { - Log.Debug("Found child name : " + childWidget.Name); + _logger?.LogDebug("Found child name: {ChildWidgetName}", childWidget.Name); var animationWidget = createAndAddAnimationWidget(childWidget); animationWidget?.Load(xmlNode); } diff --git a/src/Libraries/ACATCore/AnimationManagement/AnimationManager.cs b/src/Libraries/ACATCore/AnimationManagement/AnimationManager.cs index 2ead59ec..7512e0a8 100644 --- a/src/Libraries/ACATCore/AnimationManagement/AnimationManager.cs +++ b/src/Libraries/ACATCore/AnimationManagement/AnimationManager.cs @@ -5,6 +5,7 @@ using ACAT.Core.Utility; using ACAT.Core.WidgetManagement; using ACAT.Core.WidgetManagement.Interfaces; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Media; @@ -86,6 +87,8 @@ namespace ACAT.Core.AnimationManagement { public partial class AnimationManager : IAnimationManager, IDisposable { + private static readonly ILogger _logger = LoggingConfiguration.CreateLogger(); + /// /// Collection of animations for this panel /// @@ -381,16 +384,16 @@ public void Stop() { if (_player != null) { - Log.Verbose("Before animation player stop"); + _logger.LogTrace("Before animation player stop"); try { _player.Stop(); } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex, ex.Message); } - Log.Verbose("After animation player stop"); + _logger.LogTrace("After animation player stop"); } } @@ -407,7 +410,7 @@ public void Transition(Animation animation = null) { if (animation != null) { - Log.Verbose("Transition( " + animation.Name + "). _currentPanel: " + _currentPanel.Name); + _logger.LogTrace("Transition( {AnimationName}). _currentPanel: {PanelName}", animation.Name, _currentPanel.Name); _player.Transition(animation); } else @@ -422,7 +425,7 @@ public void Transition(Animation animation = null) } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex, ex.Message); } } @@ -436,7 +439,7 @@ protected void Dispose(bool disposing) // Check to see if Dispose has already been called. if (!_disposed) { - Log.Verbose(); + _logger.LogTrace(""); if (disposing) { @@ -483,7 +486,7 @@ protected virtual void actuatorManager_EvtSwitchDown(object sender, ActuatorSwit var widget = _player.HighlightedAnimationWidget; if (widget != null) { - Log.Verbose("Highlighted widget: " + widget.UIWidget.Name); + _logger.LogTrace("Highlighted widget: {WidgetName}", widget.UIWidget.Name); _switchDownHighlightedWidget = widget; } else @@ -567,13 +570,13 @@ protected void AppInterpreter_EvtActuateNotify(object sender, InterpreterEventA var widget = _currentPanel.Finder.FindChild(widgetName); if (widget != null) { - Log.Info("Actuate. widgetname: " + widget.Name + " Text: " + widget.GetText()); + _logger.LogInformation("Actuate. widgetname: {WidgetName} Text: {Text}", widget.Name, widget.GetText()); widget.Actuate(); } else { - Log.Warn("Did not actuate. Could not find widget " + widgetName); + _logger.LogWarning("Did not actuate. Could not find widget {WidgetName}", widgetName); } } } @@ -623,7 +626,7 @@ protected void AppInterpreter_EvtHighlightSelectedNotify(object sender, Interpre String widgetName = resolvedArgs[0]; - Log.Verbose("_currentPanel " + _currentPanel.Name + " widgetname: " + widgetName); + _logger.LogTrace("_currentPanel {PanelName} widgetname: {WidgetName}", _currentPanel.Name, widgetName); var widget = _currentPanel.Finder.FindChild(widgetName); if (widget != null) { @@ -672,13 +675,13 @@ protected void AppInterpreter_EvtStop(object sender, InterpreterEventArgs e) /// Argument list protected void AppInterpreter_EvtTransitionNotify(object sender, InterpreterEventArgs e) { - Log.Verbose(); + _logger.LogTrace(""); List resolvedArgs = ResolveArgs(e.Args); if (resolvedArgs.Count > 0) { String targetAnimation = resolvedArgs[0]; - Log.Verbose(targetAnimation); + _logger.LogTrace("{TargetAnimation}", targetAnimation); //Transition(GetAnimation(targetAnimation)); TransitionFromName(targetAnimation); } @@ -834,7 +837,7 @@ protected void playBeep(IActuatorSwitch switchObj) } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, ex.Message); } } @@ -851,7 +854,7 @@ protected void playDefaultBeep() } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, ex.Message); } } diff --git a/src/Libraries/ACATCore/AnimationManagement/AnimationPlayer.cs b/src/Libraries/ACATCore/AnimationManagement/AnimationPlayer.cs index f9536c35..bc2c48a7 100644 --- a/src/Libraries/ACATCore/AnimationManagement/AnimationPlayer.cs +++ b/src/Libraries/ACATCore/AnimationManagement/AnimationPlayer.cs @@ -12,6 +12,7 @@ using ACAT.Core.Utility; using ACAT.Core.WidgetManagement; using ACAT.Core.Widgets; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; @@ -66,6 +67,8 @@ public enum PlayerState /// internal class AnimationPlayer : IDisposable { + private readonly ILogger _logger; + /// /// Interpreter to interpret animation code /// @@ -169,7 +172,8 @@ internal class AnimationPlayer : IDisposable /// variables and their values public AnimationPlayer(Widget rootWidget, Interpret interpreter, Variables variables) { - Log.Verbose("CTOR(" + rootWidget.Name + ")"); + _logger = LoggingConfiguration.CreateLogger(); + _logger.LogTrace("CTOR(" + rootWidget.Name + ")"); if (rootWidget.UIControl is IPanel) { _syncObj = ((IPanel)rootWidget.UIControl).SyncObj; @@ -327,12 +331,12 @@ public void HighlightDefaultHome() /// public void Interrupt() { - Log.Verbose("Interrupt(" + _rootWidget.Name + ")"); + _logger.LogTrace("Interrupt(" + _rootWidget.Name + ")"); if (_timer != null && (_playerState == PlayerState.Running || _playerState == PlayerState.Timeout)) { - Log.Verbose("Interrupt timer for panel " + _rootWidget.Name); + _logger.LogTrace("Interrupt timer for panel " + _rootWidget.Name); _timer.Stop(); setPlayerState(PlayerState.Interrupted); @@ -375,14 +379,14 @@ public void ManualScanActuateWidget(Widget widget) /// public void Pause() { - Log.Verbose("Pause(" + _rootWidget.Name + ")"); + _logger.LogTrace("Pause(" + _rootWidget.Name + ")"); if (_timer != null && (_playerState == PlayerState.Running || _playerState == PlayerState.Timeout || _playerState == PlayerState.Interrupted)) { - Log.Verbose("AP1: Stop timer for panel " + _rootWidget.Name); + _logger.LogTrace("AP1: Stop timer for panel " + _rootWidget.Name); _timer.Stop(); @@ -398,21 +402,21 @@ public void Pause() /// transition to this animation public void Resume(Animation animation = null) { - Log.Verbose("Resume(" + _rootWidget.Name + ") +, state: " + _playerState); + _logger.LogTrace("Resume(" + _rootWidget.Name + ") +, state: " + _playerState); if ((_playerState == PlayerState.Paused || _playerState == PlayerState.Timeout || _playerState == PlayerState.Interrupted) && _timer != null) { - Log.Verbose("Resume(" + _rootWidget.Name + ") Setting player state to running"); + _logger.LogTrace("Resume(" + _rootWidget.Name + ") Setting player state to running"); setPlayerState(PlayerState.Running); if (!CoreGlobals.AppPreferences.EnableManualScan) { if (animation != null) { - Log.Verbose("In Resume Calling Transition"); + _logger.LogTrace("In Resume Calling Transition"); Transition(animation); } } @@ -430,25 +434,25 @@ public void Stop() { if (_timer == null) { - Log.Verbose("_heartbeatTimer is null"); + _logger.LogTrace("_heartbeatTimer is null"); return; } _timer.Elapsed -= timer_Elapsed; - Log.Verbose("Inside stopthread. before enter " + _rootWidget.UIControl.Name); + _logger.LogTrace("Inside stopthread. before enter " + _rootWidget.UIControl.Name); tryEnterUntilSuccess(_transitionSync); - Log.Verbose("Inside stopthread. after enter " + _rootWidget.UIControl.Name); + _logger.LogTrace("Inside stopthread. after enter " + _rootWidget.UIControl.Name); _timer.Stop(); - Log.Verbose("Inside stopthread. before exit" + _rootWidget.UIControl.Name); + _logger.LogTrace("Inside stopthread. before exit" + _rootWidget.UIControl.Name); Monitor.Exit(_transitionSync); - Log.Verbose("Inside stopthread. after exit" + _rootWidget.UIControl.Name); + _logger.LogTrace("Inside stopthread. after exit" + _rootWidget.UIControl.Name); - Log.Verbose("Stop" + _rootWidget.UIControl.Name + ", syncobj.status " + _syncObj.Status + ", intimer: " + _inTimer); + _logger.LogTrace("Stop" + _rootWidget.UIControl.Name + ", syncobj.status " + _syncObj.Status + ", intimer: " + _inTimer); setPlayerState(PlayerState.Stopped); _timer.Dispose(); @@ -464,7 +468,7 @@ public void Transition(Animation animation = null) { if (_syncObj == null) { - Log.Verbose("_syncObj is null. returning"); + _logger.LogTrace("_syncObj is null. returning"); return; } @@ -478,18 +482,18 @@ public void Transition(Animation animation = null) if (animation != null) { - Log.Verbose("Transition to " + animation.Name); + _logger.LogTrace("Transition to " + animation.Name); } setPlayerState(PlayerState.Stopped); - Log.Verbose("Transition : Before Enter " + _rootWidget.UIControl.Name + ", threadid: " + Kernel32Interop.GetCurrentThreadId()); + _logger.LogTrace("Transition : Before Enter " + _rootWidget.UIControl.Name + ", threadid: " + Kernel32Interop.GetCurrentThreadId()); tryEnterUntilSuccess(_transitionSync); - Log.Verbose("Transition : After Enter " + _rootWidget.UIControl.Name + ", status: " + _syncObj.Status); + _logger.LogTrace("Transition : After Enter " + _rootWidget.UIControl.Name + ", status: " + _syncObj.Status); if (_syncObj.IsClosing()) { - Log.Verbose("FORM IS CLOSING. releasing _transitionSync and returning" + _rootWidget.UIControl.Name); + _logger.LogTrace("FORM IS CLOSING. releasing _transitionSync and returning" + _rootWidget.UIControl.Name); release(_transitionSync); return; } @@ -514,11 +518,11 @@ public void Transition(Animation animation = null) _currentWidgetIndex = getFirstAnimatedWidget(); _highlightedAnimationWidget = null; - Log.Verbose("Transition : Before Release " + _rootWidget.UIControl.Name); + _logger.LogTrace("Transition : Before Release " + _rootWidget.UIControl.Name); release(_transitionSync); - Log.Verbose("Transition : After Release " + _rootWidget.UIControl.Name); + _logger.LogTrace("Transition : After Release " + _rootWidget.UIControl.Name); - Log.Verbose("Start new animation " + animation.Name); + _logger.LogTrace("Start new animation " + animation.Name); if (!animation.AutoStart && animation.OnStart) { @@ -537,17 +541,17 @@ public void Transition(Animation animation = null) } */ _timer.Interval = _currentAnimation.SteppingTime; - Log.Verbose(_rootWidget.UIControl.Name + ", syncobj.status " + _syncObj.Status); + _logger.LogTrace(_rootWidget.UIControl.Name + ", syncobj.status " + _syncObj.Status); if (_syncObj.Status == SyncLock.StatusValues.None) { timer_Elapsed(null, null); - Log.Verbose("Starting timer " + _rootWidget.UIControl.Name); + _logger.LogTrace("Starting timer " + _rootWidget.UIControl.Name); _timer.Start(); } else { - Log.Verbose("******** WILL NOT START TIMER!!!" + + _logger.LogTrace("******** WILL NOT START TIMER!!!" + _rootWidget.UIControl.Name + ", syncobj.status " + _syncObj.Status); } @@ -557,10 +561,10 @@ public void Transition(Animation animation = null) } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex.ToString()); } - Log.Verbose("Returning"); + _logger.LogTrace("Returning"); } /// @@ -571,7 +575,7 @@ public void TransitionManualScan(ManualScanModes manualScanMode = ManualScanMode { if (_syncObj == null) { - Log.Verbose("_syncObj is null. returning"); + _logger.LogTrace("_syncObj is null. returning"); return; } @@ -602,9 +606,9 @@ public void TransitionManualScan(ManualScanModes manualScanMode = ManualScanMode _delayedSelect = false; _delayedSelect2 = false; - Log.Verbose("manualScanMode is " + manualScanMode); + _logger.LogTrace("manualScanMode is " + manualScanMode); - Log.Verbose(_playerState + ", " + _manualScanMode); + _logger.LogTrace(_playerState + ", " + _manualScanMode); if (_playerState == PlayerState.Running) { if (checkStopManualAutoScan(manualScanMode)) @@ -625,20 +629,20 @@ public void TransitionManualScan(ManualScanModes manualScanMode = ManualScanMode setPlayerState(PlayerState.Stopped); - Log.Verbose("Transition : Before Enter " + _rootWidget.UIControl.Name + ", threadid: " + Kernel32Interop.GetCurrentThreadId()); + _logger.LogTrace("Transition : Before Enter " + _rootWidget.UIControl.Name + ", threadid: " + Kernel32Interop.GetCurrentThreadId()); tryEnterUntilSuccess(_transitionSync); - Log.Verbose("Transition : After Enter " + _rootWidget.UIControl.Name + ", status: " + _syncObj.Status); + _logger.LogTrace("Transition : After Enter " + _rootWidget.UIControl.Name + ", status: " + _syncObj.Status); if (_syncObj.IsClosing()) { - Log.Verbose("FORM IS CLOSING. releasing _transitionSync and returning" + _rootWidget.UIControl.Name); + _logger.LogTrace("FORM IS CLOSING. releasing _transitionSync and returning" + _rootWidget.UIControl.Name); release(_transitionSync); return; } if (_highlightedWidget == null) { - Log.Verbose("_highlightedWidget is null"); + _logger.LogTrace("_highlightedWidget is null"); HighlightDefaultHome(); } @@ -671,10 +675,10 @@ public void TransitionManualScan(ManualScanModes manualScanMode = ManualScanMode bool handled = handleSingleMove(); - Log.Verbose("Transition : Before Release " + _rootWidget.UIControl.Name); + _logger.LogTrace("Transition : Before Release " + _rootWidget.UIControl.Name); release(_transitionSync); - Log.Verbose("Transition : After Release " + _rootWidget.UIControl.Name); + _logger.LogTrace("Transition : After Release " + _rootWidget.UIControl.Name); if (handled) { @@ -685,17 +689,17 @@ public void TransitionManualScan(ManualScanModes manualScanMode = ManualScanMode if (_timer != null) { _timer.Interval = CoreGlobals.AppPreferences.ScanTime; - Log.Verbose(_rootWidget.UIControl.Name + ", syncobj.status " + _syncObj.Status); + _logger.LogTrace(_rootWidget.UIControl.Name + ", syncobj.status " + _syncObj.Status); if (_syncObj.Status == SyncLock.StatusValues.None) { timer_Elapsed(null, null); - Log.Verbose("Starting timer " + _rootWidget.UIControl.Name); + _logger.LogTrace("Starting timer " + _rootWidget.UIControl.Name); _timer.Start(); } else { - Log.Verbose("******** WILL NOT START TIMER!!!" + _rootWidget.UIControl.Name + ", syncobj.status " + _syncObj.Status); + _logger.LogTrace("******** WILL NOT START TIMER!!!" + _rootWidget.UIControl.Name + ", syncobj.status " + _syncObj.Status); } setPlayerState(PlayerState.Running); @@ -703,10 +707,10 @@ public void TransitionManualScan(ManualScanModes manualScanMode = ManualScanMode } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex.ToString()); } - Log.Verbose("Returning"); + _logger.LogTrace("Returning"); } /// @@ -718,8 +722,6 @@ protected virtual void Dispose(bool disposing) // Check to see if Dispose has already been called. if (!_disposed) { - Log.Verbose(); - if (disposing) { // dispose all managed resources. @@ -745,7 +747,7 @@ private int animatedWidgetCount() } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex.ToString()); return 0; } } @@ -758,7 +760,7 @@ private void check() { if (_syncObj != null && _syncObj.IsClosing()) { - Log.Verbose("Scanner closed" + _rootWidget.UIControl.Name); + _logger.LogTrace("Scanner closed" + _rootWidget.UIControl.Name); throw new Exception(); } } @@ -798,22 +800,22 @@ private bool checkStopManualAutoScan(ManualScanModes scanMode) /// Tag private void dumpManualPath(String tag) { - Log.Verbose(tag + " ---------------------"); + _logger.LogTrace(tag + " ---------------------"); if (_manualScanPath != null) { if (_manualScanPath.Count == 0) { - Log.Verbose("None found"); + _logger.LogTrace("None found"); } else { foreach (var h in _manualScanPath) { - Log.Verbose(h.Name); + _logger.LogTrace(h.Name); } } } - Log.Verbose("---------------------"); + _logger.LogTrace("---------------------"); } /// @@ -824,7 +826,6 @@ private void dumpManualPath(String tag) /// index of the first animation widget private int getFirstAnimatedWidget() { - Log.Verbose(); for (int ii = 0; ii < _currentAnimation.AnimationWidgetList.Count; ii++) { if (_currentAnimation.AnimationWidgetList[ii].UIWidget.CanAddForAnimation()) @@ -865,7 +866,7 @@ private int getNextAnimatedWidget(int index) } catch (Exception ex) { - Log.Exception("ex=" + ex.Message); + _logger.LogError("ex=" + ex.Message); return -1; } } @@ -1149,11 +1150,9 @@ private bool handleSingleMove() /// private void highlightNeighborAbove() { - Log.Verbose(); - if (_highlightedWidget == null) { - Log.Verbose("_widgethighlighted is null"); + _logger.LogTrace("_widgethighlighted is null"); return; } @@ -1173,7 +1172,7 @@ private void highlightNeighborAbove() above ??= _highlightedWidget.Above[0]; - Log.Verbose("above: " + above.Name); + _logger.LogTrace("above: " + above.Name); above.HighlightOn(); if (!_manualScanPath.Contains(above)) { @@ -1184,11 +1183,11 @@ private void highlightNeighborAbove() } else { - Log.Verbose("above is null. Will get wraparound"); + _logger.LogTrace("above is null. Will get wraparound"); var bottomMost = getWraparoundWidgetBottom(); if (bottomMost != null) { - Log.Verbose("bottomMost is " + bottomMost.Name); + _logger.LogTrace("bottomMost is " + bottomMost.Name); bottomMost.HighlightOn(); if (!_manualScanPath.Contains(bottomMost)) @@ -1206,11 +1205,9 @@ private void highlightNeighborAbove() /// private void highlightNeighborBelow() { - Log.Verbose(); - if (_highlightedWidget == null) { - Log.Verbose("_widgethighlighted is null"); + _logger.LogTrace("_widgethighlighted is null"); return; } @@ -1230,7 +1227,7 @@ private void highlightNeighborBelow() below ??= _highlightedWidget.Below[0]; - Log.Verbose("below: " + below.Name); + _logger.LogTrace("below: " + below.Name); below.HighlightOn(); if (!_manualScanPath.Contains(below)) { @@ -1240,11 +1237,11 @@ private void highlightNeighborBelow() } else { - Log.Verbose("Below is null. Will get wraparound"); + _logger.LogTrace("Below is null. Will get wraparound"); var topMost = getWraparoundWidgetTop(); if (topMost != null) { - Log.Verbose("topMost is " + topMost.Name); + _logger.LogTrace("topMost is " + topMost.Name); topMost.HighlightOn(); if (!_manualScanPath.Contains(topMost)) @@ -1263,8 +1260,6 @@ private void highlightNeighborBelow() /// private void highlightNeighborLeft() { - Log.Verbose(); - if (_highlightedWidget == null) { return; @@ -1286,7 +1281,7 @@ private void highlightNeighborLeft() left ??= _highlightedWidget.Left[0]; - Log.Verbose("Left: " + left.Name); + _logger.LogTrace("Left: " + left.Name); left.HighlightOn(); if (!_manualScanPath.Contains(left)) { @@ -1298,11 +1293,11 @@ private void highlightNeighborLeft() { // reached the left edge of the form. Wrap around // to start scanning at the right edge - Log.Verbose("Left is null. Will get wraparound"); + _logger.LogTrace("Left is null. Will get wraparound"); var rightmost = getWraparoundWidgetRight(); if (rightmost != null) { - Log.Verbose("Leftmost is " + rightmost.Name); + _logger.LogTrace("Leftmost is " + rightmost.Name); rightmost.HighlightOn(); if (!_manualScanPath.Contains(rightmost)) @@ -1342,7 +1337,7 @@ private void highlightNeighborRight() right ??= _highlightedWidget.Right[0]; - Log.Verbose("Right: " + right.Name); + _logger.LogTrace("Right: " + right.Name); right.HighlightOn(); if (!_manualScanPath.Contains(right)) { @@ -1397,13 +1392,13 @@ private void release(Object syncObj) { try { - //Log.Verbose("Before EXIT for " + _rootWidget.UIControl.Name); + //_logger.LogTrace("Before EXIT for " + _rootWidget.UIControl.Name); Monitor.Exit(syncObj); - //Log.Verbose("After EXIT for " + _rootWidget.UIControl.Name); + //_logger.LogTrace("After EXIT for " + _rootWidget.UIControl.Name); } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, ex.Message); } } @@ -1414,16 +1409,14 @@ private void release(Object syncObj) /// new state private void setPlayerState(PlayerState playerState) { - Log.Verbose(); - PlayerState oldState = _playerState; if (oldState != playerState) { - Log.Verbose(_rootWidget.Name + ":Set player state to " + playerState); + _logger.LogTrace(_rootWidget.Name + ":Set player state to " + playerState); _playerState = playerState; if (EvtPlayerStateChanged != null) { - Log.Verbose("Calling evtPlayerStateChanged"); + _logger.LogTrace("Calling evtPlayerStateChanged"); EvtPlayerStateChanged.BeginInvoke(this, new PlayerStateChangedEventArgs(oldState, _playerState), null, null); } } @@ -1463,13 +1456,13 @@ private void timerElapsedAutoScan(object sender, ElapsedEventArgs e) { if (_syncObj.IsClosing()) { - Log.Verbose("Form is closing. Returning" + _rootWidget.UIControl.Name); + _logger.LogTrace("Form is closing. Returning" + _rootWidget.UIControl.Name); return; } if (_inTimer) { - Log.Verbose("Timer is busy. returning"); + _logger.LogTrace("Timer is busy. returning"); return; } @@ -1477,24 +1470,24 @@ private void timerElapsedAutoScan(object sender, ElapsedEventArgs e) try { - Log.Verbose("Before tryEnter " + _rootWidget.UIControl.Name + ", threadid: " + Kernel32Interop.GetCurrentThreadId()); + _logger.LogTrace("Before tryEnter " + _rootWidget.UIControl.Name + ", threadid: " + Kernel32Interop.GetCurrentThreadId()); if (!tryEnter(_transitionSync)) { - Log.Verbose("_transition sync will block returning"); + _logger.LogTrace("_transition sync will block returning"); return; } - Log.Verbose("After tryEnter" + _rootWidget.UIControl.Name + ", status: " + _syncObj.Status); + _logger.LogTrace("After tryEnter" + _rootWidget.UIControl.Name + ", status: " + _syncObj.Status); if (_syncObj.IsClosing()) { - Log.Verbose("Form is closing. Returning" + _rootWidget.UIControl.Name); + _logger.LogTrace("Form is closing. Returning" + _rootWidget.UIControl.Name); return; } check(); - Log.Verbose("CurrentAnimation: " + _currentAnimation.Name + + _logger.LogTrace("CurrentAnimation: " + _currentAnimation.Name + ". Count: " + _currentAnimation.AnimationWidgetList.Count + ". currentWidgetIndex: " + _currentWidgetIndex); @@ -1502,14 +1495,14 @@ private void timerElapsedAutoScan(object sender, ElapsedEventArgs e) var animationWidget = _currentAnimation.AnimationWidgetList[_currentWidgetIndex]; - Log.Verbose(_rootWidget.UIControl.Name + ", status: " + _syncObj.Status); + _logger.LogTrace(_rootWidget.UIControl.Name + ", status: " + _syncObj.Status); // if any switch is currently engaged, keep the current widget // highlighted until the user releases the switch //if (ActuatorManager.Instance.IsSwitchActive()) if (IsSwitchActive) { - Log.Verbose("Some switch is active. Will try again"); + _logger.LogTrace("Some switch is active. Will try again"); return; } @@ -1522,7 +1515,7 @@ private void timerElapsedAutoScan(object sender, ElapsedEventArgs e) check(); - Log.Verbose(_rootWidget.UIControl.Name + ", status: " + _syncObj.Status); + _logger.LogTrace(_rootWidget.UIControl.Name + ", status: " + _syncObj.Status); if (!_currentAnimation.IsFirst && animatedWidgetCount() == 0) { @@ -1556,7 +1549,7 @@ private void timerElapsedAutoScan(object sender, ElapsedEventArgs e) } else { - Log.Verbose("Timer is null. returning"); + _logger.LogTrace("Timer is null. returning"); return; } @@ -1578,7 +1571,7 @@ private void timerElapsedAutoScan(object sender, ElapsedEventArgs e) if (_highlightedAnimationWidget != null && _highlightedAnimationWidget != animationWidget) { - Log.Verbose(string.Format("Animation: {0}. Turning off . name = {1}. Count: {2}", + _logger.LogTrace(string.Format("Animation: {0}. Turning off . name = {1}. Count: {2}", _currentAnimation.Name, _highlightedAnimationWidget.UIWidget.Name, _currentAnimation.AnimationWidgetList.Count)); @@ -1600,7 +1593,7 @@ private void timerElapsedAutoScan(object sender, ElapsedEventArgs e) // now turn the highlight on on the next widget in the sequence animationWidget = _currentAnimation.AnimationWidgetList[_currentWidgetIndex]; - Log.Verbose("Animation: " + _currentAnimation.Name + + _logger.LogTrace("Animation: " + _currentAnimation.Name + ". Turning on " + _currentWidgetIndex + ". name = " + animationWidget.UIWidget.Name); @@ -1629,7 +1622,7 @@ private void timerElapsedAutoScan(object sender, ElapsedEventArgs e) } else { - Log.Verbose("timer is null. returning"); + _logger.LogTrace("timer is null. returning"); return; } @@ -1664,18 +1657,18 @@ private void timerElapsedAutoScan(object sender, ElapsedEventArgs e) } catch (Exception ex) { - Log.Exception("AnimationPlayerexception " + ex); + _logger.LogError("AnimationPlayerexception " + ex); } finally { - Log.Verbose("Before release " + _rootWidget.UIControl.Name); + _logger.LogTrace("Before release " + _rootWidget.UIControl.Name); release(_transitionSync); - Log.Verbose("After release " + _rootWidget.UIControl.Name); + _logger.LogTrace("After release " + _rootWidget.UIControl.Name); - Log.Verbose("Setting intimer to false " + _rootWidget.UIControl.Name); + _logger.LogTrace("Setting intimer to false " + _rootWidget.UIControl.Name); _inTimer = false; - Log.Verbose("Exiting timer " + _rootWidget.UIControl.Name); + _logger.LogTrace("Exiting timer " + _rootWidget.UIControl.Name); } } @@ -1688,17 +1681,17 @@ private void timerElapsedManual(object sender, ElapsedEventArgs e) { bool actuate = false; - Log.Verbose("------------->>> ENTER "); + _logger.LogTrace("------------->>> ENTER "); if (_syncObj.IsClosing()) { - Log.Verbose("Form is closing. Returning" + _rootWidget.UIControl.Name); + _logger.LogTrace("Form is closing. Returning" + _rootWidget.UIControl.Name); return; } if (_inTimer) { - Log.Verbose("Timer is busy. returning"); + _logger.LogTrace("Timer is busy. returning"); return; } @@ -1711,31 +1704,31 @@ private void timerElapsedManual(object sender, ElapsedEventArgs e) try { - Log.Verbose("Before tryEnter " + _rootWidget.UIControl.Name + ", threadid: " + Kernel32Interop.GetCurrentThreadId()); + _logger.LogTrace("Before tryEnter " + _rootWidget.UIControl.Name + ", threadid: " + Kernel32Interop.GetCurrentThreadId()); if (!tryEnter(_transitionSync)) { - Log.Verbose("_transition sync will block returning"); + _logger.LogTrace("_transition sync will block returning"); return; } - Log.Verbose("After tryEnter" + _rootWidget.UIControl.Name + ", status: " + _syncObj.Status); + _logger.LogTrace("After tryEnter" + _rootWidget.UIControl.Name + ", status: " + _syncObj.Status); if (_syncObj.IsClosing()) { - Log.Verbose("Form is closing. Returning" + _rootWidget.UIControl.Name); + _logger.LogTrace("Form is closing. Returning" + _rootWidget.UIControl.Name); return; } check(); - Log.Verbose(_rootWidget.UIControl.Name + ", status: " + _syncObj.Status); + _logger.LogTrace(_rootWidget.UIControl.Name + ", status: " + _syncObj.Status); // if any switch is currently engaged, keep the current widget // highlighted until the user releases the switch //if (ActuatorManager.Instance.IsSwitchActive()) if (IsSwitchActive) { - Log.Verbose("Some switch is active. Will try again"); + _logger.LogTrace("Some switch is active. Will try again"); return; } @@ -1765,7 +1758,7 @@ private void timerElapsedManual(object sender, ElapsedEventArgs e) } } - Log.Verbose("_manualScanMode is " + _manualScanMode); + _logger.LogTrace("_manualScanMode is " + _manualScanMode); var prevWidgetHighlighted = _highlightedWidget; @@ -1790,29 +1783,29 @@ private void timerElapsedManual(object sender, ElapsedEventArgs e) if (prevWidgetHighlighted == _highlightedWidget) { - Log.Verbose("Same widget. Stopping timer"); + _logger.LogTrace("Same widget. Stopping timer"); _timer?.Stop(); } check(); } catch (Exception ex) { - Log.Exception("AnimationPlayerexception " + ex); + _logger.LogError("AnimationPlayerexception " + ex); } finally { - Log.Verbose("Before release " + _rootWidget.UIControl.Name); + _logger.LogTrace("Before release " + _rootWidget.UIControl.Name); release(_transitionSync); - Log.Verbose("After release " + _rootWidget.UIControl.Name); + _logger.LogTrace("After release " + _rootWidget.UIControl.Name); - Log.Verbose("Setting intimer to false " + _rootWidget.UIControl.Name); + _logger.LogTrace("Setting intimer to false " + _rootWidget.UIControl.Name); _inTimer = false; if (actuate) { ManualScanActuateWidget(_highlightedWidget); } - Log.Verbose("----------- <<<< Exiting timer " + _rootWidget.UIControl.Name); + _logger.LogTrace("----------- <<<< Exiting timer " + _rootWidget.UIControl.Name); } } @@ -1832,7 +1825,7 @@ private void tryEnterUntilSuccess(object syncObj) { while (!tryEnter(syncObj)) { - Log.Verbose("CALLING DOEVENTS"); + _logger.LogTrace("CALLING DOEVENTS"); if (Application.MessageLoop) { Application.DoEvents(); diff --git a/src/Libraries/ACATCore/AnimationManagement/AnimationsCollection.cs b/src/Libraries/ACATCore/AnimationManagement/AnimationsCollection.cs index 60eddada..2a2d7180 100644 --- a/src/Libraries/ACATCore/AnimationManagement/AnimationsCollection.cs +++ b/src/Libraries/ACATCore/AnimationManagement/AnimationsCollection.cs @@ -127,8 +127,6 @@ protected virtual void Dispose(bool disposing) // Check to see if Dispose has already been called. if (!_disposed) { - Log.Verbose(); - if (disposing) { // dispose all managed resources. diff --git a/src/Libraries/ACATCore/AnimationManagement/PanelAnimationManager.cs b/src/Libraries/ACATCore/AnimationManagement/PanelAnimationManager.cs index d42af578..023b24ea 100644 --- a/src/Libraries/ACATCore/AnimationManagement/PanelAnimationManager.cs +++ b/src/Libraries/ACATCore/AnimationManagement/PanelAnimationManager.cs @@ -11,17 +11,23 @@ using ACAT.Core.Utility; using ACAT.Core.WidgetManagement; using ACAT.Core.WidgetManagement.Interfaces; +using Microsoft.Extensions.Logging; using System; namespace ACAT.Core.AnimationManagement { public class PanelAnimationManager : AnimationManager, IPanelAnimationManager { + private readonly ILogger _logger; + private String _panelClass = String.Empty; private PanelConfigMapEntry _panelConfigMapEntry; - public PanelAnimationManager() : base() { } + public PanelAnimationManager(ILogger logger) : base() + { + _logger = logger; + } public bool Init(PanelConfigMapEntry panelConfigMapEntry, Widget panelWidget = null) { @@ -44,14 +50,14 @@ public bool Init(PanelConfigMapEntry panelConfigMapEntry, Widget panelWidget = n subscribeToActuatorEvents(); } - Log.Debug("returning from Anim manager init()"); + _logger.LogDebug("returning from Anim manager init()"); return retVal; } public void Start(Widget panelWidget, String animationName = null) { - Log.Debug("Start animation for panel " + panelWidget.Name); + _logger.LogDebug("Start animation for panel {PanelName}", panelWidget.Name); if (_player != null) { @@ -81,7 +87,7 @@ public void Start(Widget panelWidget, String animationName = null) { if (animations == null) { - Log.Error("Could not find animations entry for panel " + panelWidget.Name); + _logger.LogError("Could not find animations entry for panel {PanelName}", panelWidget.Name); return; } @@ -111,15 +117,15 @@ public override void TransitionFromName(String animationName) { try { - Log.Verbose(); + _logger.LogTrace("TransitionFromName called"); - Log.Debug("_currentPanel: " + _currentPanel); + _logger.LogDebug("_currentPanel: {CurrentPanel}", _currentPanel); resetSwitchEventStates(); if (_player == null) { - Log.Debug("_player is null"); + _logger.LogDebug("_player is null"); return; } @@ -132,16 +138,16 @@ public override void TransitionFromName(String animationName) var animation = animations[animationName]; if (animation == null) { - Log.Debug("Transition: animation is NULL!"); + _logger.LogDebug("Transition: animation is NULL!"); return; } - Log.Debug("Calling player transition"); + _logger.LogDebug("Calling player transition"); _player.Transition(animation); } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex, "{ExceptionMessage}", ex.Message); } } @@ -161,13 +167,13 @@ protected override void actuatorManager_EvtSwitchActivated(object sender, Actuat return; } - Log.Debug("switch: " + switchObj.Name); - Log.Debug(" Panel: " + _currentPanel.Name); + _logger.LogDebug("switch: {SwitchName}", switchObj.Name); + _logger.LogDebug(" Panel: {PanelName}", _currentPanel.Name); if (_currentPanel.UIControl is System.Windows.Forms.Form) { bool visible = Windows.GetVisible(_currentPanel.UIControl); - Log.Debug("Form: " + _currentPanel.UIControl.Name + ", visible: " + visible); + _logger.LogDebug("Form: {FormName}, visible: {Visible}", _currentPanel.UIControl.Name, visible); if (!visible) { return; @@ -178,7 +184,7 @@ protected override void actuatorManager_EvtSwitchActivated(object sender, Actuat String onTrigger = switchObj.Command; if (String.IsNullOrEmpty(onTrigger)) { - Log.Debug("OnTrigger is null. returning"); + _logger.LogDebug("OnTrigger is null. returning"); return; } @@ -195,7 +201,7 @@ protected override void actuatorManager_EvtSwitchActivated(object sender, Actuat return; } - Log.Debug("playerState: " + _player.State); + _logger.LogDebug("playerState: {PlayerState}", _player.State); // execute action if the player is in the right state. if (_player.State != PlayerState.Stopped && @@ -210,11 +216,11 @@ protected override void actuatorManager_EvtSwitchActivated(object sender, Actuat if (CoreGlobals.AppPreferences.EnableManualScan) { - Log.Debug("HOOO form: " + _currentPanel.UIControl.Name + " Player state: " + _player.State); + _logger.LogDebug("HOOO form: {FormName} Player state: {PlayerState}", _currentPanel.UIControl.Name, _player.State); if (_player.State == PlayerState.Paused) { - Log.Debug(_currentPanel.Name + ": Player is paused. Returning"); + _logger.LogDebug("{PanelName}: Player is paused. Returning", _currentPanel.Name); return; } @@ -223,7 +229,7 @@ protected override void actuatorManager_EvtSwitchActivated(object sender, Actuat var widget = _player.HighlightedWidget; if (widget != null) { - Log.Debug("Actuate. widgetname: " + widget.Name + " Text: " + widget.GetText()); + _logger.LogDebug("Actuate. widgetname: {WidgetName} Text: {WidgetText}", widget.Name, widget.GetText()); _player.Interrupt(); _player.ManualScanActuateWidget(widget); } @@ -238,15 +244,15 @@ protected override void actuatorManager_EvtSwitchActivated(object sender, Actuat if (_player.State == PlayerState.Timeout || _player.State == PlayerState.Interrupted) { - Log.Debug("Calling player transition for firstanimation"); + _logger.LogDebug("Calling player transition for firstanimation"); _player.Transition(_firstAnimation); return; } - Log.Debug("Player state is " + _player.State); + _logger.LogDebug("Player state is {PlayerState}", _player.State); if (_player.State != PlayerState.Running) { - Log.Debug(_currentPanel.Name + ": Player is not Running. Returning"); + _logger.LogDebug("{PanelName}: Player is not Running. Returning", _currentPanel.Name); return; } @@ -285,9 +291,10 @@ protected override void actuatorManager_EvtSwitchActivated(object sender, Actuat highlightedWidget.UIWidget.GetType().Name, widgetName)); - Log.Debug(_currentPanel.Name + ": Switch on " + - highlightedWidget.UIWidget.Name + " type: " + - highlightedWidget.UIWidget.GetType().Name); + _logger.LogDebug("{PanelName}: Switch on {WidgetName} type: {WidgetType}", + _currentPanel.Name, + highlightedWidget.UIWidget.Name, + highlightedWidget.UIWidget.GetType().Name); // check if the widget has a onSelect code fragment. If so execute it. Otherwise // then check if the animation seq that this widget is a part of, has a onSelect. @@ -308,12 +315,12 @@ protected override void actuatorManager_EvtSwitchActivated(object sender, Actuat } else { - Log.Debug(_currentPanel.Name + ": No current animation or highlighed widget!!"); + _logger.LogDebug("{PanelName}: No current animation or highlighed widget!!", _currentPanel.Name); } } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex, "{ExceptionMessage}", ex.Message); } finally { @@ -342,17 +349,17 @@ private void runSwitchMappedCommand(IActuatorSwitch switchObj) { if (!arg.Enabled) { - Log.Debug("Command " + onTrigger + " is not currently enabled"); + _logger.LogDebug("Command {Command} is not currently enabled", onTrigger); return; } else { - Log.Debug("Command " + onTrigger + " IS ENABLED"); + _logger.LogDebug("Command {Command} IS ENABLED", onTrigger); } } else { - Log.Debug("arg.handled is false for " + onTrigger); + _logger.LogDebug("arg.handled is false for {Command}", onTrigger); var strTrigger = onTrigger; if (strTrigger[0] == '@') @@ -362,20 +369,20 @@ private void runSwitchMappedCommand(IActuatorSwitch switchObj) var cmdDescriptor = CommandManager.Instance.AppCommandTable.Get(strTrigger); if (cmdDescriptor != null && !cmdDescriptor.EnableSwitchMap) { - Log.Debug("EnableswitchMap is not enabled for " + onTrigger); + _logger.LogDebug("EnableswitchMap is not enabled for {Command}", onTrigger); runCommand = false; } } } else { - Log.Debug("Dialog is active. Will not handle"); + _logger.LogDebug("Dialog is active. Will not handle"); runCommand = false; } if (runCommand) { - Log.Debug("Executing OnTrigger command " + onTrigger + " for panel..." + _currentPanel.Name); + _logger.LogDebug("Executing OnTrigger command {Command} for panel...{PanelName}", onTrigger, _currentPanel.Name); PCode pcode = new() { Script = "run(" + onTrigger + ")" }; var parser = new Parser(); if (parser.Parse(pcode.Script, ref pcode)) diff --git a/src/Libraries/ACATCore/AnimationManagement/UserControlAnimationManager.cs b/src/Libraries/ACATCore/AnimationManagement/UserControlAnimationManager.cs index 729b3a1f..f9f6eb59 100644 --- a/src/Libraries/ACATCore/AnimationManagement/UserControlAnimationManager.cs +++ b/src/Libraries/ACATCore/AnimationManagement/UserControlAnimationManager.cs @@ -12,11 +12,13 @@ using ACAT.Core.ActuatorManagement.Interfaces; using ACAT.Core.PanelManagement.Interfaces; using ACAT.Core.AnimationManagement.Interfaces; +using Microsoft.Extensions.Logging; namespace ACAT.Core.AnimationManagement { public class UserControlAnimationManager : AnimationManager, IUserControlAnimationManager { + private readonly ILogger _logger; private UserControlConfigMapEntry mapEntry { get; set; } = null; private String name { get; set; } = null; @@ -24,7 +26,10 @@ public class UserControlAnimationManager : AnimationManager, IUserControlAnimati public event PlayerAnimationTransition EvtPlayerAnimationTransition; - public UserControlAnimationManager() : base() { } + public UserControlAnimationManager() : base() + { + _logger = LoggingConfiguration.CreateLogger(); + } public bool Init(UserControlConfigMapEntry mapentry) { @@ -44,7 +49,7 @@ public bool Init(UserControlConfigMapEntry mapentry) subscribeToActuatorEvents(); } - Log.Debug("returning from Anim manager init()"); + _logger.LogDebug("Returning from Anim manager init()"); return retVal; } @@ -56,7 +61,7 @@ public bool IsPlayerRunning() public void OnLoad(Widget panelWidget, String animationName = null) { - Log.Debug("Start animation for panel " + panelWidget.Name); + _logger.LogDebug("Start animation for panel {PanelName}", panelWidget.Name); if (_player != null) { @@ -84,7 +89,7 @@ public void OnLoad(Widget panelWidget, String animationName = null) { if (animations == null) { - Log.Error("Could not find animations entry for panel " + panelWidget.Name); + _logger.LogError("Could not find animations entry for panel {PanelName}", panelWidget.Name); return; } @@ -115,12 +120,12 @@ public void Start(String animationName = null) { if (!CoreGlobals.AppPreferences.EnableAutoStartScan) { - Log.Verbose("CALIBTEST: UserControlAnimationManager.Start. Do AutoTransition"); + _logger.LogTrace("CALIBTEST: UserControlAnimationManager.Start. Do AutoTransition"); Transition(); } else { - Log.Verbose("CALIBTEST: UserControlAnimationManager.Start."); + _logger.LogTrace("CALIBTEST: UserControlAnimationManager.Start."); Transition(_firstAnimation); } } @@ -129,15 +134,15 @@ public override void TransitionFromName(string animationName) { try { - Log.Verbose(); + _logger.LogTrace("TransitionFromName called"); - Log.Debug("_currentPanel: " + _currentPanel); + _logger.LogDebug("_currentPanel: {CurrentPanel}", _currentPanel); resetSwitchEventStates(); if (_player == null) { - Log.Debug("_player is null"); + _logger.LogDebug("_player is null"); return; } @@ -150,17 +155,17 @@ public override void TransitionFromName(string animationName) var animation = animations[animationName]; if (animation == null) { - Log.Debug("Transition: animation is NULL!"); + _logger.LogDebug("Transition: animation is NULL!"); return; } - Log.Debug("Calling player transition"); + _logger.LogDebug("Calling player transition"); EvtPlayerAnimationTransition?.Invoke(this, animation.Name, animation.IsFirst); _player.Transition(animation); } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex, "Exception in TransitionFromName"); } } @@ -188,13 +193,13 @@ protected override void actuatorManager_EvtSwitchActivated(object sender, Actuat return; } - Log.Debug("switch: " + switchObj.Name); - Log.Debug(" Panel: " + _currentPanel.Name); + _logger.LogDebug("switch: {SwitchName}", switchObj.Name); + _logger.LogDebug(" Panel: {PanelName}", _currentPanel.Name); if (_currentPanel.UIControl is System.Windows.Forms.Form) { bool visible = Windows.GetVisible(_currentPanel.UIControl); - Log.Debug("Form: " + _currentPanel.UIControl.Name + ", playerState: " + _player.State + ", visible: " + visible); + _logger.LogDebug("Form: {FormName}, playerState: {PlayerState}, visible: {Visible}", _currentPanel.UIControl.Name, _player.State, visible); if (!visible) { return; @@ -205,7 +210,7 @@ protected override void actuatorManager_EvtSwitchActivated(object sender, Actuat String onTrigger = switchObj.Command; if (String.IsNullOrEmpty(onTrigger)) { - Log.Debug("OnTrigger is null. returning"); + _logger.LogDebug("OnTrigger is null. returning"); return; } @@ -226,11 +231,11 @@ protected override void actuatorManager_EvtSwitchActivated(object sender, Actuat if (CoreGlobals.AppPreferences.EnableManualScan) { - Log.Debug("HOOO form: " + _currentPanel.UIControl.Name + " Player state: " + _player.State); + _logger.LogDebug("HOOO form: {FormName} Player state: {PlayerState}", _currentPanel.UIControl.Name, _player.State); if (_player.State == PlayerState.Paused) { - Log.Debug(_currentPanel.Name + ": Player is paused. Returning"); + _logger.LogDebug("{PanelName}: Player is paused. Returning", _currentPanel.Name); return; } @@ -239,7 +244,7 @@ protected override void actuatorManager_EvtSwitchActivated(object sender, Actuat var widget = _player.HighlightedWidget; if (widget != null) { - Log.Debug("Actuate. widgetname: " + widget.Name + " Text: " + widget.GetText()); + _logger.LogDebug("Actuate. widgetname: {WidgetName} Text: {WidgetText}", widget.Name, widget.GetText()); _player.Interrupt(); _player.ManualScanActuateWidget(widget); } @@ -252,10 +257,10 @@ protected override void actuatorManager_EvtSwitchActivated(object sender, Actuat return; } - Log.Debug("Player state is " + _player.State); + _logger.LogDebug("Player state is {PlayerState}", _player.State); if (_player.State != PlayerState.Running) { - Log.Debug(_currentPanel.Name + ": Player is not Running. Returning"); + _logger.LogDebug("{PanelName}: Player is not Running. Returning", _currentPanel.Name); return; } @@ -294,9 +299,7 @@ protected override void actuatorManager_EvtSwitchActivated(object sender, Actuat highlightedWidget.UIWidget.GetType().Name, widgetName)); - Log.Debug(_currentPanel.Name + ": Switch on " + - highlightedWidget.UIWidget.Name + " type: " + - highlightedWidget.UIWidget.GetType().Name); + _logger.LogDebug("{PanelName}: Switch on {WidgetName} type: {WidgetType}", _currentPanel.Name, highlightedWidget.UIWidget.Name, highlightedWidget.UIWidget.GetType().Name); // check if the widget has a onSelect code fragment. If so execute it. Otherwise // then check if the animation seq that this widget is a part of, has a onSelect. @@ -319,12 +322,12 @@ protected override void actuatorManager_EvtSwitchActivated(object sender, Actuat } else { - Log.Debug(_currentPanel.Name + ": No current animation or highlighed widget!!"); + _logger.LogDebug("{PanelName}: No current animation or highlighed widget!!", _currentPanel.Name); } } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex, "Exception in actuatorManager_EvtSwitchActivated"); } finally { @@ -353,35 +356,35 @@ private void runSwitchMappedCommand(IActuatorSwitch switchObj) { if (!arg.Enabled) { - Log.Debug("Command " + onTrigger + " is not currently enabled"); + _logger.LogDebug("Command {Command} is not currently enabled", onTrigger); return; } else { - Log.Debug("Command " + onTrigger + " IS ENABLED"); + _logger.LogDebug("Command {Command} IS ENABLED", onTrigger); } } else { - Log.Debug("arg.handled is false for " + onTrigger); + _logger.LogDebug("arg.handled is false for {Command}", onTrigger); var cmdDescriptor = CommandManager.Instance.AppCommandTable.Get(onTrigger); if (cmdDescriptor != null && !cmdDescriptor.EnableSwitchMap) { - Log.Debug("EnableswitchMap is not enabled for " + onTrigger); + _logger.LogDebug("EnableswitchMap is not enabled for {Command}", onTrigger); runCommand = false; } } } else { - Log.Debug("Dialog is active. Will not handle"); + _logger.LogDebug("Dialog is active. Will not handle"); runCommand = false; } if (runCommand) { - Log.Debug("Executing OnTrigger command " + onTrigger + " for panel..." + _currentPanel.Name); + _logger.LogDebug("Executing OnTrigger command {Command} for panel...{PanelName}", onTrigger, _currentPanel.Name); PCode pcode = new() { Script = "run(" + onTrigger + ")" }; var parser = new Parser(); if (parser.Parse(pcode.Script, ref pcode)) diff --git a/src/Libraries/ACATCore/AnimationManagement/Variables.cs b/src/Libraries/ACATCore/AnimationManagement/Variables.cs index 58ccf598..b4e000c9 100644 --- a/src/Libraries/ACATCore/AnimationManagement/Variables.cs +++ b/src/Libraries/ACATCore/AnimationManagement/Variables.cs @@ -142,7 +142,7 @@ public String GetString(String variableName) /// It's value public void Set(String variableName, object value) { - //Log.Debug("Set variable " + variableName); + //_logger.LogDebug("Set variable {VariableName}", variableName); if (_list.ContainsKey(variableName)) { _list[variableName] = value; diff --git a/src/Libraries/ACATCore/Audit/AuditLog.cs b/src/Libraries/ACATCore/Audit/AuditLog.cs index 7eb8258f..94524316 100644 --- a/src/Libraries/ACATCore/Audit/AuditLog.cs +++ b/src/Libraries/ACATCore/Audit/AuditLog.cs @@ -62,7 +62,7 @@ public class AuditLog /// static AuditLog() { - _logger = LoggerFactory.Create(builder => builder.AddConsole()).CreateLogger(); + _logger = LoggingConfiguration.CreateLogger(); string logFileFolder = FileUtils.GetLogsDir(); diff --git a/src/Libraries/ACATCore/Extensions/ExtensionInvoker.cs b/src/Libraries/ACATCore/Extensions/ExtensionInvoker.cs index 5ca0fe8d..b056aad2 100644 --- a/src/Libraries/ACATCore/Extensions/ExtensionInvoker.cs +++ b/src/Libraries/ACATCore/Extensions/ExtensionInvoker.cs @@ -6,6 +6,7 @@ //////////////////////////////////////////////////////////////////////////// using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Reflection; @@ -27,6 +28,7 @@ namespace ACAT.Core.Extensions /// public class ExtensionInvoker : IExtension { + private static readonly ILogger _logger = LoggingConfiguration.CreateLogger(); /// /// The object whose methods/properties/events are to /// be invoked through reflection @@ -193,7 +195,7 @@ public object GetValue(String property) } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, "Error getting value for property {Property}", property); } return null; @@ -233,7 +235,7 @@ public object InvokeExtensionMethod(string methodName, params object[] args) } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex, "Error invoking extension method {MethodName}", methodName); } return result; @@ -287,7 +289,7 @@ public bool SetValue(String property, object value) } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex, "Error setting value for property {Property}", property); retVal = false; } diff --git a/src/Libraries/ACATCore/Interpreter/Interpret.cs b/src/Libraries/ACATCore/Interpreter/Interpret.cs index 73f78edd..fa076945 100644 --- a/src/Libraries/ACATCore/Interpreter/Interpret.cs +++ b/src/Libraries/ACATCore/Interpreter/Interpret.cs @@ -6,6 +6,7 @@ //////////////////////////////////////////////////////////////////////////// using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Reflection; @@ -29,6 +30,8 @@ namespace ACAT.Core.Interpreter /// public class Interpret { + private static readonly ILogger _logger = LoggingConfiguration.CreateLogger(); + #pragma warning disable IDE0051 /// @@ -223,12 +226,12 @@ public bool Execute(ActionVerb actionVerb) } else { - Log.Debug("Error executing verb " + actionVerb.Action + ". Mi is null"); + _logger.LogDebug("Error executing verb {Action}. Mi is null", actionVerb.Action); } } catch (Exception e) { - Log.Exception("Error executing verb " + actionVerb.Action + ". Exception: " + e.ToString()); + _logger.LogError(e, "Error executing verb {Action}", actionVerb.Action); retVal = false; } diff --git a/src/Libraries/ACATCore/Interpreter/Parser.cs b/src/Libraries/ACATCore/Interpreter/Parser.cs index 1d23ca8e..ce3a3af8 100644 --- a/src/Libraries/ACATCore/Interpreter/Parser.cs +++ b/src/Libraries/ACATCore/Interpreter/Parser.cs @@ -6,6 +6,7 @@ //////////////////////////////////////////////////////////////////////////// using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Text; @@ -19,6 +20,7 @@ namespace ACAT.Core.Interpreter /// public class Parser { + private static readonly ILogger _logger = LoggingConfiguration.CreateLogger(); /// /// State of parsing /// @@ -159,7 +161,7 @@ private bool getActionAndArguments(String parseString, ref String retAction, ref break; case ParseState.Invalid: - Log.Error("Parse error at index " + index + ". String: " + parseString); + _logger.LogError("Parse error at index {Index}. String: {ParseString}", index, parseString); retVal = false; done = true; break; @@ -168,13 +170,13 @@ private bool getActionAndArguments(String parseString, ref String retAction, ref if (!done) { - Log.Error("Parse error at index " + index + ". String: " + parseString); + _logger.LogError("Parse error at index {Index}. String: {ParseString}", index, parseString); retVal = false; } if (retVal && index < parseString.Length) { - Log.Error("Parse error at index " + index + ". String: " + parseString); + _logger.LogError("Parse error at index {Index}. String: {ParseString}", index, parseString); retVal = false; } diff --git a/src/Libraries/ACATCore/PanelManagement/CommandDispatcher/RunCommands.cs b/src/Libraries/ACATCore/PanelManagement/CommandDispatcher/RunCommands.cs index 9a123397..0e439b54 100644 --- a/src/Libraries/ACATCore/PanelManagement/CommandDispatcher/RunCommands.cs +++ b/src/Libraries/ACATCore/PanelManagement/CommandDispatcher/RunCommands.cs @@ -6,6 +6,7 @@ //////////////////////////////////////////////////////////////////////////// using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; @@ -17,6 +18,8 @@ namespace ACAT.Core.PanelManagement.CommandDispatcher /// public class RunCommands { + private static readonly ILogger _logger = LoggingConfiguration.CreateLogger(typeof(RunCommands).Name); + /// /// Command dispatcher object. Caller can set this and the dispatcher /// will be called to dispatch the command. @@ -70,7 +73,7 @@ public bool Add(RunCommandHandler handler) catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, ex.Message); ret = false; } diff --git a/src/Libraries/ACATCore/PanelManagement/Common/DialogCommon.cs b/src/Libraries/ACATCore/PanelManagement/Common/DialogCommon.cs index d24d6e49..779bea85 100644 --- a/src/Libraries/ACATCore/PanelManagement/Common/DialogCommon.cs +++ b/src/Libraries/ACATCore/PanelManagement/Common/DialogCommon.cs @@ -21,6 +21,7 @@ using System.Windows.Automation; using System.Windows.Forms; using ACAT.Core.PanelManagement.PanelConfig; +using Microsoft.Extensions.Logging; namespace ACAT.Core.PanelManagement.Common { @@ -31,7 +32,7 @@ namespace ACAT.Core.PanelManagement.Common /// events are handled and makes it easier for the developer to add /// new dialogs to ACAT. /// A dialog form will contain a DialogCommon field and - /// call the methods in this class whereever they are needed. Refer + /// call the methods in this class wherever they are needed. Refer /// to the documentation for the methods in this class for info on when these /// methods need to be invoked. /// This class creates the WidgetManager and PanelAnimationManager objects @@ -39,6 +40,8 @@ namespace ACAT.Core.PanelManagement.Common /// public class DialogCommon : IDisposable, IPanelCommon { + private static ILogger _logger => LogManager.GetLogger(); + /// /// All dialog forms should derive from IDialogPanel /// @@ -269,15 +272,16 @@ public void OnFormClosing(FormClosingEventArgs e) { if (_syncLock.Status != SyncLock.StatusValues.None) { - Log.Debug(_form.Name + ", _syncObj.Status: " + _syncLock.Status + ", form already closed. returning"); + _logger?.LogDebug("{FormName}, _syncObj.Status: {Status}, form already closed. returning", + _form.Name, _syncLock.Status); return; } _syncLock.Status = SyncLock.StatusValues.Closing; - Log.Debug("Before animationmangoer.stop"); + _logger?.LogDebug("Before animationmanager.stop"); _form.Invoke(new StopDelegate(_animationManager.Stop)); - Log.Debug("After animationmangoer.stop"); + _logger?.LogDebug("After animationmanager.stop"); unsubscribeFromEvents(); } @@ -339,14 +343,14 @@ protected virtual void Dispose(bool disposing) // Check to see if Dispose has already been called. if (!_disposed) { - Log.Verbose(); + _logger?.LogTrace("Disposing DialogCommon"); if (disposing) { PanelManager.Instance.EvtScannerShow -= Instance_EvtScannerShow; // dispose all managed resources. - Log.Verbose(); + _logger?.LogTrace("Disposing managed resources"); _animationManager?.Dispose(); @@ -388,7 +392,7 @@ private void createAndShowScannerForWidget(Widget widget) var startupArg = createStartupArgForScanner(widget); - Log.Debug("Creating Panel " + widget.Panel); + _logger?.LogDebug("Creating Panel {PanelName}", widget.Panel); Form panel = Context.AppPanelManager.CreatePanel(widget.Panel, string.Empty, startupArg); var child = panel as IScannerPanel; if (child != null) @@ -422,12 +426,12 @@ private StartupArg createStartupArgForScanner(Widget widget) /// private bool initAnimationManager(PanelConfigMapEntry panelConfigMapEntry) { - _animationManager = new PanelAnimationManager(); + _animationManager = new PanelAnimationManager(LoggingConfiguration.CreateLogger()); bool retVal = _animationManager.Init(panelConfigMapEntry); if (!retVal) { - Log.Error("Error initializing animation manager"); + _logger?.LogError("Error initializing animation manager"); } return retVal; @@ -439,7 +443,7 @@ private bool initAnimationManager(PanelConfigMapEntry panelConfigMapEntry) /// private bool initWidgetManager(PanelConfigMapEntry panelConfigMapEntry) { - _widgetManager = new WidgetManager(_form); + _widgetManager = new WidgetManager(_form, LoggingConfiguration.CreateLogger()); _widgetManager.Layout.SetColorScheme(ColorSchemes.DialogSchemeName); @@ -447,7 +451,7 @@ private bool initWidgetManager(PanelConfigMapEntry panelConfigMapEntry) if (!retVal) { - Log.Error("Unable to initialize widget manager"); + _logger?.LogError("Unable to initialize widget manager"); } else { @@ -555,7 +559,7 @@ private void widget_EvtActuated(object sender, WidgetActuatedEventArgs e) string value = widget.Value; if (!string.IsNullOrEmpty(value)) { - Log.Debug("**Actuate** " + widget.Name + " Value: " + value); + _logger?.LogDebug("**Actuate** {WidgetName} Value: {Value}", widget.Name, value); _dialogPanel.OnButtonActuated(widget); } @@ -595,7 +599,7 @@ form is IScannerPanel && Windows.DockWithScanner(_form, form, Context.AppWindowPosition, false); } - Log.Debug("Left: " + _form.Left); + _logger?.LogDebug("Left: {Left}", _form.Left); if (_form.Left < 0) { diff --git a/src/Libraries/ACATCore/PanelManagement/Common/ScannerCommon.cs b/src/Libraries/ACATCore/PanelManagement/Common/ScannerCommon.cs index 314506a3..51827144 100644 --- a/src/Libraries/ACATCore/PanelManagement/Common/ScannerCommon.cs +++ b/src/Libraries/ACATCore/PanelManagement/Common/ScannerCommon.cs @@ -156,7 +156,7 @@ public ScannerCommon(IScannerPanel iScannerPanel, ILogger logger HideScannerOnIdle = CoreGlobals.AppPreferences.HideScannerOnIdle; _syncLock = new SyncLock(); - _userControlManager = new UserControlManager(iScannerPanel, TextController); + _userControlManager = new UserControlManager(iScannerPanel, TextController, LoggingConfiguration.CreateLogger()); } /// @@ -663,7 +663,7 @@ public void OnLoad() /// public void OnPause(PauseDisplayMode mode = PauseDisplayMode.Default) { - Log.Debug("CALIBTEST_isPaused: " + _isPaused); + _logger?.LogDebug("CALIBTEST_isPaused: " + _isPaused); if (_isPaused) { return; @@ -675,18 +675,18 @@ public void OnPause(PauseDisplayMode mode = PauseDisplayMode.Default) { if (DialogMode) { - Log.Debug("CALIBTEST Dialog mode is true. Returning"); + _logger?.LogDebug("CALIBTEST Dialog mode is true. Returning"); return; } - Log.Verbose("CALIBTEST Pausing animation manager"); + _logger?.LogTrace("CALIBTEST Pausing animation manager"); AnimationManager.Pause(); - Log.Verbose("CALIBTEST calling setDisplayStateOnpause"); + _logger?.LogTrace("CALIBTEST calling setDisplayStateOnpause"); setDisplayStateOnPause(mode); } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger?.LogError(ex.ToString()); } } @@ -695,7 +695,7 @@ public void OnPause(PauseDisplayMode mode = PauseDisplayMode.Default) /// public void OnResume() { - Log.Debug("CALIBTEST Scannercommon2 OnResume. is_paused: " + _isPaused); + _logger?.LogDebug("CALIBTEST Scannercommon2 OnResume. is_paused: " + _isPaused); if (!_isPaused) { return; @@ -707,10 +707,10 @@ public void OnResume() { PositionSizeController.ScaleForm(); - Log.Verbose("CALIBTEST Scannercommon2 Showing scanner"); + _logger?.LogTrace("CALIBTEST Scannercommon2 Showing scanner"); ShowScanner(); - Log.Verbose("CALIBTEST Calling Animationmanager resume"); + _logger?.LogTrace("CALIBTEST Calling Animationmanager resume"); AnimationManager.Resume(); updateStatusBar(); @@ -722,7 +722,7 @@ public void OnResume() } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger?.LogError(ex.ToString()); } } @@ -809,7 +809,7 @@ protected virtual void Dispose(bool disposing) // Check to see if Dispose has already been called. if (!_disposed) { - Log.Verbose(); + _logger?.LogTrace("Dispose called"); if (disposing) { @@ -875,7 +875,7 @@ widget is WordListItemWidget || SendKeys.SendWait(widget.Value + " "); Context.AppAgentMgr.TextChangedNotifications.Release(); CoreGlobals.Stopwatch1.Stop(); - Log.Verbose("TimeElapsed 1: " + CoreGlobals.Stopwatch1.ElapsedMilliseconds); + _logger?.LogTrace("TimeElapsed 1: " + CoreGlobals.Stopwatch1.ElapsedMilliseconds); } else { @@ -885,7 +885,7 @@ widget is WordListItemWidget || actuateKey(button.GetWidgetAttribute(), widget.Value[0]); CoreGlobals.Stopwatch1.Stop(); - Log.Verbose("TimeElapsed 2 : " + CoreGlobals.Stopwatch1.ElapsedMilliseconds); + _logger?.LogTrace("TimeElapsed 2 : " + CoreGlobals.Stopwatch1.ElapsedMilliseconds); } } @@ -900,7 +900,7 @@ widget is WordListItemWidget || /// String to send private void actuateKey(WidgetAttribute widgetAttribute, char value) { - Log.Verbose(value.ToString()); + _logger?.LogTrace(value.ToString()); if (!TextController.HandlePunctuation(widgetAttribute.Modifiers, value)) { if ((KeyStateTracker.IsShiftOn() || KeyStateTracker.IsCapsLockOn()) && @@ -924,7 +924,7 @@ private void actuateKey(WidgetAttribute widgetAttribute, char value) /// value of the key private void actuateVirtualKey(WidgetAttribute widgetAttribute, string value) { - Log.Verbose("VirtualKey: " + value); + _logger?.LogTrace("VirtualKey: " + value); Keys key = TextController.MapVirtualKey(value); if (key == Keys.Escape && _dialogMode) @@ -953,7 +953,7 @@ private void animationManager_EvtPlayerStateChanged(object sender, PlayerStateCh try { var newState = _animationManager.GetPlayerState(); - Log.Debug(ScannerForm.Name + ": PlayerState changed from " + e.OldState + " to " + newState); + _logger?.LogDebug(ScannerForm.Name + ": PlayerState changed from " + e.OldState + " to " + newState); switch (newState) { case PlayerState.Timeout: @@ -969,7 +969,7 @@ private void animationManager_EvtPlayerStateChanged(object sender, PlayerStateCh } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger?.LogError(ex.ToString()); } } @@ -1003,7 +1003,7 @@ private bool AppAgent_EvtScannerHitTest(int x, int y) /// private void AppAgent_EvtTextChanged(object sender, EventArgs e) { - Log.Debug("Enter " + Kernel32Interop.GetCurrentThreadId()); + _logger?.LogDebug("Enter " + Kernel32Interop.GetCurrentThreadId()); try { if (Windows.GetVisible(ScannerForm) && @@ -1023,18 +1023,18 @@ ScannerForm is not MenuPanelBase && if (!abbreviationDetected && !context.TextAgent().SupportsSpellCheck()) { - Log.Verbose("Calling spellccheck " + Kernel32Interop.GetCurrentThreadId()); + _logger?.LogTrace("Calling spellccheck " + Kernel32Interop.GetCurrentThreadId()); TextController.SpellCheck(); - Log.Verbose("Returned from spellccheck " + Kernel32Interop.GetCurrentThreadId()); + _logger?.LogTrace("Returned from spellccheck " + Kernel32Interop.GetCurrentThreadId()); } } } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger?.LogError(ex.ToString()); } - Log.Verbose("Leave " + Kernel32Interop.GetCurrentThreadId()); + _logger?.LogTrace("Leave " + Kernel32Interop.GetCurrentThreadId()); } /// @@ -1044,11 +1044,11 @@ ScannerForm is not MenuPanelBase && /// event args private void AppPanelManager_EvtCalibrationEndNotify(object sender, EventArgs e) { - Log.Debug("CALIBTEST Calibration end notify for " + ScannerForm.Name); + _logger?.LogDebug("CALIBTEST Calibration end notify for " + ScannerForm.Name); if (Context.AppPanelManager.GetCurrentForm() as Form != ScannerForm) { - Log.Verbose("CALIBTESTForm is not the current form. returning " + ScannerForm.Name + " CurrentForm is " + (Context.AppPanelManager.GetCurrentForm() as Form).Name); + _logger?.LogTrace("CALIBTESTForm is not the current form. returning " + ScannerForm.Name + " CurrentForm is " + (Context.AppPanelManager.GetCurrentForm() as Form).Name); return; } @@ -1059,7 +1059,7 @@ private void AppPanelManager_EvtCalibrationEndNotify(object sender, EventArgs e) } else { - Log.Verbose("CALIBTESTCalling OnResume for scanner"); + _logger?.LogTrace("CALIBTESTCalling OnResume for scanner"); (ScannerForm as IScannerPanel).OnResume(); } } @@ -1070,11 +1070,11 @@ private void AppPanelManager_EvtCalibrationEndNotify(object sender, EventArgs e) /// event args private void AppPanelManager_EvtCalibrationStartNotify(ActuatorManagement.CalibrationNotifyEventArgs args) { - Log.Debug("CALIBTEST ScannerCommon2: Calibration start notify for " + ScannerForm.Name); + _logger?.LogDebug("CALIBTEST ScannerCommon2: Calibration start notify for " + ScannerForm.Name); if (Context.AppPanelManager.GetCurrentForm() as Form != ScannerForm) { - Log.Verbose("CALIBTEST Form is not the current form. returning " + ScannerForm.Name + " CurrentForm is " + (Context.AppPanelManager.GetCurrentForm() as Form).Name); + _logger?.LogTrace("CALIBTEST Form is not the current form. returning " + ScannerForm.Name + " CurrentForm is " + (Context.AppPanelManager.GetCurrentForm() as Form).Name); return; } @@ -1087,7 +1087,7 @@ private void AppPanelManager_EvtCalibrationStartNotify(ActuatorManagement.Calibr } else { - Log.Verbose("CALIBTEST Calling onPause for " + ScannerForm.Name); + _logger?.LogTrace("CALIBTEST Calling onPause for " + ScannerForm.Name); (ScannerForm as IScannerPanel).OnPause(); } @@ -1165,7 +1165,7 @@ private void createIdleTimer() /// private void form_Shown(object sender, EventArgs e) { - Log.Debug("Shown " + ScannerForm.Name); + _logger?.LogDebug("Shown " + ScannerForm.Name); } /// @@ -1175,7 +1175,7 @@ private void form_Shown(object sender, EventArgs e) /// event args private void form_VisibleChanged(object sender, EventArgs e) { - Log.Debug("Form Visibility for " + ScannerForm.Name + ": " + ScannerForm.Visible); + _logger?.LogDebug("Form Visibility for " + ScannerForm.Name + ": " + ScannerForm.Visible); if (ScannerForm.Visible) { @@ -1196,7 +1196,7 @@ private void form_VisibleChanged(object sender, EventArgs e) if (_scannerPanel.PanelClass == "Alphabet") { - Log.Verbose("form_visibleChanged " + ScannerForm.Width); + _logger?.LogTrace("form_visibleChanged " + ScannerForm.Width); } notifyScannerShow(); } @@ -1232,14 +1232,14 @@ private bool initAnimationManager(PanelConfigMapEntry panelConfigMapEntry) { bool retVal = true; - _animationManager = new PanelAnimationManager(); + _animationManager = new PanelAnimationManager(LoggingConfiguration.CreateLogger()); if (_animationManager.Init(panelConfigMapEntry, _rootWidget)) { _animationManager.EvtPlayerStateChanged += animationManager_EvtPlayerStateChanged; } else { - Log.Error("Error initializing animation manager"); + _logger?.LogError("Error initializing animation manager"); _animationManager = null; retVal = false; } @@ -1255,14 +1255,14 @@ private bool initAnimationManager(PanelConfigMapEntry panelConfigMapEntry) /// true on success private bool initWidgetManager(PanelConfigMapEntry panelConfigMapEntry) { - _widgetManager = new WidgetManager(ScannerForm); + _widgetManager = new WidgetManager(ScannerForm, LoggingConfiguration.CreateLogger()); _widgetManager.Layout.SetColorScheme(ColorSchemes.ScannerSchemeName); _widgetManager.Layout.SetDisabledButtonColorScheme(ColorSchemes.DisabledScannerButtonSchemeName); bool retVal = _widgetManager.Initialize(panelConfigMapEntry.ConfigFileName); if (!retVal) { - Log.Error("Unable to initialize widget manager"); + _logger?.LogError("Unable to initialize widget manager"); } else { @@ -1302,7 +1302,7 @@ private void Interpreter_EvtRun(object sender, InterpreterRunEventArgs e) return; } - Log.Verbose(e.Script); + _logger?.LogTrace(e.Script); runCommand(e.Script); } @@ -1384,7 +1384,7 @@ private void runCommand(string command) command = command.Substring(1); } - Log.Debug("Calling scanner common runcomand with " + command); + _logger?.LogDebug("Calling scanner common runcomand with " + command); ScannerForm.Invoke(new MethodInvoker(delegate { string[] parts = command.Split('.'); @@ -1441,7 +1441,7 @@ private void ScannerForm_SizeChanged(object sender, EventArgs e) { if (_scannerPanel.PanelClass == "Alphabet") { - Log.Debug("ScannerForm_SizeChanged " + ScannerForm.Width); + _logger?.LogDebug("ScannerForm_SizeChanged " + ScannerForm.Width); } notifyScannerShow(); } @@ -1452,7 +1452,7 @@ private void ScannerForm_SizeChanged(object sender, EventArgs e) /// what to do? private void setDisplayStateOnPause(PauseDisplayMode mode) { - Log.Debug("setDisplayStateOnPause. mode: " + mode); + _logger?.LogDebug("setDisplayStateOnPause. mode: " + mode); if (mode == PauseDisplayMode.None) { return; @@ -1484,7 +1484,7 @@ private void setWidgetEnabledStates(WindowActivityMonitorInfo monitorInfo) { if (_syncLock.IsClosing()) { - Log.Debug("Form is closing " + ScannerForm.Name); + _logger?.LogDebug("Form is closing " + ScannerForm.Name); WindowActivityMonitor.EvtWindowMonitorHeartbeat -= WindowActivityMonitor_EvtWindowMonitorHeartbeat; return; } @@ -1513,7 +1513,7 @@ private void setWidgetEnabledStates(WindowActivityMonitorInfo monitorInfo) break; } - Log.Verbose("widget.Enabled set to : " + widget.Enabled + " for feature " + widget.SubClass); + _logger?.LogTrace("widget.Enabled set to : " + widget.Enabled + " for feature " + widget.SubClass); } } } @@ -1551,7 +1551,7 @@ private void subscribeToEvents() AnimationManager.Interpreter.EvtRun -= Interpreter_EvtRun; AnimationManager.Interpreter.EvtRun += Interpreter_EvtRun; - Log.Debug("Subscribing on instance " + AnimationManager.Interpreter.GetHashCode()); + _logger?.LogDebug("Subscribing on instance " + AnimationManager.Interpreter.GetHashCode()); AnimationManager.Interpreter.EvtShowPopup -= Interpreter_EvtShowPopup; AnimationManager.Interpreter.EvtShowPopup += Interpreter_EvtShowPopup; subscribeToButtonEvents(); @@ -1564,7 +1564,7 @@ private void subscribeToEvents() /// text to convert private void textToSpeech(string text) { - Log.Debug("Convert to speech. text=" + text); + _logger?.LogDebug("Convert to speech. text=" + text); Context.AppTTSManager.ActiveEngine.Speak(text); AuditLog.Audit(new AuditEventTextToSpeech(Context.AppTTSManager.ActiveEngine.Descriptor.Name)); } @@ -1626,7 +1626,7 @@ private void widget_EvtActuated(object sender, WidgetActuatedEventArgs e) var value = widget.Value; if (!string.IsNullOrEmpty(value)) { - Log.Debug("**Actuate** " + widget.Name + " Value: " + value); + _logger?.LogDebug("**Actuate** " + widget.Name + " Value: " + value); actuateButton(widget); } @@ -1666,7 +1666,7 @@ private void Windows_EvtWindowPositionChanged(Form form, Windows.WindowPosition if (_scannerPanel.PanelClass == "Alphabet") { - Log.Debug("WindowPosChanged" + ScannerForm.Width); + _logger?.LogDebug("WindowPosChanged" + ScannerForm.Width); } notifyScannerShow(); } diff --git a/src/Libraries/ACATCore/PanelManagement/Common/ScannerPositionSizeController.cs b/src/Libraries/ACATCore/PanelManagement/Common/ScannerPositionSizeController.cs index dd4b5199..ece24508 100644 --- a/src/Libraries/ACATCore/PanelManagement/Common/ScannerPositionSizeController.cs +++ b/src/Libraries/ACATCore/PanelManagement/Common/ScannerPositionSizeController.cs @@ -8,6 +8,7 @@ using ACAT.Core.PanelManagement.Utils; using ACAT.Core.Utility; using ACAT.Core.WidgetManagement; +using Microsoft.Extensions.Logging; using System; using System.Drawing; using System.Windows.Forms; @@ -23,6 +24,8 @@ namespace ACAT.Core.PanelManagement.Common /// public class ScannerPositionSizeController { + private readonly ILogger _logger; + /// /// Multiplier to calculate the scanner size based /// on the scale factor @@ -102,8 +105,9 @@ public class ScannerPositionSizeController /// Initializes a new instance of the class. /// /// ScannerForm object associated with the form - internal ScannerPositionSizeController(ScannerCommon scannerCommon) + internal ScannerPositionSizeController(ScannerCommon scannerCommon, ILogger logger = null) { + _logger = logger; AutoPosition = true; ManualPosition = Context.AppWindowPosition; _prevAutoPositionScannerValue = AutoPosition; @@ -238,11 +242,11 @@ public void RestoreDefaults() /// public void SaveScaleSetting(SystemPreferences prefs) { - Log.Debug("saving scale factor. _scaleFactor=" + ScaleFactor); + _logger?.LogDebug("Saving scale factor: {ScaleFactor}", ScaleFactor); prefs.ScannerScaleFactor = CoreGlobals.AppPreferences.ScannerScaleFactor = Convert.ToInt16(ScaleFactor * IntMultiplier); prefs.Save(); CoreGlobals.AppPreferences.NotifyPreferencesChanged(); - Log.Debug("scale factor saved is:" + prefs.ScannerScaleFactor); + _logger?.LogDebug("Scale factor saved: {SavedScaleFactor}", prefs.ScannerScaleFactor); } /// @@ -250,16 +254,16 @@ public void SaveScaleSetting(SystemPreferences prefs) /// public void SaveSettings(SystemPreferences prefs) { - Log.Debug("saving scale factor. _scaleFactor=" + ScaleFactor); + _logger?.LogDebug("Saving scale factor: {ScaleFactor}", ScaleFactor); prefs.ScannerScaleFactor = CoreGlobals.AppPreferences.ScannerScaleFactor = Convert.ToInt16(ScaleFactor * IntMultiplier); - Log.Debug("Saving window position as " + Context.AppWindowPosition); + _logger?.LogDebug("Saving window position: {WindowPosition}", Context.AppWindowPosition); prefs.ScannerPosition = CoreGlobals.AppPreferences.ScannerPosition = Context.AppWindowPosition; prefs.Save(); AutoPosition = true; CoreGlobals.AppPreferences.NotifyPreferencesChanged(); - Log.Debug("scale factor saved is:" + prefs.ScannerScaleFactor); + _logger?.LogDebug("Scale factor saved: {SavedScaleFactor}", prefs.ScannerScaleFactor); } /// @@ -277,7 +281,7 @@ public void ScaleDefault() /// public void ScaleDown() { - Log.Debug("scaling down. _scaleFactor=" + ScaleFactor + " SCALE_FACTOR_MINIMUM=" + ScaleFactorMinimum); + _logger?.LogDebug("Scaling down - current scale factor: {ScaleFactor}, minimum: {Minimum}", ScaleFactor, ScaleFactorMinimum); if (ScaleFactor > ScaleFactorMinimum) { ScaleFactor -= ScaleFactorAmount; @@ -308,13 +312,12 @@ public void ScaleForm() /// the scale factor public void ScaleForm(float scaleFactor) { - Log.Debug("Enter. scaleFactor: " + scaleFactor); + _logger?.LogDebug("Scaling form - scale factor: {ScaleFactor}", scaleFactor); var newSize = new Size(Convert.ToInt32(_originalSize.Width * scaleFactor), Convert.ToInt32(_originalSize.Height * scaleFactor)); - Log.Debug(_form.Name + "," + "scalefactor: " + scaleFactor + - "orig/new width: " + _originalSize.Width + ", " + newSize.Width + - "orig/new height: " + _originalSize.Height + ", " + newSize.Height); + _logger?.LogDebug("Form: {FormName}, scale factor: {ScaleFactor}, original width: {OrigWidth}, new width: {NewWidth}, original height: {OrigHeight}, new height: {NewHeight}", + _form.Name, scaleFactor, _originalSize.Width, newSize.Width, _originalSize.Height, newSize.Height); //_rootWidget.Dump(); @@ -323,7 +326,7 @@ public void ScaleForm(float scaleFactor) _form.Size = newSize; - Log.Debug("Exit"); + _logger?.LogDebug("Form scaling complete"); } /// @@ -331,8 +334,7 @@ public void ScaleForm(float scaleFactor) /// public void ScaleUp() { - Log.Debug("Enter"); - Log.Debug("scaling up. _scaleFactor=" + ScaleFactor + " SCALE_FACTOR_MAXIMUM=" + ScaleFactorMaximum); + _logger?.LogDebug("Scaling up - current scale factor: {ScaleFactor}, maximum: {Maximum}", ScaleFactor, ScaleFactorMaximum); if (ScaleFactor < ScaleFactorMaximum) { ScaleFactor += ScaleFactorAmount; @@ -340,7 +342,7 @@ public void ScaleUp() SetPositionAndNotify(); } - Log.Debug("Exit"); + _logger?.LogDebug("Scale up complete"); } /// @@ -374,7 +376,7 @@ private void _autoPostionScanner_EvtAutoPostionScannerStopped(object sender, Eve /// private void _form_ResizeEnd(object sender, EventArgs e) { - Log.Debug("Formwidth: " + _form.Width + ", originalWidth: " + _originalSize.Width); + _logger?.LogDebug("Form resize end - form width: {Width}, original width: {OriginalWidth}", _form.Width, _originalSize.Width); float aspectRatio = (float)_originalSize.Width / _originalSize.Height; float scaleFactor = 0.0f; @@ -444,7 +446,7 @@ private void resizeScannerToFitDesktop(float scaleFactor) { _form.Invoke(new MethodInvoker(delegate { - Log.Debug("Enter. scaleFactor: " + scaleFactor); + _logger?.LogDebug("Resizing scanner to fit desktop - scale factor: {ScaleFactor}", scaleFactor); var newSize = new Size(Convert.ToInt32(_originalSize.Width * scaleFactor), Convert.ToInt32(_originalSize.Height * scaleFactor)); diff --git a/src/Libraries/ACATCore/PanelManagement/Common/Splash.cs b/src/Libraries/ACATCore/PanelManagement/Common/Splash.cs index 5920bbe6..6664a719 100644 --- a/src/Libraries/ACATCore/PanelManagement/Common/Splash.cs +++ b/src/Libraries/ACATCore/PanelManagement/Common/Splash.cs @@ -6,6 +6,7 @@ //////////////////////////////////////////////////////////////////////////// using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Diagnostics; using System.Threading; @@ -21,6 +22,8 @@ namespace ACAT.Core.PanelManagement.Common /// public class Splash { + private static readonly ILogger _logger = LoggingConfiguration.CreateLogger(typeof(Splash).Name); + /// /// The splash screen form /// @@ -70,7 +73,7 @@ public void Close() } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex, ex.Message); } } diff --git a/src/Libraries/ACATCore/PanelManagement/Common/TextController.cs b/src/Libraries/ACATCore/PanelManagement/Common/TextController.cs index 603a16b7..74a5d352 100644 --- a/src/Libraries/ACATCore/PanelManagement/Common/TextController.cs +++ b/src/Libraries/ACATCore/PanelManagement/Common/TextController.cs @@ -310,7 +310,7 @@ public Abbreviation CheckAndReplaceAbbreviation(ref bool handled) } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, ex.Message); } return abbr; @@ -345,26 +345,25 @@ public void DeletePreviousWord() caretPos == _autoCompleteCaretPos && _beforeAutoCompleteCaretPos >= 0) { - Log.Debug("Delete: _autoCompleteCaretPos: " + _autoCompleteCaretPos + - ", _beforeAutoCOmpleteCaretPos: " + _beforeAutoCompleteCaretPos + ", count: " + - (_autoCompleteCaretPos - _beforeAutoCompleteCaretPos)); + _logger.LogDebug("Delete: _autoCompleteCaretPos: {AutoCompleteCaretPos}, _beforeAutoCompleteCaretPos: {BeforeAutoCompleteCaretPos}, count: {Count}", + _autoCompleteCaretPos, _beforeAutoCompleteCaretPos, (_autoCompleteCaretPos - _beforeAutoCompleteCaretPos)); int prefixLen = _autoCompletePartialWord.Length; - Log.Debug("prefixLen: " + prefixLen); + _logger.LogDebug("prefixLen: {PrefixLen}", prefixLen); if (prefixLen > 0) { int start = _autocompleteStartOffset; - Log.Debug("start: " + start); + _logger.LogDebug("start: {Start}", start); start = Math.Max(0, start); - Log.Debug("Deleting from " + start + ", numchars: " + (_autoCompleteCaretPos - start)); + _logger.LogDebug("Deleting from {Start}, numchars: {NumChars}", start, (_autoCompleteCaretPos - start)); context.TextAgent().Delete(start, _autoCompleteCaretPos - start); - Log.Debug("Inserting at " + start + ", string: " + _autoCompletePartialWord); + _logger.LogDebug("Inserting at {Start}, string: {String}", start, _autoCompletePartialWord); context.TextAgent().Insert(start, _autoCompletePartialWord); } else { - Log.Debug("Delete from " + _beforeAutoCompleteCaretPos); + _logger.LogDebug("Delete from {BeforeAutoCompleteCaretPos}", _beforeAutoCompleteCaretPos); context.TextAgent().Delete(_beforeAutoCompleteCaretPos, _autoCompleteCaretPos - _beforeAutoCompleteCaretPos); } } @@ -379,7 +378,7 @@ public void DeletePreviousWord() } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, ex.Message); } finally { @@ -422,7 +421,7 @@ public void HandleAlphaNumericChar(char inputChar) /// true on success public bool HandlePunctuation(ArrayList modifiers, char punctuation) { - Log.Verbose(); + _logger.LogTrace("HandlePunctuation called with punctuation: {Punctuation}", punctuation); try { @@ -455,15 +454,15 @@ public bool HandlePunctuation(ArrayList modifiers, char punctuation) { // delete any spaces before the punctuation context.TextAgent().GetPrecedingWhiteSpaces(out int offset, out int count); - Log.Debug("Preceding whitespace count: " + count); + _logger.LogDebug("Preceding whitespace count: {Count}", count); if (count > 0) { - Log.Debug("Deleting whitespaces from offset " + offset); + _logger.LogDebug("Deleting whitespaces from offset {Offset}", offset); context.TextAgent().Delete(offset, count); } } - Log.Debug("Sending punctuation"); + _logger.LogDebug("Sending punctuation"); Context.AppAgentMgr.Keyboard.Send(modifiers != null ? modifiers.Cast().ToList() : KeyStateTracker.GetExtendedKeys(), punctuation); @@ -475,7 +474,7 @@ public bool HandlePunctuation(ArrayList modifiers, char punctuation) _autoCompleteCaretPos = context.TextAgent().GetCaretPos(); - Log.Debug("after actuating, caretpos is " + _autoCompleteCaretPos); + _logger.LogDebug("after actuating, caretpos is {CaretPos}", _autoCompleteCaretPos); KeyStateTracker.KeyTriggered(punctuation); @@ -483,7 +482,7 @@ public bool HandlePunctuation(ArrayList modifiers, char punctuation) } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, ex.Message); } finally { @@ -517,7 +516,7 @@ public void HandleVirtualKey(ArrayList modifiers, string value) } catch { - Log.Error("Invalid virtual key " + value.Substring(1)); + _logger.LogError("Invalid virtual key {VirtualKey}", value.Substring(1)); } } @@ -535,7 +534,7 @@ public Keys MapVirtualKey(string value) } catch { - Log.Error("Invalid virtual key " + value.Substring(1)); + _logger.LogError("Invalid virtual key {VirtualKey}", value.Substring(1)); return Keys.None; } @@ -578,8 +577,8 @@ public void SmartDeletePrevWord() { try { - Log.Debug("LastAction: " + _lastAction + ", currentEditingMode: " + - Context.AppAgentMgr.CurrentEditingMode); + _logger.LogDebug("LastAction: {LastAction}, currentEditingMode: {CurrentEditingMode}", + _lastAction, Context.AppAgentMgr.CurrentEditingMode); using (var context = Context.AppAgentMgr.ActiveContext()) { @@ -608,7 +607,7 @@ public void SmartDeletePrevWord() } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, ex.Message); } _lastAction = LastAction.Unknown; @@ -627,15 +626,15 @@ public void SpellCheck() return; } - Log.Debug("char left of caret: [" + charAtCaret + "]"); + _logger.LogDebug("char left of caret: [{CharAtCaret}]", charAtCaret); if (!TextUtils.IsTerminatorOrWhiteSpace(charAtCaret)) { - Log.Debug("no sentence terminator or white space here. returning"); + _logger.LogDebug("no sentence terminator or white space here. returning"); return; } int startPos = AgentManager.Instance.TextControlAgent.GetPreviousWordAtCaret(out string word); - Log.Debug("Prev word: [" + word + "]"); + _logger.LogDebug("Prev word: [{Word}]", word); if (string.IsNullOrEmpty(word)) { return; @@ -643,9 +642,9 @@ public void SpellCheck() bool isFirstWord = AgentManager.Instance.TextControlAgent.IsPreviousWordAtCaretTheFirstWord(); - Log.Debug("Looking up " + word); + _logger.LogDebug("Looking up {Word}", word); string replacement = Context.AppSpellCheckManager.ActiveSpellChecker.Lookup(word); - Log.Debug("Replacement is [" + replacement + "]"); + _logger.LogDebug("Replacement is [{Replacement}]", replacement); if (string.IsNullOrEmpty(replacement) && isFirstWord) { replacement = word; @@ -670,8 +669,8 @@ public void UndoLastEditChange() { try { - Log.Debug("LastAction: " + _lastAction + ", currentEditingMode: " + - Context.AppAgentMgr.CurrentEditingMode); + _logger.LogDebug("LastAction: {LastAction}, currentEditingMode: {CurrentEditingMode}", + _lastAction, Context.AppAgentMgr.CurrentEditingMode); if (Context.AppAgentMgr.CurrentEditingMode != EditingMode.TextEntry) { @@ -715,7 +714,7 @@ public void UndoLastEditChange() } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, ex.Message); } _lastAction = LastAction.Unknown; @@ -760,7 +759,7 @@ private void deletePreviousPunctuation() { int numChars = 2; // punctuation + space after punctuation context.TextAgent().GetPrecedingCharacters(numChars, out string precedingChars); - Log.Debug("prev " + numChars + " chars are : [" + precedingChars + "]"); + _logger.LogDebug("prev {NumChars} chars are : [{PrecedingChars}]", numChars, precedingChars); if (precedingChars.Length == numChars && ResourceUtils.LanguageSettings().IsInsertSpaceAfterChar(precedingChars[0])) { Context.AppAgentMgr.Keyboard.Send(Keys.Back, numChars); @@ -778,7 +777,7 @@ private void deletePreviousPunctuation() } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, ex.Message); } } @@ -795,12 +794,12 @@ private void postAutoCompleteWord() { bool retVal = context.TextAgent().GetCharAtCaret(out char charAtCaret); - Log.Debug("charAtCaret is " + Convert.ToInt32(charAtCaret)); + _logger.LogDebug("charAtCaret is {CharAtCaretInt}", Convert.ToInt32(charAtCaret)); if (!char.IsPunctuation(charAtCaret) && (!retVal || charAtCaret == 0x0D || !char.IsWhiteSpace(charAtCaret))) { - Log.Debug("Sending space suffix... caretpos is " + context.TextAgent().GetCaretPos()); + _logger.LogDebug("Sending space suffix... caretpos is {CaretPos}", context.TextAgent().GetCaretPos()); Context.AppAgentMgr.Keyboard.Send(KeyStateTracker.GetExtendedKeys(), ' '); - Log.Debug("Done sending space suffix caretPos is " + context.TextAgent().GetCaretPos()); + _logger.LogDebug("Done sending space suffix caretPos is {CaretPos}", context.TextAgent().GetCaretPos()); KeyStateTracker.KeyTriggered(' '); } else if (char.IsWhiteSpace(charAtCaret)) @@ -812,7 +811,7 @@ private void postAutoCompleteWord() } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, ex.Message); } } @@ -831,9 +830,9 @@ private void replaceMisspeltWord(string word, string replacement, int startPos, { using AgentContext context = Context.AppAgentMgr.ActiveContext(); string textToCaret = context.TextAgent().GetStringToCaret(startPos); - Log.Debug("textToCaret : [" + textToCaret + "]"); + _logger.LogDebug("textToCaret : [{TextToCaret}]", textToCaret); replacement = textToCaret.Replace(word, replacement); - Log.Debug("After replacement, replacement : [" + replacement + "]"); + _logger.LogDebug("After replacement, replacement : [{Replacement}]", replacement); if (isFirstWord) { string cap = TextUtils.Capitalize(replacement); @@ -843,14 +842,14 @@ private void replaceMisspeltWord(string word, string replacement, int startPos, } } - Log.Debug("Replace word at " + startPos + ". Length: " + replacement.Length + ". replacement: " + - replacement); + _logger.LogDebug("Replace word at {StartPos}. Length: {Length}. replacement: {Replacement}", + startPos, replacement.Length, replacement); context.TextAgent().Replace(startPos, word.Length + 1, replacement); } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, ex.Message); } } diff --git a/src/Libraries/ACATCore/PanelManagement/Context.cs b/src/Libraries/ACATCore/PanelManagement/Context.cs index 6f38f83a..7e141714 100644 --- a/src/Libraries/ACATCore/PanelManagement/Context.cs +++ b/src/Libraries/ACATCore/PanelManagement/Context.cs @@ -16,6 +16,7 @@ using ACAT.Core.Utility; using ACAT.Core.WidgetManagement; using ACAT.Core.WordPredictorManagement; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Globalization; @@ -37,17 +38,17 @@ namespace ACAT.Core.PanelManagement /// public class Context { - private static readonly AbbreviationsManager _abbreviationsManager; - private static readonly ActuatorManager _actuatorManager; - private static readonly AgentManager _agentManager; - private static readonly AutomationEventManager _automationEventManager; - private static readonly CommandManager _commandManager; + private static readonly Lazy _abbreviationsManager = new Lazy(() => AbbreviationsManager.Instance); + private static readonly Lazy _actuatorManager = new Lazy(() => ActuatorManager.Instance); + private static readonly Lazy _agentManager = new Lazy(() => AgentManager.Instance); + private static readonly Lazy _automationEventManager = new Lazy(() => AutomationEventManager.Instance); + private static readonly Lazy _commandManager = new Lazy(() => CommandManager.Instance); private static readonly List _extensionDirs = new(); - private static readonly PanelManager _panelManager; - private static readonly SpellCheckManager _spellCheckManager; - private static readonly ThemeManager _themeManager; - private static readonly TTSManager _ttsManager; - private static readonly WordPredictionManager _wordPredictionManager; + private static readonly Lazy _panelManager = new Lazy(() => PanelManager.Instance); + private static readonly Lazy _spellCheckManager = new Lazy(() => SpellCheckManager.Instance); + private static readonly Lazy _themeManager = new Lazy(() => ThemeManager.Instance); + private static readonly Lazy _ttsManager = new Lazy(() => TTSManager.Instance); + private static readonly Lazy _wordPredictionManager = new Lazy(() => WordPredictionManager.Instance); /// /// Error message if there was an error during initialization @@ -77,17 +78,8 @@ static Context() AppQuit = false; AppWindowPosition = Windows.WindowPosition.CenterScreen; - //Initialize all the manager singleton objects - _abbreviationsManager = AbbreviationsManager.Instance; - _actuatorManager = ActuatorManager.Instance; - _agentManager = AgentManager.Instance; - _panelManager = PanelManager.Instance; - _ttsManager = TTSManager.Instance; - _automationEventManager = AutomationEventManager.Instance; - _wordPredictionManager = WordPredictionManager.Instance; - _spellCheckManager = SpellCheckManager.Instance; - _themeManager = ThemeManager.Instance; - _commandManager = CommandManager.Instance; + // Manager singleton objects will be initialized lazily on first access + // This allows Context.ServiceProvider to be set before managers are created } /// @@ -120,7 +112,7 @@ public enum StartupFlags /// public static AbbreviationsManager AppAbbreviationsManager { - get { return _abbreviationsManager; } + get { return _abbreviationsManager.Value; } } /// @@ -128,7 +120,7 @@ public static AbbreviationsManager AppAbbreviationsManager /// public static ActuatorManager AppActuatorManager { - get { return _actuatorManager; } + get { return _actuatorManager.Value; } } /// @@ -136,7 +128,7 @@ public static ActuatorManager AppActuatorManager /// public static AgentManager AppAgentMgr { - get { return _agentManager; } + get { return _agentManager.Value; } } /// @@ -144,12 +136,12 @@ public static AgentManager AppAgentMgr /// public static AutomationEventManager AppAutomationEventManger { - get { return _automationEventManager; } + get { return _automationEventManager.Value; } } public static CommandManager AppCommandManager { - get { return _commandManager; } + get { return _commandManager.Value; } } /// @@ -157,7 +149,7 @@ public static CommandManager AppCommandManager /// public static PanelManager AppPanelManager { - get { return _panelManager; } + get { return _panelManager.Value; } } /// @@ -170,7 +162,7 @@ public static PanelManager AppPanelManager /// public static SpellCheckManager AppSpellCheckManager { - get { return _spellCheckManager; } + get { return _spellCheckManager.Value; } } /// @@ -178,7 +170,7 @@ public static SpellCheckManager AppSpellCheckManager /// public static ThemeManager AppThemeManager { - get { return _themeManager; } + get { return _themeManager.Value; } } /// @@ -186,7 +178,7 @@ public static ThemeManager AppThemeManager /// public static TTSManager AppTTSManager { - get { return _ttsManager; } + get { return _ttsManager.Value; } } /// @@ -199,7 +191,7 @@ public static TTSManager AppTTSManager /// public static WordPredictionManager AppWordPredictionManager { - get { return _wordPredictionManager; } + get { return _wordPredictionManager.Value; } } /// @@ -234,6 +226,11 @@ public static IEnumerable ExtensionDirs /// public static bool ShowTalkWindowOnStartup { get; set; } + /// + /// Gets or sets the service provider for dependency injection in extension instantiation + /// + public static IServiceProvider ServiceProvider { get; set; } + ///// ///// Changes the culture to the specified culture ///// @@ -383,7 +380,7 @@ public static bool Init(StartupFlags startup = StartupFlags.All) retVal = false; } - Log.Debug("Returning " + retVal + " from context init"); + LoggingConfiguration.CreateLogger().LogDebug("Returning {RetVal} from context init", retVal); return retVal; } diff --git a/src/Libraries/ACATCore/PanelManagement/PanelConfig/PanelConfigMap.cs b/src/Libraries/ACATCore/PanelManagement/PanelConfig/PanelConfigMap.cs index ec8195c2..71229a3b 100644 --- a/src/Libraries/ACATCore/PanelManagement/PanelConfig/PanelConfigMap.cs +++ b/src/Libraries/ACATCore/PanelManagement/PanelConfig/PanelConfigMap.cs @@ -7,6 +7,7 @@ using ACAT.Core.UserManagement; using ACAT.Core.Utility; using ACAT.Core.Utility.TypeLoader; +using Microsoft.Extensions.Logging; using System; using System.Collections; using System.Collections.Generic; @@ -28,6 +29,8 @@ namespace ACAT.Core.PanelManagement.PanelConfig /// public class PanelConfigMap { + private static readonly ILogger _logger = LoggingConfiguration.CreateLogger(); + /// /// Name of the panel class config file. This file contains a /// list of panel configurations to use @@ -237,7 +240,7 @@ public static bool Load(IEnumerable extensionDirs) var agents = AgentManager.Instance.GetExtensions(); foreach (IApplicationAgent agent in agents.Cast()) { - Log.Debug("Loading agent " + agent); + _logger?.LogDebug("Loading agent {Agent}", agent); addTypeToCache(agent.GetType()); } @@ -251,7 +254,7 @@ public static bool Load(IEnumerable extensionDirs) } var configsDir = FileUtils.GetPanelConfigDir(); - Log.Debug($"Loading resources from {configsDir}"); + _logger?.LogDebug("Loading resources from {ConfigsDir}", configsDir); if (Directory.Exists(Path.Combine(configsDir, "common"))) { @@ -377,11 +380,11 @@ internal static void AddFormToCache(Guid guid, Type type) { if (_formsCache.ContainsKey(guid)) { - Log.Debug("Form Type " + type.FullName + ", guid " + guid + " is already added"); + _logger?.LogDebug("Form Type {TypeName} with guid {Guid} is already added", type.FullName, guid); return; } - Log.Debug("Adding form " + type.FullName + ", guid " + guid + " to cache"); + _logger?.LogDebug("Adding form {TypeName} with guid {Guid} to cache", type.FullName, guid); _formsCache.Add(guid, type); updateFormTypeReferences(guid, type); @@ -393,29 +396,29 @@ internal static void AddFormToCache(Guid guid, Type type) /// internal static void CleanupOrphans() { - Log.Debug("Cleaning up panelConfigMap entries..."); + _logger?.LogDebug("Cleaning up panelConfigMap entries"); var removeList = new List(); foreach (var mapEntry in _masterPanelConfigMapTable.Values) { - Log.Debug("Looking up " + mapEntry.ToString()); + _logger?.LogDebug("Looking up entry: {Entry}", mapEntry.ToString()); if (_formsCache.ContainsKey(mapEntry.FormId)) { mapEntry.FormType = (Type)_formsCache[mapEntry.FormId]; } - Log.IsNull("mapEntry.FormType ", mapEntry.FormType); + _logger?.LogTrace("FormType is null: {IsNull}", mapEntry.FormType == null); var configFilePath = getConfigFilePathFromLocationMap(mapEntry.ConfigFileName); if (mapEntry.FormType != null && !string.IsNullOrEmpty(configFilePath)) { - Log.Debug("Yes. _configFileLocationMap has configFile " + mapEntry.ConfigFileName); + _logger?.LogDebug("Found config file {ConfigFileName} in location map", mapEntry.ConfigFileName); mapEntry.ConfigFileName = configFilePath; } else { - Log.Debug("No. _configFileLocationMap does not have configFile " + mapEntry.ConfigFileName); + _logger?.LogDebug("Config file {ConfigFileName} not found in location map - marking for removal", mapEntry.ConfigFileName); removeList.Add(mapEntry); } } @@ -448,7 +451,7 @@ internal static Guid GetFormId(Type type) } else { - Log.Error("Type " + type.FullName + " does not have a valid ACAT descriptor guid"); + _logger?.LogError("Type {TypeName} does not have a valid ACAT descriptor guid", type.FullName); } } @@ -661,7 +664,7 @@ private static bool loadTypesFromAssembly(Assembly assembly) } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger?.LogError(ex, "Error loading types from assembly"); retVal = false; } @@ -684,26 +687,26 @@ private static void onDllFound(string dllName) try { - Log.Debug("Found dll " + dllName); + _logger?.LogDebug("Found dll {DllName}", dllName); typeLoader.LoadFromAssembly(dllName, false); foreach (var type in typeLoader.LoadedTypes.Values) { - Log.Debug("Found type " + type.FullName); + _logger?.LogDebug("Found type {TypeName}", type.FullName); addTypeToCache(type); } } catch (BadImageFormatException ex) { - Log.Exception($"Error loading dll {dllName} Exception: {ex.Message}"); + _logger?.LogError(ex, "Error loading dll {DllName}", dllName); //_DLLError = true; } catch (Exception ex) { - Log.Exception($"Error loading dll{dllName} Exception: {ex.Message}"); + _logger?.LogError(ex, "Error loading dll {DllName}", dllName); _DLLError = true; } } @@ -738,7 +741,7 @@ private static void onPanelConfigMapFileFound(string configFileName) } catch (Exception ex) { - Log.Exception(ex); + _logger?.LogError(ex, "Error loading panel config map"); } } /// @@ -758,12 +761,12 @@ private static void onXmlFileFound(string xmlFileName) if (_loadConfigFileLocationMap.ContainsKey(fileName)) { - Log.Debug($"Updating xmlfile {fileName}, fullPath: {xmlFileName}"); + _logger?.LogDebug("Updating xml file {FileName}, full path: {FullPath}", fileName, xmlFileName); _loadConfigFileLocationMap[fileName] = xmlFileName; } else { - Log.Debug($"Adding xmlfile {fileName}, fullPath: {xmlFileName}"); + _logger?.LogDebug("Adding xml file {FileName}, full path: {FullPath}", fileName, xmlFileName); _loadConfigFileLocationMap.Add(fileName, xmlFileName); } } diff --git a/src/Libraries/ACATCore/PanelManagement/PanelConfig/PanelConfigMapEntry.cs b/src/Libraries/ACATCore/PanelManagement/PanelConfig/PanelConfigMapEntry.cs index 0992d7fe..044c6c89 100644 --- a/src/Libraries/ACATCore/PanelManagement/PanelConfig/PanelConfigMapEntry.cs +++ b/src/Libraries/ACATCore/PanelManagement/PanelConfig/PanelConfigMapEntry.cs @@ -6,6 +6,7 @@ //////////////////////////////////////////////////////////////////////////// using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Xml; @@ -18,6 +19,8 @@ namespace ACAT.Core.PanelManagement.PanelConfig /// public class PanelConfigMapEntry { + private static readonly ILogger _logger = LoggingConfiguration.CreateLogger(typeof(PanelConfigMapEntry).Name); + private readonly Dictionary _userControlsDict = new(); /// @@ -175,7 +178,7 @@ public override string ToString() { if (FormType == null) { - Log.Debug("FORM TYPE IS NULL"); + _logger.LogDebug("FORM TYPE IS NULL"); } return "PanelConfigMapEntry. configName: " + ConfigName + diff --git a/src/Libraries/ACATCore/PanelManagement/PanelConfig/PreferredPanelConfig.cs b/src/Libraries/ACATCore/PanelManagement/PanelConfig/PreferredPanelConfig.cs index 07da4242..ede8096c 100644 --- a/src/Libraries/ACATCore/PanelManagement/PanelConfig/PreferredPanelConfig.cs +++ b/src/Libraries/ACATCore/PanelManagement/PanelConfig/PreferredPanelConfig.cs @@ -24,6 +24,7 @@ using System.IO; using System.Xml; using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; #region SupressStyleCopWarnings @@ -69,6 +70,8 @@ namespace ACAT.Core.PanelManagement /// internal class PreferredPanelConfig { + private static readonly ILogger _logger = LoggingConfiguration.CreateLogger(); + /// /// Name of the preferred config file /// @@ -226,8 +229,7 @@ private bool loadPreferredPanelConfig(String file) String name = XmlUtils.GetXMLAttrString(node, "name").ToLower().Trim(); if (String.IsNullOrEmpty(name) || _mapping.ContainsKey(name)) { - Log.Debug("PreferredPanelconfig will not be added. Name either already exists or is empty " + - name); + _logger.LogDebug("PreferredPanelconfig will not be added. Name either already exists or is empty {Name}", name); continue; } @@ -240,7 +242,7 @@ private bool loadPreferredPanelConfig(String file) } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex, "Error loading preferred panel config"); retVal = false; } diff --git a/src/Libraries/ACATCore/PanelManagement/PanelManager.cs b/src/Libraries/ACATCore/PanelManagement/PanelManager.cs index 18315835..fb9b7658 100644 --- a/src/Libraries/ACATCore/PanelManagement/PanelManager.cs +++ b/src/Libraries/ACATCore/PanelManagement/PanelManager.cs @@ -61,9 +61,15 @@ public class PanelManager : IDisposable public static String UiRootDir = ""; /// - /// Singleton instance of PanelManager + /// Singleton instance of PanelManager - lazy initialized to get logger from DI container /// - private static PanelManager _instance; + private static readonly Lazy _instance = new Lazy(() => + { + // Get logger from DI container if available, otherwise use LogManager + ILogger logger = Context.ServiceProvider?.GetService(typeof(ILogger)) as ILogger + ?? LogManager.GetLogger(); + return new PanelManager(logger); + }); /// /// Logger instance @@ -88,9 +94,9 @@ public class PanelManager : IDisposable /// /// Initializes an instance of the PanelManager /// - public PanelManager(ILogger logger = null) + public PanelManager(ILogger logger) { - _logger = logger; + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); Context.AppAgentMgr.EvtPanelRequest += AppAgent_EvtPanelRequest; Context.AppAgentMgr.EvtFocusChanged += AppAgent_EvtFocusChanged; Context.EvtCultureChanged += Context_EvtCultureChanged; @@ -160,7 +166,7 @@ public PanelManager(ILogger logger = null) /// public static PanelManager Instance { - get { return _instance ??= new PanelManager(); } + get { return _instance.Value; } } /// diff --git a/src/Libraries/ACATCore/PanelManagement/PanelStack.cs b/src/Libraries/ACATCore/PanelManagement/PanelStack.cs index 2930b5f6..5d338e92 100644 --- a/src/Libraries/ACATCore/PanelManagement/PanelStack.cs +++ b/src/Libraries/ACATCore/PanelManagement/PanelStack.cs @@ -365,12 +365,12 @@ public void CloseCurrentForm() /// public void CloseCurrentPanel() { - Log.Verbose(); + _logger?.LogTrace(nameof(CloseCurrentPanel)); bool isCurrentForm = false; if (_currentPanel != null) { - Log.Debug("Will close panel. _currentPanel.name is " + _currentPanel.Name); + _logger?.LogDebug("Will close panel. _currentPanel.name is " + _currentPanel.Name); Form f = _currentPanel; while (true) { @@ -381,18 +381,18 @@ public void CloseCurrentPanel() if (f is IScannerPanel) { - Log.Debug("panelClass: " + ((IScannerPanel)f).PanelClass); + _logger?.LogDebug("panelClass: " + ((IScannerPanel)f).PanelClass); } if (f.Owner != null) { - Log.Debug("This one has a owner"); + _logger?.LogDebug("This one has a owner"); Control form = f.Owner; f = (Form)form; } else { - Log.Debug("Setting currentpanel to null. This one does not has a owner. Closing " + + _logger?.LogDebug("Setting currentpanel to null. This one does not has a owner. Closing " + f.Name + ", type: " + f.GetType()); Windows.CloseForm(f); @@ -404,7 +404,7 @@ public void CloseCurrentPanel() } else { - Log.Debug("_currentPanel is null"); + _logger?.LogDebug("_currentPanel is null"); } if (isCurrentForm) @@ -443,11 +443,11 @@ public Form CreatePanel(String panelClass, String title) /// the form for the panel public Form CreatePanel(String panelClass, String panelTitle, StartupArg startupArg) { - Log.Debug("panelClass: " + panelClass); + _logger?.LogDebug("panelClass: " + panelClass); Form form = CreatePanel(ref panelClass, panelTitle, IntPtr.Zero, null); - Log.IsNull("Form for this panel ", form); + _logger?.LogDebug("Form for this panel " + ". " + ((form != null) ? " is not null " : " is null ")); if (form is IPanel) { @@ -455,7 +455,7 @@ public Form CreatePanel(String panelClass, String panelTitle, StartupArg startup (form as IPanel).Initialize(startupArg); } - Log.Debug("Returning form from DynamicallyCreatePanelForm"); + _logger?.LogDebug("Returning form from DynamicallyCreatePanelForm"); return form; } @@ -474,24 +474,24 @@ public Form CreatePanel( IntPtr winHandle, AutomationElement focusedElement) { - Log.Debug($"Searching for panel of type {panelClass}"); + _logger?.LogDebug($"Searching for panel of type {panelClass}"); var panelConfigMapEntry = PanelConfigMap.GetPanelConfigMapEntry(panelClass); if (panelConfigMapEntry == null) { - Log.Warn($"Could not find panel for {panelClass} - Using default."); + _logger?.LogWarning($"Could not find panel for {panelClass} - Using default."); panelClass = PanelClasses.Alphabet; panelConfigMapEntry = PanelConfigMap.GetPanelConfigMapEntry(PanelClasses.Alphabet); if (panelConfigMapEntry == null) { - Log.Error($"Unable to find an appropriate panel class."); + _logger?.LogError($"Unable to find an appropriate panel class."); return null; } } - Log.Debug($"Found panel class {panelConfigMapEntry.PanelClass} with. name {panelConfigMapEntry.FormType.Name}"); + _logger?.LogDebug($"Found panel class {panelConfigMapEntry.PanelClass} with. name {panelConfigMapEntry.FormType.Name}"); var form = DynamicallyCreatePanelForm(panelClass, panelTitle, panelConfigMapEntry.FormType, winHandle, focusedElement); return form; @@ -540,7 +540,7 @@ public void Pause() { if (_currentForm is IPanel) { - Log.Debug("Pausing _currentForm " + _currentForm.Name + ", IsModal: " + _currentForm.Modal); + _logger?.LogDebug("Pausing _currentForm " + _currentForm.Name + ", IsModal: " + _currentForm.Modal); (_currentForm as IPanel).OnPause(); IsPaused = true; } @@ -556,7 +556,7 @@ public void Resume() return; } - Log.Debug("Calling OnResume on " + _currentForm.Name); + _logger?.LogDebug("Calling OnResume on " + _currentForm.Name); (_currentForm as IPanel).OnResume(); @@ -618,7 +618,7 @@ public bool ShowDialog(IPanel parent, IPanel panel) var form = (Form)panel; - Log.Debug("showDialog " + form.Name + ", type: " + form.GetType()); + _logger?.LogDebug("showDialog " + form.Name + ", type: " + form.GetType()); bool retVal; // if parent has not been specified, used the current form @@ -626,18 +626,18 @@ public bool ShowDialog(IPanel parent, IPanel panel) // show. if (parent == null) { - Log.Debug("parent passed is null"); - Log.IsNull("_currentForm ", _currentForm); - Log.IsNull("_currentPanel ", _currentPanel); + _logger?.LogDebug("parent passed is null"); + _logger?.LogDebug("_currentForm " + ". " + ((_currentForm != null) ? " is not null " : " is null ")); + _logger?.LogDebug("_currentPanel " + ". " + ((_currentPanel != null) ? " is not null " : " is null ")); if (_currentForm is IPanel) { - Log.Debug("Showing as dialog child: " + panel.GetType() + ", parent: " + _currentForm.GetType()); + _logger?.LogDebug("Showing as dialog child: " + panel.GetType() + ", parent: " + _currentForm.GetType()); retVal = show((IPanel)_currentForm, panel, DisplayModeTypes.Dialog); } else { - Log.Debug("Just showing " + form.GetType()); + _logger?.LogDebug("Just showing " + form.GetType()); //retVal = Show(panel); retVal = show(null, panel, DisplayModeTypes.Dialog); } @@ -645,7 +645,7 @@ public bool ShowDialog(IPanel parent, IPanel panel) else { var parentForm = parent as Form; - Log.Debug("showDialog parent: " + parentForm.Name + ", type: " + parentForm.GetType()); + _logger?.LogDebug("showDialog parent: " + parentForm.Name + ", type: " + parentForm.GetType()); retVal = show(parent, panel, DisplayModeTypes.Dialog); } @@ -748,7 +748,7 @@ private Form DynamicallyCreatePanelForm( IntPtr winHandle, AutomationElement focusedElement) { - Log.Debug($"*** panelClass: [{panelClass}], panel: [{type.FullName}] title: [{panelTitle ?? "null"}]"); + _logger?.LogDebug($"*** panelClass: [{panelClass}], panel: [{type.FullName}] title: [{panelTitle ?? "null"}]"); var constructorArgSets = new object[][] { @@ -775,11 +775,11 @@ private Form DynamicallyCreatePanelForm( } catch (Exception ex) { - Log.Exception($"Constructor failed with args ({string.Join(", ", args.Select(a => a?.ToString() ?? "null"))}): {ex}"); + _logger?.LogError(ex, $"Constructor failed with args ({string.Join(", ", args.Select(a => a?.ToString() ?? "null"))})"); } } - Log.Debug($"No suitable constructor found for {type.FullName}"); + _logger?.LogDebug($"No suitable constructor found for {type.FullName}"); return null; } @@ -800,7 +800,7 @@ private bool initializePanel(IScannerPanel scannerPanel, PanelRequestEventArgs a var panelConfigMapEntry = PanelConfigMap.GetPanelConfigMapEntry(arg.PanelClass); - Log.Debug("panelClass: " + arg.PanelClass + ", ConfigFile: " + ((panelConfigMapEntry != null) ? panelConfigMapEntry.ConfigFileName : String.Empty)); + _logger?.LogDebug("panelClass: " + arg.PanelClass + ", ConfigFile: " + ((panelConfigMapEntry != null) ? panelConfigMapEntry.ConfigFileName : String.Empty)); return scannerPanel.Initialize(startupArg); } @@ -814,16 +814,16 @@ private void panel_FormClosed(object sender, FormClosedEventArgs e) { var form = (Form)sender; - Log.Debug("Enter (" + form.Name + ")"); + _logger?.LogDebug("Enter (" + form.Name + ")"); IPanel panel = form as IPanel; if (panel.SyncObj.Status == SyncLock.StatusValues.Closed) { - Log.Debug("Form is already closed. Returning " + form.Name); + _logger?.LogDebug("Form is already closed. Returning " + form.Name); return; } - Log.Debug("Setting CLOSED for " + form.Name); + _logger?.LogDebug("Setting CLOSED for " + form.Name); (form as IPanel).SyncObj.Status = SyncLock.StatusValues.Closed; form.FormClosed -= panel_FormClosed; @@ -834,7 +834,7 @@ private void panel_FormClosed(object sender, FormClosedEventArgs e) auditLogScannerEvent(form, "close"); - Log.Debug("number of owned forms: " + array.Length); + _logger?.LogDebug("number of owned forms: " + array.Length); // close all the forms this panel owns while (true) @@ -842,17 +842,17 @@ private void panel_FormClosed(object sender, FormClosedEventArgs e) Form[] ownedForms = form.OwnedForms; if (ownedForms.Length == 0) { - Log.Debug(form.Name + ": No more owned forms. Breaking"); + _logger?.LogDebug(form.Name + ": No more owned forms. Breaking"); break; } - Log.Debug("Removing owned form from list. " + ownedForms[0].Name); + _logger?.LogDebug("Removing owned form from list. " + ownedForms[0].Name); form.RemoveOwnedForm(ownedForms[0]); - Log.Debug("Calling close on " + ownedForms[0].Name); + _logger?.LogDebug("Calling close on " + ownedForms[0].Name); Windows.CloseForm(ownedForms[0]); } - Log.Debug("form Name: " + form.Name + ", type: " + form.GetType()); + _logger?.LogDebug("form Name: " + form.Name + ", type: " + form.GetType()); // Exit the application if instructed to do so. if (Context.AppQuit) @@ -870,23 +870,23 @@ private void panel_FormClosed(object sender, FormClosedEventArgs e) { // Resume the parent if it is prudent to do so. - Log.Debug("parent Form is " + parentForm.Name); + _logger?.LogDebug("parent Form is " + parentForm.Name); IPanel parentPanel = (IPanel)parentForm; if (parentPanel.SyncObj.IsClosing()) { - Log.Debug("*** Parent is closing. Will not call OnResume"); + _logger?.LogDebug("*** Parent is closing. Will not call OnResume"); } else { - Log.Debug("parent form is not closing. Setting _currentPanel to " + parentForm.Name + + _logger?.LogDebug("parent form is not closing. Setting _currentPanel to " + parentForm.Name + ", type: " + parentForm.GetType()); _currentPanel = parentForm; _currentForm = parentForm; - Log.Debug("Calling OnResume on parentForm " + parentForm.Name); + _logger?.LogDebug("Calling OnResume on parentForm " + parentForm.Name); parentPanel.OnResume(); @@ -898,7 +898,7 @@ private void panel_FormClosed(object sender, FormClosedEventArgs e) } else { - Log.Debug("parentform is null"); + _logger?.LogDebug("parentform is null"); _currentPanel = null; _currentForm = null; } @@ -906,23 +906,23 @@ private void panel_FormClosed(object sender, FormClosedEventArgs e) var panelClass = (form is IScannerPanel) ? ((IScannerPanel)form).PanelClass : PanelClasses.None; if (!PanelConfigMap.AreEqual(panelClass, PanelClasses.None)) { - Log.Debug("Calling AppAgentMgr.OnPanelClosed for " + panelClass); + _logger?.LogDebug("Calling AppAgentMgr.OnPanelClosed for " + panelClass); Context.AppAgentMgr.OnPanelClosed(panelClass); } if (EvtScannerClosed != null) { - Log.Debug("Calling evetscannerclosed for " + form.Name); + _logger?.LogDebug("Calling evetscannerclosed for " + form.Name); EvtScannerClosed(this, new ScannerCloseEventArg(form as IPanel)); } else { - Log.Debug("EvtScannerClosed is NULL"); + _logger?.LogDebug("EvtScannerClosed is NULL"); } // (form as IPanel).SyncObj.Status = SyncLock.StatusValues.Closed; // moved this up - Log.Debug("Exit " + form.Name); + _logger?.LogDebug("Exit " + form.Name); } /// @@ -940,7 +940,7 @@ private bool show(IPanel parent, IPanel panel, DisplayModeTypes displayMode) Form panelForm = (Form)panel; Form parentForm = (Form)parent; - Log.Debug("parentForm: " + ((parentForm != null) ? parentForm.Name : " null") + + _logger?.LogDebug("parentForm: " + ((parentForm != null) ? parentForm.Name : " null") + ". panel: " + panelForm.Name); panelForm.FormClosed += panel_FormClosed; @@ -956,7 +956,7 @@ private bool show(IPanel parent, IPanel panel, DisplayModeTypes displayMode) if (displayMode == DisplayModeTypes.Dialog) { - Log.Debug("Showing Dialog" + panelForm.Name + " with parent " + parentForm.Name); + _logger?.LogDebug("Showing Dialog" + panelForm.Name + " with parent " + parentForm.Name); auditLogScannerEvent(panelForm, "show"); Context.AppPanelManager.NotifyPanelPreShow(new PanelPreShowEventArg(panel, displayMode)); @@ -964,9 +964,9 @@ private bool show(IPanel parent, IPanel panel, DisplayModeTypes displayMode) } else { - Log.Debug("Showing " + panelForm.Name); + _logger?.LogDebug("Showing " + panelForm.Name); - Log.Debug("parent is not null. Setting _currentPanel to " + panelForm.Name + + _logger?.LogDebug("parent is not null. Setting _currentPanel to " + panelForm.Name + ", type: " + panelForm.GetType()); _currentPanel = panelForm; auditLogScannerEvent(panelForm, "show"); @@ -978,8 +978,8 @@ private bool show(IPanel parent, IPanel panel, DisplayModeTypes displayMode) } else { - Log.Debug("showing " + panelForm.Name + ", parent is null"); - Log.Debug("parent is null. Setting _currentPanel to " + panelForm.Name + + _logger?.LogDebug("showing " + panelForm.Name + ", parent is null"); + _logger?.LogDebug("parent is null. Setting _currentPanel to " + panelForm.Name + ", type: " + panelForm.GetType()); _currentPanel = panelForm; @@ -1013,38 +1013,38 @@ private bool show(IPanel parent, IPanel panel, DisplayModeTypes displayMode) /// Info about which scanner to display private void switchCurrentPanel(PanelRequestEventArgs eventArg) { - Log.Verbose(); + _logger?.LogTrace(nameof(switchCurrentPanel)); - Log.Debug(eventArg.ToString()); + _logger?.LogDebug(eventArg.ToString()); if (!eventArg.UseCurrentScreenAsParent) { - Log.Debug("UseCurrentScreenAsParent is false. closing current panel " + + _logger?.LogDebug("UseCurrentScreenAsParent is false. closing current panel " + ((_currentPanel != null) ? _currentPanel.Name : "")); CloseCurrentPanel(); } - Log.Debug("Creating panel ..." + eventArg.PanelClass); + _logger?.LogDebug("Creating panel ..." + eventArg.PanelClass); Form form = createPanel(eventArg); - Log.Debug("Calling show for ..." + eventArg.PanelClass); + _logger?.LogDebug("Calling show for ..." + eventArg.PanelClass); if (form == null) { - Log.Debug("DynamicallyCreatePanelForm returned null!!"); + _logger?.LogDebug("DynamicallyCreatePanelForm returned null!!"); } else { initializePanel(form as IScannerPanel, eventArg); - Log.Debug("Calling show for ..." + eventArg.PanelClass); + _logger?.LogDebug("Calling show for ..." + eventArg.PanelClass); if (eventArg.UseCurrentScreenAsParent && _currentForm is IPanel) { - Log.Debug("Showing form " + form.Name + ", parent " + _currentForm.Name); + _logger?.LogDebug("Showing form " + form.Name + ", parent " + _currentForm.Name); Show((IPanel)_currentForm, (IPanel)form); } else { - Log.Debug("Showing form " + form.Name + " without parent."); + _logger?.LogDebug("Showing form " + form.Name + " without parent."); Show(null, (IPanel)form); } } diff --git a/src/Libraries/ACATCore/PanelManagement/UI/MenuPanelBase.cs b/src/Libraries/ACATCore/PanelManagement/UI/MenuPanelBase.cs index e8178107..cccf3bde 100644 --- a/src/Libraries/ACATCore/PanelManagement/UI/MenuPanelBase.cs +++ b/src/Libraries/ACATCore/PanelManagement/UI/MenuPanelBase.cs @@ -12,6 +12,7 @@ using ACAT.Core.Utility; using ACAT.Core.WidgetManagement; using ACAT.Core.WidgetManagement.Interfaces; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; @@ -27,6 +28,8 @@ namespace ACAT.Core.PanelManagement /// public partial class MenuPanelBase : Form, IScannerPanel { + private static readonly ILogger _logger = LoggingConfiguration.CreateLogger(typeof(MenuPanelBase).Name); + /// /// Title of the scanner /// @@ -188,7 +191,7 @@ public bool Initialize(StartupArg arg) if (!scannerCommon.Initialize(startupArg)) { - Log.Error($"Could not initialize form {Name}"); + _logger.LogError("Could not initialize form {FormName}", Name); return false; } diff --git a/src/Libraries/ACATCore/PanelManagement/UI/ToastForm.cs b/src/Libraries/ACATCore/PanelManagement/UI/ToastForm.cs index 610b1082..3a0611a9 100644 --- a/src/Libraries/ACATCore/PanelManagement/UI/ToastForm.cs +++ b/src/Libraries/ACATCore/PanelManagement/UI/ToastForm.cs @@ -6,6 +6,7 @@ //////////////////////////////////////////////////////////////////////////// using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.ComponentModel; using System.Threading; @@ -20,6 +21,8 @@ namespace ACAT.Core.PanelManagement /// public partial class ToastForm : Form { + private static readonly ILogger _logger = LoggingConfiguration.CreateLogger(typeof(ToastForm).Name); + /// /// Thread proc for fading out /// @@ -87,7 +90,7 @@ private void fadeOutProc() } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, ex.Message); } } } diff --git a/src/Libraries/ACATCore/PanelManagement/UI/ToastForm2.cs b/src/Libraries/ACATCore/PanelManagement/UI/ToastForm2.cs index 88d57807..570f0497 100644 --- a/src/Libraries/ACATCore/PanelManagement/UI/ToastForm2.cs +++ b/src/Libraries/ACATCore/PanelManagement/UI/ToastForm2.cs @@ -6,6 +6,7 @@ //////////////////////////////////////////////////////////////////////////// using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.ComponentModel; using System.Threading; @@ -20,6 +21,8 @@ namespace ACAT.Core.PanelManagement /// public partial class ToastForm2 : Form { + private static readonly ILogger _logger = LoggingConfiguration.CreateLogger(typeof(ToastForm2).Name); + /// /// Thread proc for fading out /// @@ -88,7 +91,7 @@ private void fadeOutProc() } catch (Exception ex) { - Log.Exception(ex); + _logger.LogError(ex, ex.Message); } } } diff --git a/src/Libraries/ACATCore/PanelManagement/Utils/AutoPositionScanner.cs b/src/Libraries/ACATCore/PanelManagement/Utils/AutoPositionScanner.cs index 8228f5ab..957c4598 100644 --- a/src/Libraries/ACATCore/PanelManagement/Utils/AutoPositionScanner.cs +++ b/src/Libraries/ACATCore/PanelManagement/Utils/AutoPositionScanner.cs @@ -128,8 +128,6 @@ protected virtual void Dispose(bool disposing) // Check to see if Dispose has already been called. if (!_disposed) { - Log.Verbose(); - if (disposing) { // dispose all managed resources. diff --git a/src/Libraries/ACATCore/PanelManagement/Utils/DockScanner.cs b/src/Libraries/ACATCore/PanelManagement/Utils/DockScanner.cs index 71219cde..34874455 100644 --- a/src/Libraries/ACATCore/PanelManagement/Utils/DockScanner.cs +++ b/src/Libraries/ACATCore/PanelManagement/Utils/DockScanner.cs @@ -1,4 +1,5 @@ using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Windows.Automation; using System.Windows.Forms; @@ -11,6 +12,8 @@ namespace ACAT.Core.PanelManagement.Utils /// public class DockScanner : IDisposable { + private static readonly ILogger _logger = LoggingConfiguration.CreateLogger(typeof(DockScanner).Name); + /// /// If docking to a window, relative position of the dock /// @@ -85,7 +88,7 @@ public void Dock() } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex, ex.Message); _automationElementDockTo = null; } } @@ -124,7 +127,7 @@ protected virtual void Dispose(bool disposing) // Check to see if Dispose has already been called. if (!_disposed) { - Log.Verbose(); + _logger.LogDebug("Disposing DockScanner"); if (disposing) { diff --git a/src/Libraries/ACATCore/PanelManagement/Utils/Fonts.cs b/src/Libraries/ACATCore/PanelManagement/Utils/Fonts.cs index fe36a076..43511bdd 100644 --- a/src/Libraries/ACATCore/PanelManagement/Utils/Fonts.cs +++ b/src/Libraries/ACATCore/PanelManagement/Utils/Fonts.cs @@ -6,6 +6,7 @@ //////////////////////////////////////////////////////////////////////////// using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Drawing; using System.Drawing.Text; @@ -29,6 +30,8 @@ public class Fonts : IDisposable /// private static readonly Fonts _instance = new(); + private static readonly ILogger _logger = LoggingConfiguration.CreateLogger(); + /// /// Collection of installed fonts /// @@ -65,7 +68,7 @@ public static void LoadFontsFromDir(string directory) { if (!Directory.Exists(directory)) { - Log.Info("No user fonts installed."); + _logger.LogInformation("No user fonts installed"); return; } loadFontsFromDir(directory, "*.ttf"); @@ -87,7 +90,7 @@ public bool AddFontFile(string fontFileName) } catch (Exception ex) { - Log.Exception("Could not add font file " + fontFileName + ", exception: " + ex); + _logger.LogError(ex, "Could not add font file {FontFileName}", fontFileName); retVal = false; } return retVal; @@ -133,7 +136,7 @@ public FontFamily GetFontFamily(string[] fontNames) private static void loadFontsFromDir(string directory, string wildCard) { var walker = new DirectoryWalker(directory, wildCard); - Log.Verbose("Walking dir " + directory); + _logger.LogTrace("Walking dir {Directory}", directory); walker.Walk(new OnFileFoundDelegate(onFileFound)); } @@ -143,7 +146,7 @@ private static void loadFontsFromDir(string directory, string wildCard) /// private static void onFileFound(string file) { - Log.Verbose("Found font file " + file); + _logger.LogTrace("Found font file {File}", file); Instance.AddFontFile(file); } diff --git a/src/Libraries/ACATCore/PanelManagement/Utils/OutlineWindow.cs b/src/Libraries/ACATCore/PanelManagement/Utils/OutlineWindow.cs index 6c3f560b..7842e5a9 100644 --- a/src/Libraries/ACATCore/PanelManagement/Utils/OutlineWindow.cs +++ b/src/Libraries/ACATCore/PanelManagement/Utils/OutlineWindow.cs @@ -6,6 +6,7 @@ //////////////////////////////////////////////////////////////////////////// using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Drawing; using System.Windows.Forms; @@ -19,6 +20,8 @@ namespace ACAT.Core.PanelManagement.Utils /// internal class OutlineWindow : IDisposable { + private static ILogger _logger => LogManager.GetLogger(); + /// /// Width of the pen to draw the border /// @@ -71,7 +74,7 @@ public void Dispose() /// width of the pen public void Draw(Rectangle rectangle, int penWidth = 0) { - Log.Debug(rectangle.ToString()); + _logger?.LogDebug("Drawing rectangle: {Rectangle}", rectangle); _form.Invalidate(); _form.Refresh(); @@ -118,7 +121,7 @@ public void Draw(Rectangle rectangle, int penWidth = 0) var width = rectangle.X > 0 ? rectangle.Width : rectangle.Width + (float)rectangle.X; var height = rectangle.Y > 0 ? rectangle.Height : rectangle.Height + (float)rectangle.Y; - Log.Debug("Draw rectangle " + x + " " + y + " " + width + " " + height); + _logger?.LogDebug("Draw rectangle x={X} y={Y} width={Width} height={Height}", x, y, width, height); formGraphics.DrawRectangle(pen, x, y, width, height); } @@ -141,7 +144,7 @@ protected virtual void Dispose(bool disposing) // Check to see if Dispose has already been called. if (!_disposed) { - Log.Verbose(); + _logger?.LogTrace("Disposing OutlineWindow"); if (disposing) { @@ -170,10 +173,10 @@ private void initForm(Form form) form.FormBorderStyle = FormBorderStyle.None; form.WindowState = FormWindowState.Maximized; - Log.Debug("Form width: " + form.Width + "Form height: " + form.Height); + _logger?.LogDebug("Form width: {Width}, Form height: {Height}", form.Width, form.Height); int boundWidth = Screen.PrimaryScreen.Bounds.Width; int boundHeight = Screen.PrimaryScreen.Bounds.Height; - Log.Debug("boundWidth=" + boundWidth + " boundHeight=" + boundHeight); + _logger?.LogDebug("boundWidth={BoundWidth}, boundHeight={BoundHeight}", boundWidth, boundHeight); form.Location = new Point(0, 0); } diff --git a/src/Libraries/ACATCore/PanelManagement/Utils/WindowHighlight.cs b/src/Libraries/ACATCore/PanelManagement/Utils/WindowHighlight.cs index 0ccc4f3b..b3520493 100644 --- a/src/Libraries/ACATCore/PanelManagement/Utils/WindowHighlight.cs +++ b/src/Libraries/ACATCore/PanelManagement/Utils/WindowHighlight.cs @@ -1,4 +1,5 @@ using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Windows.Automation; using System.Windows.Forms; @@ -11,6 +12,8 @@ namespace ACAT.Core.PanelManagement.Utils /// public class WindowHighlight : IDisposable { + private static readonly ILogger _logger = LoggingConfiguration.CreateLogger(); + /// /// Scanner form. /// @@ -58,7 +61,7 @@ public WindowHighlight(IntPtr targetWindow, Form form) } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex, ex.Message); _automationElement = null; } } @@ -84,12 +87,12 @@ protected virtual void Dispose(bool disposing) // Check to see if Dispose has already been called. if (!_disposed) { - Log.Verbose(); + _logger.LogTrace(""); if (disposing) { // dispose all managed resources. - Log.Verbose(); + _logger.LogTrace(""); stopTimer(); @@ -97,13 +100,13 @@ protected virtual void Dispose(bool disposing) { try { - Log.Debug("Disposing highlight overlay window"); + _logger.LogDebug("Disposing highlight overlay window"); _outlineWindow.Dispose(); _outlineWindow = null; } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex, ex.Message); } } @@ -130,7 +133,7 @@ private void _timer_Tick(object sender, EventArgs e) private void highlightWindow(AutomationElement focusedElement) { - Log.Verbose(); + _logger.LogTrace(""); try { lock (_sync) @@ -149,14 +152,14 @@ private void highlightWindow(AutomationElement focusedElement) } catch (Exception exp) { - Log.Exception(exp.ToString()); + _logger.LogError(exp, exp.Message); } })); } } catch (Exception e) { - Log.Exception(e.ToString()); + _logger.LogError(e, e.Message); } } diff --git a/src/Libraries/ACATCore/PreferencesManagement/PreferencesBase.cs b/src/Libraries/ACATCore/PreferencesManagement/PreferencesBase.cs index 75ac0a17..42fc8504 100644 --- a/src/Libraries/ACATCore/PreferencesManagement/PreferencesBase.cs +++ b/src/Libraries/ACATCore/PreferencesManagement/PreferencesBase.cs @@ -16,6 +16,7 @@ using ACAT.Core.PreferencesManagement.Interfaces; using ACAT.Core.Utility; using CommunityToolkit.Mvvm.ComponentModel; +using Microsoft.Extensions.Logging; using System; using System.ComponentModel; using System.Reflection; @@ -34,6 +35,8 @@ namespace ACAT.Core.PreferencesManagement [Serializable] public abstract class PreferencesBase : ObservableValidator, IPreferences, IDisposable { + private static readonly ILogger _logger = LoggingConfiguration.CreateLogger(); + [XmlIgnore] public bool IsDirty { get; private set; } = false; @@ -103,7 +106,7 @@ protected override void OnPropertyChanged(PropertyChangedEventArgs e) if (preferences == null) { - Log.Warn($"Could not load preferences from {preferencesFile} - creating a new one."); + _logger.LogWarning("Could not load preferences from {PreferencesFile} - creating a new one", preferencesFile); if (loadDefaultsOnFail == true) { preferences = new T(); @@ -114,7 +117,7 @@ protected override void OnPropertyChanged(PropertyChangedEventArgs e) { if (!XmlUtils.XmlFileSave(preferences, preferencesFile)) { - Log.Error("Unable to save default preferences!"); + _logger.LogError("Unable to save default preferences"); preferences = default; } } @@ -145,7 +148,7 @@ public static bool Save(T prefs, String preferencesFile) if (retVal == false) { - Log.Error("Error saving preferences! file=" + preferencesFile); + _logger.LogError("Error saving preferences to file {PreferencesFile}", preferencesFile); } return retVal; diff --git a/src/Libraries/ACATCore/SpellCheckManagement/NullSpellChecker.cs b/src/Libraries/ACATCore/SpellCheckManagement/NullSpellChecker.cs index 69b4ce56..6bbb70f7 100644 --- a/src/Libraries/ACATCore/SpellCheckManagement/NullSpellChecker.cs +++ b/src/Libraries/ACATCore/SpellCheckManagement/NullSpellChecker.cs @@ -131,8 +131,6 @@ protected virtual void Dispose(bool disposing) // Check to see if Dispose has already been called. if (!_disposed) { - Log.Verbose(); - if (disposing) { // dispose all managed resources. diff --git a/src/Libraries/ACATCore/SpellCheckManagement/SpellCheckManager.cs b/src/Libraries/ACATCore/SpellCheckManagement/SpellCheckManager.cs index fd9cb53b..d1438c3a 100644 --- a/src/Libraries/ACATCore/SpellCheckManagement/SpellCheckManager.cs +++ b/src/Libraries/ACATCore/SpellCheckManagement/SpellCheckManager.cs @@ -34,9 +34,15 @@ public class SpellCheckManager : IDisposable public static String SpellCheckersRootName = ""; /// - /// Word prediction manager instance + /// Word prediction manager instance - lazy initialized to get logger from DI container /// - private static readonly SpellCheckManager _instance = new(); + private static readonly Lazy _instance = new Lazy(() => + { + // Get logger from DI container if available, otherwise use LogManager + ILogger logger = Context.ServiceProvider?.GetService(typeof(ILogger)) as ILogger + ?? LogManager.GetLogger(); + return new SpellCheckManager(logger); + }); /// /// Logger instance @@ -61,9 +67,9 @@ public class SpellCheckManager : IDisposable /// /// Initializes a new instance of the class. /// - private SpellCheckManager(ILogger logger = null) + private SpellCheckManager(ILogger logger) { - _logger = logger; + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); AppDomain currentDomain = AppDomain.CurrentDomain; currentDomain.AssemblyResolve += currentDomain_AssemblyResolve; @@ -77,7 +83,7 @@ private SpellCheckManager(ILogger logger = null) /// public static SpellCheckManager Instance { - get { return _instance; } + get { return _instance.Value; } } /// @@ -319,7 +325,7 @@ protected virtual void Dispose(bool disposing) // Check to see if Dispose has already been called. if (!_disposed) { - Log.Verbose(); + _logger.LogTrace("Disposing SpellCheckManager"); if (disposing) { @@ -370,7 +376,7 @@ private bool createAndSetActiveSpellChecker(Type type, CultureInfo ci) } catch (Exception ex) { - Log.Exception("Unable to load spellchecker " + type + ", assembly: " + type.Assembly.FullName + ". Exception: " + ex); + _logger.LogError(ex, "Unable to load spellchecker {Type}, assembly: {AssemblyName}", type, type.Assembly.FullName); retVal = false; } diff --git a/src/Libraries/ACATCore/SpellCheckManagement/SpellCheckers.cs b/src/Libraries/ACATCore/SpellCheckManagement/SpellCheckers.cs index c87d4bb3..2c7614a8 100644 --- a/src/Libraries/ACATCore/SpellCheckManagement/SpellCheckers.cs +++ b/src/Libraries/ACATCore/SpellCheckManagement/SpellCheckers.cs @@ -167,7 +167,8 @@ public Guid GetDefaultByCulture(CultureInfo ci) ClassDescriptorAttribute descriptor = ClassDescriptorAttribute.GetDescriptor(foundTuple.Item2); if (descriptor != null) { - Log.Debug("Found spellchecker for culture " + (ci != null ? ci.TwoLetterISOLanguageName : "Neutral") + "[" + descriptor.Name + "]"); + _logger?.LogDebug("Found spellchecker for culture {Culture} [{Name}]", + (ci != null ? ci.TwoLetterISOLanguageName : "Neutral"), descriptor.Name); return descriptor.Id; } } @@ -260,12 +261,12 @@ public Type Lookup(Guid guid) ClassDescriptorAttribute descriptor = ClassDescriptorAttribute.GetDescriptor(type); if (descriptor != null && Equals(guid, descriptor.Id)) { - Log.Debug($"Found spellchecker of type {type}"); + _logger?.LogDebug("Found spellchecker of type {Type}", type); return type; } } - Log.Error($"Could not find spellchecker for id {guid}"); + _logger?.LogError("Could not find spellchecker for id {Guid}", guid); return null; } @@ -322,7 +323,7 @@ protected virtual void Dispose(bool disposing) // Check to see if Dispose has already been called. if (!_disposed) { - Log.Verbose(); + _logger?.LogTrace("Disposing SpellCheckers"); if (disposing) { @@ -399,7 +400,7 @@ private void onFileFound(String dllName) } catch (Exception ex) { - Log.Exception("Could get types from assembly " + dllName + ". Exception : " + ex); + _logger?.LogError(ex, "Could not get types from assembly {DllName}", dllName); } } } diff --git a/src/Libraries/ACATCore/TTSManagement/NullTTSEngine.cs b/src/Libraries/ACATCore/TTSManagement/NullTTSEngine.cs index ae43b7b3..cb0cf95d 100644 --- a/src/Libraries/ACATCore/TTSManagement/NullTTSEngine.cs +++ b/src/Libraries/ACATCore/TTSManagement/NullTTSEngine.cs @@ -355,8 +355,6 @@ protected virtual void Dispose(bool disposing) // Check to see if Dispose has already been called. if (!_disposed) { - Log.Verbose(); - if (disposing) { // dispose all managed resources. diff --git a/src/Libraries/ACATCore/TTSManagement/Pronunciation.cs b/src/Libraries/ACATCore/TTSManagement/Pronunciation.cs index 25f27729..048062be 100644 --- a/src/Libraries/ACATCore/TTSManagement/Pronunciation.cs +++ b/src/Libraries/ACATCore/TTSManagement/Pronunciation.cs @@ -6,6 +6,7 @@ //////////////////////////////////////////////////////////////////////////// using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; namespace ACAT.Core.TTSManagement @@ -21,6 +22,8 @@ namespace ACAT.Core.TTSManagement /// public class Pronunciation : IDisposable { + private readonly ILogger _logger; + /// /// Has this object been disposed /// @@ -31,9 +34,10 @@ public class Pronunciation : IDisposable /// /// original word /// phonetic spelling - public Pronunciation(String word, String altPronunciation) + public Pronunciation(String word, String altPronunciation, ILogger logger = null) { - Log.Debug("Entering...word=" + word + " altPronunciation=" + altPronunciation); + _logger = logger; + _logger?.LogDebug("Creating pronunciation: word={Word}, altPronunciation={AltPronunciation}", word, altPronunciation); Word = word; AltPronunciation = altPronunciation; } diff --git a/src/Libraries/ACATCore/TTSManagement/Pronunciations.cs b/src/Libraries/ACATCore/TTSManagement/Pronunciations.cs index 2a244e3d..f005bc2d 100644 --- a/src/Libraries/ACATCore/TTSManagement/Pronunciations.cs +++ b/src/Libraries/ACATCore/TTSManagement/Pronunciations.cs @@ -7,6 +7,7 @@ using ACAT.Core.UserManagement; using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Globalization; @@ -29,6 +30,9 @@ namespace ACAT.Core.TTSManagement /// public class Pronunciations : IDisposable { + private static readonly ILogger _staticLogger = LoggingConfiguration.CreateLogger(); + private readonly ILogger _logger; + /// /// xml attribute to get the alternate pronunciation /// @@ -49,6 +53,11 @@ public class Pronunciations : IDisposable /// private bool _disposed; + public Pronunciations(ILogger logger = null) + { + _logger = logger; + } + /// /// Holds a mapping between words and their pronunciations /// @@ -130,7 +139,7 @@ public bool Load(String filePath) { _pronunciationList.Clear(); - Log.Debug("Found pronuncation file " + filePath); + _logger?.LogDebug("Found pronuncation file {FilePath}", filePath); doc.Load(filePath); @@ -144,7 +153,7 @@ public bool Load(String filePath) } catch (Exception ex) { - Log.Exception("Error processing pronunciation file " + filePath + ". Exception: " + ex); + _logger?.LogError(ex, "Error processing pronunciation file {FilePath}", filePath); retVal = false; } @@ -160,7 +169,7 @@ public bool Load(String filePath) /// true on success public bool Load(CultureInfo ci, String pronunciationsFileName) { - Log.Debug("Entering..."); + _logger?.LogDebug("Loading pronunciations for culture {Culture}, file {FileName}", ci.Name, pronunciationsFileName); String filePath = getPronunciationsFilePath(ci, pronunciationsFileName); @@ -217,7 +226,7 @@ public String ReplaceWithAlternatePronunciations(String inputString) var strWord = new StringBuilder(); Pronunciation pronunciation; - Log.Debug("inputString: " + inputString); + _logger?.LogDebug("Processing input string: {InputString}", inputString); foreach (char ch in inputString) { @@ -242,7 +251,7 @@ public String ReplaceWithAlternatePronunciations(String inputString) var retVal = strOutput.ToString(); - Log.Debug("replacedString: " + retVal); + _logger?.LogDebug("Replaced string: {ReplacedString}", retVal); return retVal; } @@ -273,7 +282,7 @@ public bool Save(String pronunciationsFile) } catch (IOException ex) { - Log.Exception(ex); + _logger?.LogError(ex, "IO exception while saving pronunciations"); retVal = false; } @@ -301,7 +310,7 @@ protected virtual void Dispose(bool disposing) // Check to see if Dispose has already been called. if (!_disposed) { - Log.Verbose(); + _logger?.LogTrace("Disposing Pronunciations"); if (disposing) { @@ -333,7 +342,7 @@ private static void closePronunciationFile(XmlWriter xmlTextWriter) } catch (Exception ex) { - Log.Exception(ex.ToString()); + _staticLogger?.LogError(ex, "Exception closing pronunciation file"); } } @@ -356,7 +365,7 @@ private static XmlTextWriter createPronunciationsFile(String fileName) } catch (Exception ex) { - Log.Exception(ex.ToString()); + _staticLogger?.LogError(ex, "Exception creating pronunciations file"); xmlTextWriter = null; } @@ -372,7 +381,7 @@ private void createAndAddPronunciation(XmlNode node) { var word = XmlUtils.GetXMLAttrString(node, WordAttr).Trim().ToLower(); var pronunciation = XmlUtils.GetXMLAttrString(node, PronunciationAttr); - Log.Debug("word=" + word + " pronunciation=" + pronunciation); + _logger?.LogDebug("Adding pronunciation - word: {Word}, pronunciation: {Pronunciation}", word, pronunciation); Add(new Pronunciation(word, pronunciation)); } diff --git a/src/Libraries/ACATCore/TTSManagement/TTSEngines.cs b/src/Libraries/ACATCore/TTSManagement/TTSEngines.cs index 4fa413b1..1fac076e 100644 --- a/src/Libraries/ACATCore/TTSManagement/TTSEngines.cs +++ b/src/Libraries/ACATCore/TTSManagement/TTSEngines.cs @@ -132,12 +132,12 @@ public Type this[Guid guid] ClassDescriptorAttribute descriptor = ClassDescriptorAttribute.GetDescriptor(type); if (descriptor != null && Guid.Equals(guid, descriptor.Id)) { - Log.Debug($"Found TTS engine of type {type}"); + _logger?.LogDebug("Found TTS engine of type {Type}", type); return type; } } - Log.Error($"Could not find TTS engine for id {guid}"); + _logger?.LogError("Could not find TTS engine for id {Guid}", guid); return null; } } @@ -205,7 +205,8 @@ public Guid GetDefaultByCulture(CultureInfo ci) ClassDescriptorAttribute descriptor = ClassDescriptorAttribute.GetDescriptor(foundTuple.Item2); if (descriptor != null) { - Log.Debug("Found TTS Engine for culture " + (ci != null ? ci.TwoLetterISOLanguageName : "Neutral") + "[" + descriptor.Name + "]"); + _logger?.LogDebug("Found TTS Engine for culture {Culture} [{Name}]", + ci != null ? ci.TwoLetterISOLanguageName : "Neutral", descriptor.Name); return descriptor.Id; } } @@ -299,12 +300,12 @@ public Type Lookup(Guid guid) ClassDescriptorAttribute descriptor = ClassDescriptorAttribute.GetDescriptor(type); if (descriptor != null && Equals(guid, descriptor.Id)) { - Log.Debug($"Found TTS Engine of type {type}"); + _logger?.LogDebug("Found TTS Engine of type {Type}", type); return type; } } - Log.Error($"Could not find TTS Engine for id {guid}"); + _logger?.LogError("Could not find TTS Engine for id {Guid}", guid); return null; } @@ -352,7 +353,7 @@ protected virtual void Dispose(bool disposing) // Check to see if Dispose has already been called. if (!_disposed) { - Log.Verbose(); + _logger?.LogTrace("Disposing TTSEngines"); if (disposing) { @@ -400,7 +401,7 @@ private void onFileFound(String dllName) } catch (Exception ex) { - Log.Exception("Could not load assembly " + dllName + ". Exception: " + ex.ToString()); + _logger?.LogError(ex, "Could not load assembly {DllName}", dllName); _DLLError = true; return; // skip further processing if there was a DLL error } diff --git a/src/Libraries/ACATCore/TTSManagement/TTSManager.cs b/src/Libraries/ACATCore/TTSManagement/TTSManager.cs index 9d0dd08d..9b677475 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.DependencyInjection; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; @@ -52,9 +53,15 @@ public class TTSManager : IDisposable private const int _minNormalizedVolume = 0; /// - /// Singleton instance of the manager + /// Singleton instance of the manager - lazy initialized to get logger from DI container /// - private static readonly TTSManager _instance = new(); + private static readonly Lazy _instance = new Lazy(() => + { + // Get logger from DI container if available, otherwise use LogManager + ILogger logger = Context.ServiceProvider?.GetService(typeof(ILogger)) as ILogger + ?? LogManager.GetLogger(); + return new TTSManager(logger); + }); /// /// Logger instance @@ -74,9 +81,9 @@ public class TTSManager : IDisposable /// /// Initializes the singleton instance of the class /// - private TTSManager(ILogger logger = null) + private TTSManager(ILogger logger) { - _logger = logger; + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); ActiveEngine = TTSEngines.NullTTSEngine; Context.EvtCultureChanged += Context_EvtCultureChanged; } @@ -98,7 +105,7 @@ private TTSManager(ILogger logger = null) /// public static TTSManager Instance { - get { return _instance; } + get { return _instance.Value; } } /// @@ -386,7 +393,7 @@ protected virtual void Dispose(bool disposing) // Check to see if Dispose has already been called. if (!_disposed) { - Log.Verbose(); + _logger?.LogTrace("Disposing TTSManager"); if (disposing) { @@ -425,7 +432,15 @@ private bool createAndSetActiveEngine(Type type, CultureInfo ci) try { - var ttsEngine = (ITTSEngine)Activator.CreateInstance(type); + // Use ExtensionInstantiator to create instance with proper dependency injection + var ttsEngine = ExtensionInstantiator.CreateExtensionInstance(Context.ServiceProvider, type, _logger) as ITTSEngine; + + if (ttsEngine == null) + { + _logger.LogError("Failed to create TTS Engine instance for type {Type}", type); + return false; + } + retVal = ttsEngine.Init(ci); if (retVal) { @@ -435,7 +450,7 @@ private bool createAndSetActiveEngine(Type type, CultureInfo ci) } catch (Exception ex) { - Log.Exception("Unable to load TTS Engine" + type + ", assembly: " + type.Assembly.FullName + ". Exception: " + ex); + _logger.LogError(ex, "Unable to load TTS Engine {Type}, assembly: {AssemblyName}", type, type.Assembly.FullName); retVal = false; } diff --git a/src/Libraries/ACATCore/ThemeManagement/ColorScheme.cs b/src/Libraries/ACATCore/ThemeManagement/ColorScheme.cs index 303b6578..dc74338a 100644 --- a/src/Libraries/ACATCore/ThemeManagement/ColorScheme.cs +++ b/src/Libraries/ACATCore/ThemeManagement/ColorScheme.cs @@ -6,6 +6,7 @@ //////////////////////////////////////////////////////////////////////////// using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Drawing; using System.IO; @@ -20,6 +21,7 @@ namespace ACAT.Core.ThemeManagement /// public class ColorScheme : IDisposable { + private static readonly ILogger _logger = LoggingConfiguration.CreateLogger(); /// /// Default bg color to use if not defined in the config file /// @@ -523,7 +525,7 @@ protected virtual void Dispose(bool disposing) // Check to see if Dispose has already been called. if (!_disposed) { - Log.Verbose(); + _logger.LogTrace("Disposing ColorScheme"); if (disposing) { @@ -564,16 +566,16 @@ private static Image loadImage(String bitmapFile) return null; } - Log.Debug("imagePath: " + bitmapFile); + _logger.LogDebug("imagePath: {BitmapFile}", bitmapFile); if (File.Exists(bitmapFile)) { - Log.Debug("File exists. Loading image"); + _logger.LogDebug("File exists. Loading image"); retVal = Image.FromFile(bitmapFile); } else { - Log.Error($"Could not find bitmap file {bitmapFile}"); + _logger.LogError("Could not find bitmap file {BitmapFile}", bitmapFile); } return retVal; diff --git a/src/Libraries/ACATCore/ThemeManagement/Theme.cs b/src/Libraries/ACATCore/ThemeManagement/Theme.cs index 8e65ac89..1620ffcd 100644 --- a/src/Libraries/ACATCore/ThemeManagement/Theme.cs +++ b/src/Libraries/ACATCore/ThemeManagement/Theme.cs @@ -6,6 +6,7 @@ //////////////////////////////////////////////////////////////////////////// using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.IO; using System.Xml; @@ -25,6 +26,8 @@ public class Theme : IDisposable /// public const String PreviewScannerImageName = "Preview.png"; + private readonly ILogger _logger; + /// /// Has this object been disposed? /// @@ -34,8 +37,9 @@ public class Theme : IDisposable /// Initializes a new instance of the class. /// /// Name of the color scheme - private Theme(String name) + private Theme(String name, ILogger logger = null) { + _logger = logger; Name = name; Colors = new ColorSchemes(); } @@ -69,7 +73,7 @@ public static Theme Create(String name) /// directory where theme assets are located /// name of the theme config file /// - public static Theme Create(String themeName, String themeDir, String themeFile) + public static Theme Create(String themeName, String themeDir, String themeFile, ILogger logger = null) { Theme theme = null; @@ -88,12 +92,12 @@ public static Theme Create(String themeName, String themeDir, String themeFile) var colorSchemesNode = doc.SelectSingleNode("/ACAT/Theme/ColorSchemes"); if (colorSchemesNode != null) { - theme = new Theme(themeName) { Colors = ColorSchemes.Create(colorSchemesNode, themeDir) }; + theme = new Theme(themeName, logger) { Colors = ColorSchemes.Create(colorSchemesNode, themeDir) }; } } catch (Exception ex) { - Log.Exception(ex.ToString()); + logger?.LogError(ex, "Failed to create theme from file: {ThemeFile}", themeFile); } return theme; @@ -120,7 +124,7 @@ protected virtual void Dispose(bool disposing) // Check to see if Dispose has already been called. if (!_disposed) { - Log.Verbose(); + _logger?.LogTrace("Disposing Theme"); if (disposing) { diff --git a/src/Libraries/ACATCore/ThemeManagement/ThemeManager.cs b/src/Libraries/ACATCore/ThemeManagement/ThemeManager.cs index ecafe98d..f1a4ecd0 100644 --- a/src/Libraries/ACATCore/ThemeManagement/ThemeManager.cs +++ b/src/Libraries/ACATCore/ThemeManagement/ThemeManager.cs @@ -6,10 +6,12 @@ // //////////////////////////////////////////////////////////////////////////// +using ACAT.Core.PanelManagement; using ACAT.Core.Utility; using System; using System.Collections.Generic; using System.IO; +using Microsoft.Extensions.Logging; namespace ACAT.Core.ThemeManagement { @@ -25,6 +27,8 @@ namespace ACAT.Core.ThemeManagement /// public class ThemeManager : IDisposable { + private readonly ILogger _logger; + /// /// Name of the default theme /// @@ -41,9 +45,15 @@ public class ThemeManager : IDisposable private const String ThemeConfigFileName = "Theme.xml"; /// - /// Returns the singleton instance + /// Returns the singleton instance - lazy initialized to get logger from DI container /// - private static readonly ThemeManager _instance = new(); + private static readonly Lazy _instance = new Lazy(() => + { + // Get logger from DI container if available, otherwise use LogManager + ILogger logger = Context.ServiceProvider?.GetService(typeof(ILogger)) as ILogger + ?? LogManager.GetLogger(); + return new ThemeManager(logger); + }); /// /// The current active ksin @@ -58,8 +68,9 @@ public class ThemeManager : IDisposable /// /// Initializes the singleton instance of the manager /// - private ThemeManager() + private ThemeManager(ILogger logger) { + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); ActiveThemeName = DefaultThemeName; DefaultTheme = Theme.Create(ActiveThemeName); _activeTheme = Theme.Create(ActiveThemeName); @@ -75,7 +86,7 @@ private ThemeManager() /// public static ThemeManager Instance { - get { return _instance; } + get { return _instance.Value; } } /// @@ -85,7 +96,7 @@ public Theme ActiveTheme { get { - Log.Debug("Active Theme name is " + _activeTheme.Name); + _logger?.LogDebug("Active Theme name is {ThemeName}", _activeTheme.Name); return _activeTheme; } } @@ -168,12 +179,12 @@ public bool Init() public bool SetActiveTheme(String name) { bool retVal = true; - Log.Debug("Set active Theme to " + name); + _logger?.LogDebug("Set active Theme to {ThemeName}", name); var themeDir = GetThemeDir(name); if (String.IsNullOrEmpty(themeDir)) { - Log.Error($"Could not find Theme {name}, using default."); + _logger?.LogError("Could not find Theme {ThemeName}, using default", name); themeDir = GetThemeDir(DefaultThemeName); if (String.IsNullOrEmpty(themeDir)) { @@ -185,7 +196,7 @@ public bool SetActiveTheme(String name) var themeFile = Path.Combine(themeDir, ThemeConfigFileName); - Log.Debug($"Creating Theme {name}, themeDir: {themeDir}"); + _logger?.LogDebug("Creating Theme {ThemeName}, themeDir: {ThemeDir}", name, themeDir); // create the Theme object. This parses the Theme xml file and // creates the Theme object @@ -196,11 +207,11 @@ public bool SetActiveTheme(String name) _activeTheme = theme; ActiveThemeName = name; - Log.Debug("$Created Theme successfully. active Theme is {_activeTheme.Name}."); + _logger.LogDebug("Created Theme successfully. active Theme is {ThemeName}", _activeTheme.Name); } else { - Log.Error($"Error creating theme with name {theme}"); + _logger.LogError("Error creating theme with name {ThemeName}", name); retVal = false; } @@ -216,7 +227,7 @@ protected virtual void Dispose(bool disposing) // Check to see if Dispose has already been called. if (!_disposed) { - Log.Verbose(); + _logger.LogTrace("Disposing ThemeManager"); if (disposing) { @@ -243,7 +254,7 @@ private void onFileFound(String filePath) var file = new FileInfo(filePath); if (!ThemesLookupTable.ContainsKey(file.Directory.Name)) { - Log.Debug("Adding Theme: " + file.Directory.Name + ", themeDir: " + file.Directory.FullName); + _logger?.LogDebug("Adding Theme: {ThemeName}, themeDir: {ThemeDir}", file.Directory.Name, file.Directory.FullName); ThemesLookupTable.Add(file.Directory.Name, file.Directory.FullName); } } diff --git a/src/Libraries/ACATCore/UserControlManagement/UserControlCommon.cs b/src/Libraries/ACATCore/UserControlManagement/UserControlCommon.cs index 7282fe45..4ed622bf 100644 --- a/src/Libraries/ACATCore/UserControlManagement/UserControlCommon.cs +++ b/src/Libraries/ACATCore/UserControlManagement/UserControlCommon.cs @@ -27,9 +27,9 @@ public class UserControlCommon : IUserControlCommon, IDisposable { private readonly ILogger _logger; - public UserControlCommon(IUserControl userControl, UserControlConfigMapEntry mapEntry, IScannerPanel iScannerPanel, ILogger logger) + public UserControlCommon(IUserControl userControl, UserControlConfigMapEntry mapEntry, IScannerPanel iScannerPanel, ILogger logger = null) { - _logger = logger; + _logger = logger ?? LoggingConfiguration.CreateLogger(); ScannerForm = iScannerPanel.Form; this.mapEntry = mapEntry; ScannerPanel = iScannerPanel; @@ -286,7 +286,7 @@ private bool initAnimationManager(UserControlConfigMapEntry panelConfigMapEntry) private bool initWidgetManager(UserControlConfigMapEntry mapEntry) { - WidgetManager = new WidgetManager(UserControl as Control); + WidgetManager = new WidgetManager(UserControl as Control, LoggingConfiguration.CreateLogger()); WidgetManager.Layout.SetColorScheme(ColorSchemes.ScannerSchemeName); WidgetManager.Layout.SetDisabledButtonColorScheme(ColorSchemes.DisabledScannerButtonSchemeName); diff --git a/src/Libraries/ACATCore/UserControlManagement/UserControlConfigMap.cs b/src/Libraries/ACATCore/UserControlManagement/UserControlConfigMap.cs index 2cd13dc9..8d84aa70 100644 --- a/src/Libraries/ACATCore/UserControlManagement/UserControlConfigMap.cs +++ b/src/Libraries/ACATCore/UserControlManagement/UserControlConfigMap.cs @@ -10,6 +10,7 @@ using ACAT.Core.UserControlManagement.Interfaces; using ACAT.Core.Utility; using ACAT.Core.Utility.TypeLoader; +using Microsoft.Extensions.Logging; using System; using System.Collections; using System.Collections.Generic; @@ -28,6 +29,8 @@ namespace ACAT.Core.UserControlManagement /// public class UserControlConfigMap { + private static readonly ILogger _logger = LoggingConfiguration.CreateLogger(); + private const String DefaultKey = "panelconfigs"; /// @@ -70,11 +73,11 @@ public static void AddUserControlToCache(Guid guid, Type type) { if (_userControlsCache.ContainsKey(guid)) { - Log.Debug("Form Type " + type.FullName + ", guid " + guid + " is already added"); + _logger?.LogDebug("Form Type {TypeName} with guid {Guid} is already added", type.FullName, guid); return; } - Log.Debug("Adding form " + type.FullName + ", guid " + guid + " to cache"); + _logger?.LogDebug("Adding form {TypeName} with guid {Guid} to cache", type.FullName, guid); _userControlsCache.Add(guid, type); updateUserControlTypeReferences(guid, type); @@ -217,14 +220,17 @@ public static bool Load(IEnumerable extensionDirs) var usercontrolConfigMapFile = Path.Combine(FileUtils.GetPanelConfigDir(), UserControlConfigMapFileName); LoadUserControlConfigMap(usercontrolConfigMapFile); + var configsDir = FileUtils.GetPanelConfigDir(); + _logger?.LogDebug("Loading resources from {ConfigsDir}", configsDir); + // load the panels from the default culture (which is English) var resourcesDir = Path.Combine(FileUtils.GetPanelConfigDir(), "common"); - Log.Debug("DefaultResourcesDir: " + resourcesDir); + _logger?.LogDebug("Default resources directory: {ResourcesDir}", resourcesDir); load(resourcesDir, "*.xml"); // Also pick up any overrides for the current culture resourcesDir = Path.Combine(FileUtils.GetPanelConfigDir(), CultureInfo.CurrentUICulture.TwoLetterISOLanguageName); - Log.Debug("DefaultResourcesDir: " + resourcesDir); + _logger?.LogDebug("Culture-specific resources directory: {ResourcesDir}", resourcesDir); load(resourcesDir, "*.xml"); _ConfigIdMapTable.Add(DefaultKey, _loadUserControlConfigMapTable); @@ -266,29 +272,29 @@ public static void Reset() /// internal static void CleanupOrphans() { - Log.Debug("Cleaning up userControlConfigMap entries..."); + _logger?.LogDebug("Cleaning up userControlConfigMap entries"); var removeList = new List(); foreach (var mapEntry in _masterUserControlConfigMapTable.Values) { - Log.Debug("Looking up " + mapEntry.ToString()); + _logger?.LogDebug("Looking up entry: {Entry}", mapEntry.ToString()); if (_userControlsCache.ContainsKey(mapEntry.UserControlId)) { mapEntry.UserControlType = (Type)_userControlsCache[mapEntry.UserControlId]; } - Log.IsNull("mapEntry.UsercontrolType", mapEntry.UserControlType); + _logger?.LogTrace("UserControlType is null: {IsNull}", mapEntry.UserControlType == null); var configFilePath = getConfigFilePathFromLocationMap(mapEntry.ConfigFileName); if (mapEntry.UserControlType != null && !String.IsNullOrEmpty(configFilePath)) { - Log.Debug("Yes. _configFileLocationMap has configfile " + mapEntry.ConfigFileName); + _logger?.LogDebug("Found config file {ConfigFileName} in location map", mapEntry.ConfigFileName); mapEntry.ConfigFileName = configFilePath; } else { - Log.Debug("No. _configFileLocationMap does not have configfile " + mapEntry.ConfigFileName); + _logger?.LogDebug("Config file {ConfigFileName} not found in location map - marking for removal", mapEntry.ConfigFileName); removeList.Add(mapEntry); } } @@ -430,7 +436,7 @@ private static void load(String dir, string wildcard) if (Directory.Exists(dir) && !_DLLError) { var walker = new DirectoryWalker(dir, wildcard); - Log.Debug("Walking dir " + dir); + _logger?.LogDebug("Walking directory {Directory}", dir); walker.Walk(new OnFileFoundDelegate(onFileFound)); } } @@ -447,26 +453,26 @@ private static void onDllFound(String dllName) try { - Log.Debug("Found dll " + dllName); + _logger?.LogDebug("Found dll {DllName}", dllName); typeLoader.LoadFromAssembly(dllName, false); foreach (var type in typeLoader.LoadedTypes.Values) { - Log.Debug("Found type " + type.FullName); + _logger?.LogDebug("Found type {TypeName}", type.FullName); addUserControlTypeToCache(type); } } catch (BadImageFormatException ex) { - Log.Exception($"Error loading dll {dllName} Exception: {ex.Message}"); + _logger?.LogError(ex, "Error loading dll {DllName}", dllName); //_DLLError = true; } catch (Exception ex) { - Log.Exception($"Error loading dll{dllName} Exception: {ex.Message}"); + _logger?.LogError(ex, "Error loading dll {DllName}", dllName); _DLLError = true; } } @@ -523,7 +529,7 @@ private static void LoadUserControlConfigMap(String configFileName) } catch (Exception ex) { - Log.Exception(ex); + _logger?.LogError(ex, "Error loading user control config map"); } } @@ -538,12 +544,12 @@ private static void onXmlFileFound(String xmlFileName) if (_loadConfigFileLocationMap.ContainsKey(fileName)) { - Log.Debug("Updating xmlfile " + fileName + ", fullPath: " + xmlFileName); + _logger?.LogDebug("Updating xml file {FileName}, full path: {FullPath}", fileName, xmlFileName); _loadConfigFileLocationMap[fileName] = xmlFileName; } else { - Log.Debug("Adding xmlfile " + fileName + ", fullPath: " + xmlFileName); + _logger?.LogDebug("Adding xml file {FileName}, full path: {FullPath}", fileName, xmlFileName); _loadConfigFileLocationMap.Add(fileName, xmlFileName); } } diff --git a/src/Libraries/ACATCore/UserControlManagement/UserControlKeyboardCommon.cs b/src/Libraries/ACATCore/UserControlManagement/UserControlKeyboardCommon.cs index 935fac3c..d057c22d 100644 --- a/src/Libraries/ACATCore/UserControlManagement/UserControlKeyboardCommon.cs +++ b/src/Libraries/ACATCore/UserControlManagement/UserControlKeyboardCommon.cs @@ -12,6 +12,7 @@ using ACAT.Core.WidgetManagement.Interfaces; using ACAT.Core.WidgetManagement.Layout; using ACAT.Core.Widgets; +using Microsoft.Extensions.Logging; using System; using System.Windows.Forms; @@ -19,9 +20,12 @@ namespace ACAT.Core.UserControlManagement { public class UserControlKeyboardCommon : UserControlCommon { - public UserControlKeyboardCommon(IUserControl userControl, UserControlConfigMapEntry mapEntry, TextController textController, IScannerPanel iScannerPanel) : - base(userControl, mapEntry, iScannerPanel) + private readonly ILogger _logger; + + public UserControlKeyboardCommon(IUserControl userControl, UserControlConfigMapEntry mapEntry, TextController textController, IScannerPanel iScannerPanel, ILogger logger = null) : + base(userControl, mapEntry, iScannerPanel, logger ?? LoggingConfiguration.CreateLogger()) { + _logger = logger; TextController = textController; } @@ -68,7 +72,7 @@ widget is WordListItemWidget || SendKeys.SendWait(widget.Value + " "); Context.AppAgentMgr.TextChangedNotifications.Release(); CoreGlobals.Stopwatch1.Stop(); - Log.Debug("TimeElapsed 1: " + CoreGlobals.Stopwatch1.ElapsedMilliseconds); + _logger?.LogDebug("TimeElapsed 1: {ElapsedMs}", CoreGlobals.Stopwatch1.ElapsedMilliseconds); } else { @@ -78,7 +82,7 @@ widget is WordListItemWidget || actuateKey(button.GetWidgetAttribute(), widget.Value[0]); CoreGlobals.Stopwatch1.Stop(); - Log.Debug("TimeElapsed 2 : " + CoreGlobals.Stopwatch1.ElapsedMilliseconds); + _logger?.LogDebug("TimeElapsed 2 : {ElapsedMs}", CoreGlobals.Stopwatch1.ElapsedMilliseconds); } } @@ -87,7 +91,7 @@ widget is WordListItemWidget || private void actuateKey(WidgetAttribute widgetAttribute, char value) { - Log.Debug(value.ToString()); + _logger?.LogDebug("{Value}", value); if (!TextController.HandlePunctuation(widgetAttribute.Modifiers, value)) { if ((KeyStateTracker.IsShiftOn() || KeyStateTracker.IsCapsLockOn()) && @@ -104,7 +108,7 @@ private void actuateKey(WidgetAttribute widgetAttribute, char value) private void actuateVirtualKey(WidgetAttribute widgetAttribute, String value) { - Log.Debug("VirtualKey: " + value); + _logger?.LogDebug("VirtualKey: {Value}", value); TextController.HandleVirtualKey(widgetAttribute.Modifiers, value); } diff --git a/src/Libraries/ACATCore/UserControlManagement/UserControlManager.cs b/src/Libraries/ACATCore/UserControlManagement/UserControlManager.cs index ca81eb52..352909e4 100644 --- a/src/Libraries/ACATCore/UserControlManagement/UserControlManager.cs +++ b/src/Libraries/ACATCore/UserControlManagement/UserControlManager.cs @@ -29,6 +29,7 @@ namespace ACAT.Core.UserControlManagement /// public class UserControlManager { + private static readonly ILogger _staticLogger = LoggingConfiguration.CreateLogger(); private readonly ILogger _logger; private int _iterationCount = 0; private int _iterations = 1; @@ -93,7 +94,7 @@ public static List findAllWidgets(List list) } catch (Exception es) { - _logger.LogError(es, "Error geting widgets: {Exception}", es.ToString()); + _staticLogger.LogError(es, "Error geting widgets: {Exception}", es.ToString()); } return Widgets; } diff --git a/src/Libraries/ACATCore/UserManagement/ProfileManager.cs b/src/Libraries/ACATCore/UserManagement/ProfileManager.cs index 86f8f7db..6daf6b84 100644 --- a/src/Libraries/ACATCore/UserManagement/ProfileManager.cs +++ b/src/Libraries/ACATCore/UserManagement/ProfileManager.cs @@ -6,6 +6,7 @@ //////////////////////////////////////////////////////////////////////////// using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.IO; @@ -21,6 +22,8 @@ namespace ACAT.Core.UserManagement /// public class ProfileManager { + private static readonly ILogger _logger = LoggingConfiguration.CreateLogger(); + /// /// Name of the default profile /// @@ -112,7 +115,7 @@ public static bool CreateProfileDir(String profileName) } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex, "Failed to create profile directory: {ProfileName}", profileName); retVal = false; } diff --git a/src/Libraries/ACATCore/UserManagement/UserManager.cs b/src/Libraries/ACATCore/UserManagement/UserManager.cs index 195cea50..063c0ed2 100644 --- a/src/Libraries/ACATCore/UserManagement/UserManager.cs +++ b/src/Libraries/ACATCore/UserManagement/UserManager.cs @@ -24,7 +24,7 @@ namespace ACAT.Core.UserManagement /// public class UserManager { - private static ILogger _logger; + private static readonly ILogger _logger = LoggingConfiguration.CreateLogger(); public const String BaseUserInstallDir = "Install\\Users"; @@ -43,7 +43,6 @@ public class UserManager /// static UserManager() { - _logger = LoggerFactory.Create(builder => builder.AddConsole()).CreateLogger(); _currentUserName = DefaultUserName; } @@ -107,7 +106,7 @@ public static bool CreateUser(String userName, String sourceUserInstallPath = nu var targetDir = Path.Combine(UserManager.CurrentUserDir); - Log.Debug("Copy directory " + srcDir + "=> " + targetDir); + _logger.LogDebug("Copy directory {SourceDir} => {TargetDir}", srcDir, targetDir); return FileUtils.CopyDir(srcDir, targetDir); } @@ -140,7 +139,7 @@ public static bool CreateUserDir(String userName) { MessageBox.Show("Error creating dir. ex: " + ex); - _logger.LogError(ex, ex.Message); + _logger.LogError(ex, "Failed to create user directory: {UserName}", userName); retVal = false; } diff --git a/src/Libraries/ACATCore/Utility/AutomationEventManager.cs b/src/Libraries/ACATCore/Utility/AutomationEventManager.cs index 65f585d4..be26c09e 100644 --- a/src/Libraries/ACATCore/Utility/AutomationEventManager.cs +++ b/src/Libraries/ACATCore/Utility/AutomationEventManager.cs @@ -1,10 +1,11 @@ -//////////////////////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////////////////// // // Copyright 2013-2019; 2023 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // //////////////////////////////////////////////////////////////////////////// +using ACAT.Core.PanelManagement; using Microsoft.Extensions.Logging; using System; using System.Collections; @@ -34,9 +35,15 @@ public class AutomationEventManager : IDisposable private readonly ILogger _logger; /// - /// Returns the singleton instance + /// Returns the singleton instance - lazy initialized to get logger from DI container /// - private static readonly AutomationEventManager _instance = new(); + private static readonly Lazy _instance = new Lazy(() => + { + // Get logger from DI container if available, otherwise use LogManager + ILogger logger = Context.ServiceProvider?.GetService(typeof(ILogger)) as ILogger + ?? LogManager.GetLogger(); + return new AutomationEventManager(logger); + }); /// /// Maps a window handle to its WindowElement object (see below) @@ -68,9 +75,9 @@ public class AutomationEventManager : IDisposable /// /// Prevents a default instance of AutomationEventManager class from being created /// - private AutomationEventManager(ILogger logger = null) + private AutomationEventManager(ILogger logger) { - _logger = logger; + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); Start(); } @@ -79,7 +86,7 @@ private AutomationEventManager(ILogger logger = null) /// public static AutomationEventManager Instance { - get { return _instance; } + get { return _instance.Value; } } /// @@ -95,7 +102,7 @@ public static void AddAutomationEventHandler(IntPtr hWnd, AutomationElement element, AutomationEventHandler eventHandler) { - _logger?.LogTrace("AddAutomationEventHandler called"); + Instance._logger.LogTrace("AddAutomationEventHandler called"); var windowElement = (WindowElement)WindowTable[hWnd]; if (windowElement == null) @@ -117,7 +124,7 @@ public static void AddAutomationEventHandler(IntPtr hWnd, } else { - _logger?.LogDebug("Found window element"); + Instance._logger.LogDebug("Found window element"); } // create the item and add it @@ -172,7 +179,7 @@ public static void AddAutomationPropertyChangedEventHandler(IntPtr hWnd, /// window handle public static void RemoveAllAutomationEventHandlers(IntPtr hwnd) { - _instance._logger?.LogDebug("RemoveAllAutomationEventHandlers: {Hwnd}", hwnd); + Instance._logger.LogDebug("RemoveAllAutomationEventHandlers: {Hwnd}", hwnd); lock (WindowTable) { @@ -181,17 +188,17 @@ public static void RemoveAllAutomationEventHandlers(IntPtr hwnd) var windowElement = (WindowElement)WindowTable[hwnd]; windowElement.EvtOnWindowClosed -= windowElement_EvtOnWindowClosed; - _instance._logger?.LogDebug("Found {Hwnd} in hashtable. removing it", hwnd); + Instance._logger.LogDebug("Found {Hwnd} in hashtable. removing it", hwnd); WindowTable.Remove(hwnd); - _instance._logger?.LogDebug("Calling RemoveAllEvents"); + Instance._logger.LogDebug("Calling RemoveAllEvents"); var item = new RemoveAllEventsItem { WinElement = windowElement }; RemoveAllEvents(item); } else { - _instance._logger?.LogDebug("Did not find {Hwnd} in hashtable", hwnd); + Instance._logger.LogDebug("Did not find {Hwnd} in hashtable", hwnd); } } } @@ -204,7 +211,7 @@ public static void RemoveAllAutomationEventHandlers(IntPtr hwnd) /// the automation element public static void RemoveAutomationEventHandler(IntPtr hWnd, AutomationEvent autoEvent, AutomationElement element) { - _instance._logger?.LogDebug("RemoveAutomationEventHandler: hWnd={HWnd}", hWnd); + Instance._logger.LogDebug("RemoveAutomationEventHandler: hWnd={HWnd}", hWnd); if (hWnd != IntPtr.Zero) { lock (WindowTable) @@ -238,7 +245,7 @@ public static void RemoveAutomationPropertyChangedEventHandler(IntPtr hWnd, AutomationElement element, AutomationPropertyChangedEventHandler eventHandler) { - _instance._logger?.LogTrace("RemoveAutomationPropertyChangedEventHandler called"); + Instance._logger.LogTrace("RemoveAutomationPropertyChangedEventHandler called"); if (hWnd == IntPtr.Zero) { @@ -350,7 +357,7 @@ protected virtual void Dispose(bool disposing) // Check to see if Dispose has already been called. if (!_disposed) { - _logger?.LogTrace("Dispose called"); + _logger.LogTrace("Dispose called"); try { @@ -362,15 +369,15 @@ protected virtual void Dispose(bool disposing) _queue.Enqueue(item); - _logger?.LogDebug("Aborting thread..."); + _logger.LogDebug("Aborting thread..."); _thread.Abort(); - _logger?.LogDebug("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. - _logger?.LogDebug("Calling Join"); + _logger.LogDebug("Calling Join"); _thread.Join(); - _logger?.LogDebug("Returned from join"); + _logger.LogDebug("Returned from join"); // dispose all managed resources. Automation.RemoveAllEventHandlers(); @@ -391,7 +398,7 @@ protected virtual void Dispose(bool disposing) /// item to add private static void AddAutomationEvent(AddEventHandlerItem item) { - _instance._queue.Enqueue(item); + Instance._queue.Enqueue(item); } /// @@ -400,7 +407,7 @@ private static void AddAutomationEvent(AddEventHandlerItem item) /// item to add private static void AddAutomationPropertyChanged(AddAutomationPropertyChangedItem item) { - _instance._queue.Enqueue(item); + Instance._queue.Enqueue(item); } /// @@ -448,7 +455,7 @@ private static void removeAllAutomationEventHandlers(Form form) /// item to add private static void RemoveAllEvents(RemoveAllEventsItem item) { - _instance._queue.Enqueue(item); + Instance._queue.Enqueue(item); } /// @@ -457,7 +464,7 @@ private static void RemoveAllEvents(RemoveAllEventsItem item) /// item to add private static void RemoveAutomationEvent(RemoveEventHandlerItem item) { - _instance._queue.Enqueue(item); + Instance._queue.Enqueue(item); } /// @@ -466,7 +473,7 @@ private static void RemoveAutomationEvent(RemoveEventHandlerItem item) /// item to add private static void RemoveAutomationPropertyChanged(RemoveAutomationPropertyChangedItem item) { - _instance._queue.Enqueue(item); + Instance._queue.Enqueue(item); } /// @@ -476,7 +483,7 @@ private static void RemoveAutomationPropertyChanged(RemoveAutomationPropertyChan /// handle to the window that was closed private static void windowElement_EvtOnWindowClosed(IntPtr hwnd) { - _instance._logger?.LogDebug("Window closed: {Hwnd}", hwnd); + Instance._logger?.LogDebug("Window closed: {Hwnd}", hwnd); RemoveAllAutomationEventHandlers(hwnd); } @@ -573,7 +580,7 @@ public WindowElement(IntPtr handle) } catch (Exception ex) { - _instance._logger?.LogError(ex, "Exception in WindowElement constructor"); + Instance._logger?.LogError(ex, "Exception in WindowElement constructor"); } } @@ -596,38 +603,38 @@ public WindowElement(IntPtr handle) /// the event handler public void AddAutomationEventHandler(AutomationElement element, AutomationEvent autoEvent, AutomationEventHandler eventHandler) { - _instance._logger?.LogTrace("AddAutomationEventHandler called"); + Instance._logger?.LogTrace("AddAutomationEventHandler called"); try { var events = (Hashtable)_controlElements[element]; if (events == null) { - _instance._logger?.LogDebug("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)) { - _instance._logger?.LogDebug("Events array does not contain. Adding automation event {EventName}. AutomationID: {AutomationId}", + 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); - _instance._logger?.LogDebug("Returned from AddAutomationEventHandler"); + Instance._logger?.LogDebug("Returned from AddAutomationEventHandler"); events.Add(autoEvent, eventHandler); - _instance._logger?.LogDebug("Done adding"); + Instance._logger?.LogDebug("Done adding"); } else { - _instance._logger?.LogDebug("Event already registered. Will not be readded {EventName}. AutomationID: {AutomationId}", + Instance._logger?.LogDebug("Event already registered. Will not be readded {EventName}. AutomationID: {AutomationId}", autoEvent.ProgrammaticName, element.Current.AutomationId ?? "none"); } } catch (Exception e) { - _instance._logger?.LogError(e, "Exception occurred in AddAutomationEventHandler"); + Instance._logger?.LogError(e, "Exception occurred in AddAutomationEventHandler"); } } @@ -641,7 +648,7 @@ public void AddAutomationPropertyChangedEventHandler(AutomationElement element, AutomationProperty property, AutomationPropertyChangedEventHandler eventHandler) { - _instance._logger?.LogTrace("AddAutomationPropertyChangedEventHandler called"); + Instance._logger?.LogTrace("AddAutomationPropertyChangedEventHandler called"); try { @@ -656,7 +663,7 @@ public void AddAutomationPropertyChangedEventHandler(AutomationElement element, { Automation.AddAutomationPropertyChangedEventHandler(element, TreeScope.Element, onPropertyChanged, property); - _instance._logger?.LogDebug("Adding property changed event {PropertyName}. AutomationID: {AutomationId}", + Instance._logger?.LogDebug("Adding property changed event {PropertyName}. AutomationID: {AutomationId}", property.ProgrammaticName, element.Current.AutomationId ?? "none"); @@ -671,7 +678,7 @@ public void AddAutomationPropertyChangedEventHandler(AutomationElement element, var eventHandlerList = (List)events[property]; if (!eventHandlerList.Contains(eventHandler)) { - _instance._logger?.LogDebug("Registering event. {PropertyName}. AutomationID: {AutomationId}", + Instance._logger?.LogDebug("Registering event. {PropertyName}. AutomationID: {AutomationId}", property.ProgrammaticName, element.Current.AutomationId ?? "none"); @@ -679,7 +686,7 @@ public void AddAutomationPropertyChangedEventHandler(AutomationElement element, } else { - _instance._logger?.LogDebug("Property change already registered. {PropertyName}. AutomationID: {AutomationId}", + Instance._logger?.LogDebug("Property change already registered. {PropertyName}. AutomationID: {AutomationId}", property.ProgrammaticName, element.Current.AutomationId ?? "none"); } @@ -687,7 +694,7 @@ public void AddAutomationPropertyChangedEventHandler(AutomationElement element, } catch (Exception e) { - _instance._logger?.LogError(e, "Exception in AddAutomationPropertyChangedEventHandler"); + Instance._logger?.LogError(e, "Exception in AddAutomationPropertyChangedEventHandler"); } } @@ -696,15 +703,15 @@ public void AddAutomationPropertyChangedEventHandler(AutomationElement element, /// public void RemoveAllEvents() { - _instance._logger?.LogTrace("RemoveAllEvents called"); + Instance._logger?.LogTrace("RemoveAllEvents called"); try { - _instance._logger?.LogDebug("ControlElements count: {Count}", _controlElements.Count); + Instance._logger?.LogDebug("ControlElements count: {Count}", _controlElements.Count); foreach (AutomationElement element in _controlElements.Keys) { var events = (Hashtable)_controlElements[element]; - _instance._logger?.LogDebug("events count: {Count}", events.Count); + Instance._logger?.LogDebug("events count: {Count}", events.Count); foreach (var key in events.Keys) { if (key is AutomationEvent) @@ -713,9 +720,9 @@ public void RemoveAllEvents() var eventHandler = (AutomationEventHandler)events[autoEvent]; try { - _instance._logger?.LogDebug("Removing automation event {EventName}", autoEvent.ProgrammaticName); + Instance._logger?.LogDebug("Removing automation event {EventName}", autoEvent.ProgrammaticName); Automation.RemoveAutomationEventHandler(autoEvent, element, eventHandler); - _instance._logger?.LogDebug("Done removing automation event"); + Instance._logger?.LogDebug("Done removing automation event"); } catch { } } @@ -725,9 +732,9 @@ public void RemoveAllEvents() var eventHandler = (AutomationPropertyChangedEventHandler)events[autoProperty]; try { - _instance._logger?.LogDebug("Removing automation property {PropertyName}", autoProperty.ProgrammaticName); + Instance._logger?.LogDebug("Removing automation property {PropertyName}", autoProperty.ProgrammaticName); Automation.RemoveAutomationPropertyChangedEventHandler(element, eventHandler); - _instance._logger?.LogDebug("Done removing automation property"); + Instance._logger?.LogDebug("Done removing automation property"); } catch { } } @@ -738,7 +745,7 @@ public void RemoveAllEvents() } catch (Exception e) { - _instance._logger?.LogError(e, "Exception occurred in RemoveAllEvents"); + Instance._logger?.LogError(e, "Exception occurred in RemoveAllEvents"); } } @@ -749,28 +756,28 @@ public void RemoveAllEvents() /// the event public void RemoveAutomationEventHandler(AutomationElement element, AutomationEvent autoEvent) { - _instance._logger?.LogTrace("RemoveAutomationEventHandler called"); + Instance._logger?.LogTrace("RemoveAutomationEventHandler called"); try { var events = (Hashtable)_controlElements[element]; if (events != null && events.Contains(autoEvent)) { - _instance._logger?.LogDebug("Removing automation event {EventName}", autoEvent.ProgrammaticName); + Instance._logger?.LogDebug("Removing automation event {EventName}", autoEvent.ProgrammaticName); var eventHandler = (AutomationEventHandler)events[autoEvent]; Automation.RemoveAutomationEventHandler(autoEvent, element, eventHandler); - _instance._logger?.LogDebug("RemoveAutomationEventHandler succeeded!"); + Instance._logger?.LogDebug("RemoveAutomationEventHandler succeeded!"); events.Remove(autoEvent); } else { - _instance._logger?.LogDebug("Event already Removed. {EventName}. AutomationID: {AutomationId}", + Instance._logger?.LogDebug("Event already Removed. {EventName}. AutomationID: {AutomationId}", autoEvent.ProgrammaticName, element.Current.AutomationId ?? "none"); } } catch (Exception e) { - _instance._logger?.LogError(e, "Exception in RemoveAutomationEventHandler"); + Instance._logger?.LogError(e, "Exception in RemoveAutomationEventHandler"); } } @@ -784,11 +791,11 @@ public void RemoveAutomationPropertyChangedEventHandler(AutomationElement elemen AutomationProperty property, AutomationPropertyChangedEventHandler eventHandler) { - _instance._logger?.LogTrace("RemoveAutomationPropertyChangedEventHandler called"); + Instance._logger?.LogTrace("RemoveAutomationPropertyChangedEventHandler called"); try { - _instance._logger?.LogDebug("Removing propertychanged event for automation property {PropertyName}", 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)) { @@ -796,28 +803,28 @@ public void RemoveAutomationPropertyChangedEventHandler(AutomationElement elemen if (eventHandlerList.Contains(eventHandler)) { eventHandlerList.Remove(eventHandler); - _instance._logger?.LogDebug("RemoveAutomationPropertyChangedEventHandler succeeded!"); + Instance._logger?.LogDebug("RemoveAutomationPropertyChangedEventHandler succeeded!"); if (eventHandlerList.Count == 0) { - _instance._logger?.LogDebug("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 { - _instance._logger?.LogError("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 { - _instance._logger?.LogError("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) { - _instance._logger?.LogError(e, "Exception occurred in RemoveAutomationPropertyChangedEventHandler"); + Instance._logger?.LogError(e, "Exception occurred in RemoveAutomationPropertyChangedEventHandler"); } } @@ -829,7 +836,7 @@ public void RemoveAutomationPropertyChangedEventHandler(AutomationElement elemen /// event args private void onPropertyChanged(object sender, AutomationPropertyChangedEventArgs e) { - _instance._logger?.LogDebug("Property changed: {PropertyName}", e.Property.ProgrammaticName); + Instance._logger?.LogDebug("Property changed: {PropertyName}", e.Property.ProgrammaticName); var element = sender as AutomationElement; Hashtable events = (Hashtable)_controlElements[element]; @@ -837,10 +844,10 @@ private void onPropertyChanged(object sender, AutomationPropertyChangedEventArgs if (events != null && events.Contains(e.Property)) { var eventHandlerList = (List)events[e.Property]; - _instance._logger?.LogDebug("eventHandlerList.Count = {Count}", eventHandlerList.Count); + Instance._logger?.LogDebug("eventHandlerList.Count = {Count}", eventHandlerList.Count); foreach (var p in eventHandlerList) { - _instance._logger?.LogDebug("Calling property changed for {PropertyName}", e.Property.ProgrammaticName); + Instance._logger?.LogDebug("Calling property changed for {PropertyName}", e.Property.ProgrammaticName); p(sender, e); } } @@ -855,10 +862,11 @@ private void onWindowClose(object sender, AutomationEventArgs e) { if (EvtOnWindowClosed != null) { - _instance._logger?.LogDebug("Triggering event closed"); + Instance._logger?.LogDebug("Triggering event closed"); EvtOnWindowClosed(_hwnd); } } } } -} \ No newline at end of file +} + diff --git a/src/Libraries/ACATCore/Utility/DirectoryWalker.cs b/src/Libraries/ACATCore/Utility/DirectoryWalker.cs index dff1d2a4..bd3abe18 100644 --- a/src/Libraries/ACATCore/Utility/DirectoryWalker.cs +++ b/src/Libraries/ACATCore/Utility/DirectoryWalker.cs @@ -64,7 +64,7 @@ public DirectoryWalker(String rootDir) : this(rootDir, string.Empty) public DirectoryWalker(String rootDir, String fileWildCard, ILogger logger = null) { - _logger = logger ?? LoggerFactory.Create(builder => builder.AddConsole()).CreateLogger(); + _logger = logger ?? LoggingConfiguration.CreateLogger(); _rootDir = rootDir; _wildCard = fileWildCard; } diff --git a/src/Libraries/ACATCore/Utility/EnumWindows.cs b/src/Libraries/ACATCore/Utility/EnumWindows.cs index 8a288232..68a12f89 100644 --- a/src/Libraries/ACATCore/Utility/EnumWindows.cs +++ b/src/Libraries/ACATCore/Utility/EnumWindows.cs @@ -57,7 +57,7 @@ public static class EnumWindows static EnumWindows() { - _logger = LoggerFactory.Create(builder => builder.AddConsole()).CreateLogger(typeof(EnumWindows)); + _logger = LoggingConfiguration.CreateLogger(typeof(EnumWindows).Name); } /// diff --git a/src/Libraries/ACATCore/Utility/ExtensionInstantiator.cs b/src/Libraries/ACATCore/Utility/ExtensionInstantiator.cs new file mode 100644 index 00000000..32b67604 --- /dev/null +++ b/src/Libraries/ACATCore/Utility/ExtensionInstantiator.cs @@ -0,0 +1,104 @@ +using ACAT.Core.Extensions; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; + +namespace ACAT.Core.Utility +{ + /// + /// Helper class for creating extension instances with proper dependency injection + /// + public static class ExtensionInstantiator + { + /// + /// Creates instances of extension types using dependency injection. + /// This ensures extensions receive proper logger instances and other registered services. + /// + /// The service provider for dependency resolution + /// Collection of extension types to instantiate + /// Optional logger for diagnostics + /// Collection of successfully created extension instances + public static IEnumerable CreateExtensionInstances( + IServiceProvider serviceProvider, + IEnumerable extensionTypes, + ILogger logger = null) + { + if (serviceProvider == null) + throw new ArgumentNullException(nameof(serviceProvider)); + + if (extensionTypes == null) + return Enumerable.Empty(); + + var extensions = new List(); + + foreach (var type in extensionTypes) + { + try + { + logger?.LogDebug("Creating extension instance for {TypeName}", type.FullName); + + // Use ActivatorUtilities to create instances with proper dependency injection + // This automatically resolves ILogger and other registered services + var instance = ActivatorUtilities.CreateInstance(serviceProvider, type); + + if (instance is IExtension extension) + { + extensions.Add(extension); + logger?.LogInformation("Successfully loaded extension: {ExtensionName}", type.Name); + } + else + { + logger?.LogWarning("Type {TypeName} does not implement IExtension interface", type.FullName); + } + } + catch (Exception ex) + { + logger?.LogError(ex, "Failed to create instance of {TypeName}. This extension will be skipped.", type.FullName); + } + } + + return extensions; + } + + /// + /// Creates a single extension instance using dependency injection + /// + /// The service provider for dependency resolution + /// The extension type to instantiate + /// Optional logger for diagnostics + /// The created extension instance, or null if creation fails + public static object CreateExtensionInstance( + IServiceProvider serviceProvider, + Type extensionType, + ILogger logger = null) + { + if (serviceProvider == null) + throw new ArgumentNullException(nameof(serviceProvider)); + + if (extensionType == null) + return null; + + try + { + logger?.LogDebug("Creating extension instance for {TypeName}", extensionType.FullName); + var instance = ActivatorUtilities.CreateInstance(serviceProvider, extensionType); + + if (instance != null) + { + logger?.LogInformation("Successfully loaded extension: {ExtensionName}", extensionType.Name); + return instance; + } + + logger?.LogWarning("Failed to create instance of type {TypeName}", extensionType.FullName); + return null; + } + catch (Exception ex) + { + logger?.LogError(ex, "Failed to create instance of {TypeName}", extensionType.FullName); + return null; + } + } + } +} diff --git a/src/Libraries/ACATCore/Utility/FileUtils.cs b/src/Libraries/ACATCore/Utility/FileUtils.cs index e4f4ae84..76289e68 100644 --- a/src/Libraries/ACATCore/Utility/FileUtils.cs +++ b/src/Libraries/ACATCore/Utility/FileUtils.cs @@ -26,7 +26,7 @@ namespace ACAT.Core.Utility /// public class FileUtils { - private static ILogger _logger; + private static ILogger _logger => LogManager.GetLogger(); /// /// Folder under which ACAT extensions are stored @@ -728,7 +728,7 @@ public static bool RunBatchFile(String batchFileName, params String[] argList) } catch (Exception ex) { - Log.Exception(ex); + _logger?.LogError(ex, "Exception in RunBatchFile"); retVal = false; } @@ -764,7 +764,7 @@ private static void copyDir(string srcDir, string targetDir, bool recursive = tr if (!dir.Exists) { - Log.Error("No such directory: " + srcDir); + _logger?.LogError("No such directory: {SrcDir}", srcDir); return; } @@ -794,7 +794,7 @@ private static void copyDir(string srcDir, string targetDir, bool recursive = tr } catch (Exception ex) { - Log.Exception("Error copying file " + file.FullName + " to " + targetFile + ", exception: " + ex); + _logger?.LogError(ex, "Error copying file {SourceFile} to {TargetFile}", file.FullName, targetFile); } } diff --git a/src/Libraries/ACATCore/Utility/GlobalPreferences.cs b/src/Libraries/ACATCore/Utility/GlobalPreferences.cs index f4091c89..6dcd9f05 100644 --- a/src/Libraries/ACATCore/Utility/GlobalPreferences.cs +++ b/src/Libraries/ACATCore/Utility/GlobalPreferences.cs @@ -18,7 +18,7 @@ namespace ACAT.Core.Utility [Serializable] public class GlobalPreferences { - private static ILogger _logger; + private static ILogger _logger => LogManager.GetLogger(); public static String DefaultPreferencesFilePath = String.Empty; public static String LogFileName = String.Empty; diff --git a/src/Libraries/ACATCore/Utility/HtmlUtils.cs b/src/Libraries/ACATCore/Utility/HtmlUtils.cs index 8f9119a5..8cb02b88 100644 --- a/src/Libraries/ACATCore/Utility/HtmlUtils.cs +++ b/src/Libraries/ACATCore/Utility/HtmlUtils.cs @@ -18,7 +18,7 @@ namespace ACAT.Core.Utility { public class HtmlUtils { - private static ILogger _logger; + private static ILogger _logger => LogManager.GetLogger(); /// /// Paths of the browsers exe /// diff --git a/src/Libraries/ACATCore/Utility/ImageUtils.cs b/src/Libraries/ACATCore/Utility/ImageUtils.cs index 781f4e4e..411ae299 100644 --- a/src/Libraries/ACATCore/Utility/ImageUtils.cs +++ b/src/Libraries/ACATCore/Utility/ImageUtils.cs @@ -19,7 +19,7 @@ namespace ACAT.Core.Utility /// public class ImageUtils { - private static ILogger _logger; + private static ILogger _logger => LogManager.GetLogger(); /// /// Converts the specified icon into a bitmap /// diff --git a/src/Libraries/ACATCore/Utility/KeyStateTracker.cs b/src/Libraries/ACATCore/Utility/KeyStateTracker.cs index 0227d58c..3bd2e527 100644 --- a/src/Libraries/ACATCore/Utility/KeyStateTracker.cs +++ b/src/Libraries/ACATCore/Utility/KeyStateTracker.cs @@ -26,7 +26,7 @@ namespace ACAT.Core.Utility /// public class KeyStateTracker { - private static ILogger _logger; + private static ILogger _logger => LogManager.GetLogger(); private const byte VK_CAPITAL = 0x14; private const byte VK_NUMLOCK = 0x90; @@ -110,19 +110,19 @@ public static List GetExtendedKeys() if (IsCtrlOn()) { - Log.Debug("Ctrl is on"); + _logger?.LogDebug("Ctrl is on"); retVal.Add(Keys.LControlKey); } if (IsAltOn()) { - Log.Debug("Alt is on"); + _logger?.LogDebug("Alt is on"); retVal.Add(Keys.LMenu); } if (IsShiftOn() && !IsCapsLockOn()) { - Log.Debug("Shift is on"); + _logger?.LogDebug("Shift is on"); retVal.Add(Keys.LShiftKey); } @@ -246,7 +246,7 @@ public static bool KeyDown(Keys key) { bool retVal = true; - Log.Debug(key.ToString()); + _logger?.LogDebug("Key down: {Key}", key); switch (key) { @@ -354,7 +354,7 @@ public static void KeyTriggered(Keys key) /// public static void KeyUp(Keys key) { - Log.Debug(key.ToString()); + _logger?.LogDebug("Key up: {Key}", key); switch (key) { diff --git a/src/Libraries/ACATCore/Utility/LogManager.cs b/src/Libraries/ACATCore/Utility/LogManager.cs new file mode 100644 index 00000000..a6449efe --- /dev/null +++ b/src/Libraries/ACATCore/Utility/LogManager.cs @@ -0,0 +1,94 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2013-2019; 2023 Intel Corporation +// SPDX-License-Identifier: Apache-2.0 +// +//////////////////////////////////////////////////////////////////////////// + +using Microsoft.Extensions.Logging; +using System; + +namespace ACAT.Core.Utility +{ + /// + /// Central logging manager that provides loggers from any context. + /// Can be used before or after DI container initialization. + /// Thread-safe and singleton-based. + /// + public static class LogManager + { + private static readonly object _lock = new object(); + private static ILoggerFactory _loggerFactory; + private static bool _isInitialized = false; + + /// + /// Initialize the logging system with a specific logger factory. + /// This should be called early in application startup. + /// + /// The logger factory to use + public static void Initialize(ILoggerFactory loggerFactory) + { + lock (_lock) + { + _loggerFactory = loggerFactory; + _isInitialized = true; + } + } + + /// + /// Gets a logger for the specified type. + /// Creates a default logger factory if not yet initialized. + /// + /// The type to create a logger for + /// Logger instance (never null) + public static ILogger GetLogger() + { + EnsureInitialized(); + return _loggerFactory.CreateLogger(); + } + + /// + /// Gets a logger with the specified category name. + /// Creates a default logger factory if not yet initialized. + /// + /// The category name for the logger + /// Logger instance (never null) + public static ILogger GetLogger(string categoryName) + { + EnsureInitialized(); + return _loggerFactory.CreateLogger(categoryName); + } + + /// + /// Gets a logger for the specified type. + /// Creates a default logger factory if not yet initialized. + /// + /// The type to create a logger for + /// Logger instance (never null) + public static ILogger GetLogger(Type type) + { + EnsureInitialized(); + return _loggerFactory.CreateLogger(type); + } + + /// + /// Ensures the logger factory is initialized. + /// If not explicitly initialized, creates a default factory. + /// + private static void EnsureInitialized() + { + if (!_isInitialized) + { + lock (_lock) + { + if (!_isInitialized) + { + // Create default factory if not explicitly initialized + _loggerFactory = LoggingConfiguration.CreateLoggerFactory(); + _isInitialized = true; + } + } + } + } + } +} diff --git a/src/Libraries/ACATCore/Utility/Mouse/MouseGridScanWindow.xaml.cs b/src/Libraries/ACATCore/Utility/Mouse/MouseGridScanWindow.xaml.cs index 95c5eb49..2436b267 100644 --- a/src/Libraries/ACATCore/Utility/Mouse/MouseGridScanWindow.xaml.cs +++ b/src/Libraries/ACATCore/Utility/Mouse/MouseGridScanWindow.xaml.cs @@ -6,6 +6,7 @@ //////////////////////////////////////////////////////////////////////////// using ACAT.Core.Utility.Mouse; +using Microsoft.Extensions.Logging; using System; //using System.Drawing; @@ -36,6 +37,8 @@ namespace ACAT.Core.Utility /// public partial class MouseGridScanWindow { + private readonly ILogger _logger; + /// /// Used for the state machine /// @@ -163,8 +166,9 @@ public partial class MouseGridScanWindow /// /// Initializes an instance of the class /// - public MouseGridScanWindow() + public MouseGridScanWindow(ILogger logger = null) { + _logger = logger; InitializeComponent(); init(); @@ -487,7 +491,7 @@ private void animateSetCursorPos() System.Windows.Point screen = MyCanvas.PointToScreen(new System.Windows.Point(x, y)); System.Drawing.Point winFormsPoint = new((int)screen.X, (int)screen.Y); - Log.Debug($"Setting cursor position to {winFormsPoint}"); + _logger?.LogDebug("Setting cursor position to {Position}", winFormsPoint); System.Windows.Forms.Cursor.Position = winFormsPoint; } diff --git a/src/Libraries/ACATCore/Utility/ResourceUtils.cs b/src/Libraries/ACATCore/Utility/ResourceUtils.cs index 0bf85dd5..bb519d47 100644 --- a/src/Libraries/ACATCore/Utility/ResourceUtils.cs +++ b/src/Libraries/ACATCore/Utility/ResourceUtils.cs @@ -19,7 +19,7 @@ namespace ACAT.Core.Utility /// public class ResourceUtils { - private static ILogger _logger; + private static ILogger _logger => LogManager.GetLogger(); /// /// Name of the language resources dll /// diff --git a/src/Libraries/ACATCore/Utility/SoundManager.cs b/src/Libraries/ACATCore/Utility/SoundManager.cs index 50194f17..ab69a78b 100644 --- a/src/Libraries/ACATCore/Utility/SoundManager.cs +++ b/src/Libraries/ACATCore/Utility/SoundManager.cs @@ -19,7 +19,7 @@ namespace ACAT.Core.Utility /// public class SoundManager { - private static ILogger _logger; + private static ILogger _logger => LogManager.GetLogger(); /// /// Are the sounds initialized /// diff --git a/src/Libraries/ACATCore/Utility/TextUtils.cs b/src/Libraries/ACATCore/Utility/TextUtils.cs index c5a9a018..6176ea89 100644 --- a/src/Libraries/ACATCore/Utility/TextUtils.cs +++ b/src/Libraries/ACATCore/Utility/TextUtils.cs @@ -19,6 +19,12 @@ namespace ACAT.Core.Utility public class TextUtils { private static ILogger _logger; + + static TextUtils() + { + _logger = LoggingConfiguration.CreateLogger(); + } + /// /// Converts a byte array into a hex string /// @@ -115,12 +121,12 @@ public static bool CheckInsertOrReplaceWord(String inputString, int caretPos, ou int index = caretPos; insertOrReplaceOffset = caretPos; - Log.Debug("index: " + index + ", inputString[index] is [" + inputString[index] + "]"); + _logger.LogDebug("index: " + index + ", inputString[index] is [" + inputString[index] + "]"); // cursor is not within a word if (Char.IsWhiteSpace(inputString[index])) { insertOrReplaceOffset = caretPos + 1; - Log.Debug("iswhiespace. return true " + insertOrReplaceOffset); + _logger.LogDebug("iswhiespace. return true " + insertOrReplaceOffset); return true; } @@ -129,7 +135,7 @@ public static bool CheckInsertOrReplaceWord(String inputString, int caretPos, ou if (IsSentenceTerminator(inputString[index])) { insertOrReplaceOffset = caretPos + 1; - Log.Debug("is sentence terminator. return true " + insertOrReplaceOffset); + _logger.LogDebug("is sentence terminator. return true " + insertOrReplaceOffset); return true; } @@ -137,19 +143,19 @@ public static bool CheckInsertOrReplaceWord(String inputString, int caretPos, ou if (IsWordElement(inputString[index])) { insertOrReplaceOffset = getWordToReplace(inputString, caretPos, out wordToReplace); - Log.Debug("iswordelement is true. return false " + insertOrReplaceOffset); + _logger.LogDebug("iswordelement is true. return false " + insertOrReplaceOffset); return false; } else { insertOrReplaceOffset = caretPos + 1; - Log.Debug("iswordelement is false. return true " + insertOrReplaceOffset); + _logger.LogDebug("iswordelement is false. return true " + insertOrReplaceOffset); return true; } } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex.ToString()); insertOrReplaceOffset = 0; wordToReplace = String.Empty; return true; @@ -211,7 +217,7 @@ public static int GetEntireParagraphAtCaret(String inputString, int caretPos, ou int startPos = index + 1; - Log.Debug("startPos = " + startPos); + _logger.LogDebug("startPos = " + startPos); index = startPos; @@ -223,21 +229,21 @@ public static int GetEntireParagraphAtCaret(String inputString, int caretPos, ou int endPos = index - 1; - Log.Debug("endPos = " + endPos); + _logger.LogDebug("endPos = " + endPos); int count = endPos - startPos + 1; - Log.Debug("count = " + count); + _logger.LogDebug("count = " + count); paragraphAtCaret = (count > 0) ? inputString.Substring(startPos, count) : String.Empty; - Log.Debug("para: [" + paragraphAtCaret + "]"); + _logger.LogDebug("para: [" + paragraphAtCaret + "]"); return startPos; } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex.ToString()); paragraphAtCaret = String.Empty; return 0; } @@ -402,7 +408,7 @@ public static int GetParagraphAtCaret(String inputString, int caretPos, out Stri } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex.ToString()); paragraphAtCaret = String.Empty; return 0; } @@ -426,7 +432,7 @@ public static int GetPrecedingCharacters(String input, int caretPos, int numberO } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex.ToString()); word = String.Empty; return 0; } @@ -473,7 +479,7 @@ public static bool GetPrecedingWhiteSpaces(String inputString, int caretPos, out offset = index; count = caretPos - offset; - Log.Debug("offset: " + offset + ", caretPos: " + caretPos + ", count: " + count); + _logger.LogDebug("offset: " + offset + ", caretPos: " + caretPos + ", count: " + count); return true; } @@ -496,21 +502,17 @@ public static int GetPrefixAndWordAtCaret(String inputString, int caretPos, out prefix = String.Empty; wordAtCaret = String.Empty; - Log.Verbose(); - - //Log.Debug("inputstring: [" + inputString + "]"); - // first get the current sentence int startPos = GetSentenceAtCaret(inputString, caretPos, out string sentenceAtCaret); if (startPos < 0) { - Log.Debug("returning " + startPos); + _logger.LogDebug("returning " + startPos); return startPos; } if (String.IsNullOrEmpty(sentenceAtCaret)) { - Log.Debug("returning " + startPos); + _logger.LogDebug("returning " + startPos); return startPos; } @@ -518,27 +520,27 @@ public static int GetPrefixAndWordAtCaret(String inputString, int caretPos, out //Log.Debug("Calling getwordatcaret. InputString: [" + inputString + "]"); int wordPos = GetWordAtCaret(inputString, caretPos, out string w); - Log.Debug("startPos: " + startPos + "wordPos: " + wordPos + " wordPos-startPos: " + (wordPos - startPos)); - Log.Debug("Getwordatcaret returned [" + w + "]"); + _logger.LogDebug("startPos: " + startPos + "wordPos: " + wordPos + " wordPos-startPos: " + (wordPos - startPos)); + _logger.LogDebug("Getwordatcaret returned [" + w + "]"); int count = wordPos - startPos; - Log.Debug("count: " + count); + _logger.LogDebug("count: " + count); if (count > 0) { - Log.Debug("Getting substring: startPos: " + startPos + ", count: " + count); + _logger.LogDebug("Getting substring: startPos: " + startPos + ", count: " + count); } prefix = (count > 0) ? inputString.Substring(startPos, count) : String.Empty; - Log.Debug("prefix: [" + prefix + "]"); + _logger.LogDebug("prefix: [" + prefix + "]"); if (!String.IsNullOrEmpty(w)) { - Log.Debug("caretPos: " + caretPos + " wordPos: " + wordPos); + _logger.LogDebug("caretPos: " + caretPos + " wordPos: " + wordPos); count = caretPos - wordPos; if (count > 0) { - Log.Debug("calling w.Substring starting at 0, count = " + count); + _logger.LogDebug("calling w.Substring starting at 0, count = " + count); } if (count >= w.Length) @@ -553,12 +555,12 @@ public static int GetPrefixAndWordAtCaret(String inputString, int caretPos, out wordAtCaret = String.Empty; } - Log.Debug("returning " + startPos); + _logger.LogDebug("returning " + startPos); return startPos; } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex.ToString()); prefix = String.Empty; wordAtCaret = String.Empty; return 0; @@ -616,13 +618,13 @@ public static int GetPreviousWord(String input, int caretPos, out String word) word = (count > 0) ? input.Substring(startPos, count) : String.Empty; - Log.Debug("word: " + word); + _logger.LogDebug("word: " + word); return startPos; } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex.ToString()); word = String.Empty; return 0; } @@ -663,14 +665,14 @@ public static bool GetPrevWordOffset(String inputString, int caretPos, out int o int index = caretPos; offset = caretPos; int endPos = caretPos; - Log.Debug("endPos: " + endPos); + _logger.LogDebug("endPos: " + endPos); while (index >= 0 && Char.IsWhiteSpace(inputString[index])) { index--; } - Log.Debug("HARRIS Before: index: " + index + " char: [" + inputString[index] + "]"); + _logger.LogDebug("HARRIS Before: index: " + index + " char: [" + inputString[index] + "]"); /* while (index >= 0 && (IsTerminator(inputString[index]) || inputString[index] == '-')) @@ -691,8 +693,8 @@ public static bool GetPrevWordOffset(String inputString, int caretPos, out int o index--; } - Log.Debug("HARRIS After index: " + index + " char: [" + inputString[index] + "]"); - Log.Debug("HARRIS Count dash: " + countDash); + _logger.LogDebug("HARRIS After index: " + index + " char: [" + inputString[index] + "]"); + _logger.LogDebug("HARRIS Count dash: " + countDash); if (countDash > 1) { @@ -737,7 +739,7 @@ public static bool GetPrevWordOffset(String inputString, int caretPos, out int o } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex.ToString()); offset = 0; count = 0; return false; @@ -779,14 +781,14 @@ public static bool GetPrevWordOffsetAutoComplete(String inputString, int caretPo int index = caretPos; offset = caretPos; int endPos = caretPos; - Log.Debug("endPos: " + endPos); + _logger.LogDebug("endPos: " + endPos); while (index >= 0 && Char.IsWhiteSpace(inputString[index])) { index--; } - Log.Debug("HARRIS Before: index: " + index + " char: [" + inputString[index] + "]"); + _logger.LogDebug("HARRIS Before: index: " + index + " char: [" + inputString[index] + "]"); /* while (index >= 0 && (IsTerminator(inputString[index]) || inputString[index] == '-')) @@ -807,8 +809,8 @@ public static bool GetPrevWordOffsetAutoComplete(String inputString, int caretPo index--; } - Log.Debug("HARRIS After index: " + index + " char: [" + inputString[index] + "]"); - Log.Debug("HARRIS Count dash: " + countDash); + _logger.LogDebug("HARRIS After index: " + index + " char: [" + inputString[index] + "]"); + _logger.LogDebug("HARRIS Count dash: " + countDash); if (countDash > 1) { @@ -854,7 +856,7 @@ public static bool GetPrevWordOffsetAutoComplete(String inputString, int caretPo } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex.ToString()); offset = 0; count = 0; return false; @@ -876,10 +878,9 @@ public static int GetSentenceAtCaret(String inputString, int caretPos, out Strin { sentenceAtCaret = String.Empty; - Log.Verbose(); if (String.IsNullOrEmpty(inputString.Trim())) { - Log.Debug("returning -1"); + _logger.LogDebug("returning -1"); return -1; } @@ -915,12 +916,12 @@ public static int GetSentenceAtCaret(String inputString, int caretPos, out Strin int count = endPos - startPos + 1; sentenceAtCaret = (count > 0) ? inputString.Substring(startPos, count) : String.Empty; - Log.Debug("returning " + startPos); + _logger.LogDebug("returning " + startPos); return startPos; } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex.ToString()); sentenceAtCaret = String.Empty; return 0; } @@ -1037,13 +1038,13 @@ public static int GetWordAtCaret(String inputString, int caretPos, out String wo { int startPos = caretPos; - //Log.Debug("inputString: [" + inputString + "], caretPos: " + caretPos); - Log.Debug("caretPos: " + caretPos); + //_logger.LogDebug("inputString: [" + inputString + "], caretPos: " + caretPos); + _logger.LogDebug("caretPos: " + caretPos); wordAtCaret = String.Empty; if (String.IsNullOrEmpty(inputString)) { - Log.Debug("inputstring is empty. returning"); + _logger.LogDebug("inputstring is empty. returning"); return -1; } @@ -1109,21 +1110,21 @@ public static int GetWordAtCaret(String inputString, int caretPos, out String wo if (endPos >= startPos) { - Log.Debug("wordAtCaret: Getting substring from startPos: " + startPos + ", length: " + (endPos - startPos)); + _logger.LogDebug("wordAtCaret: Getting substring from startPos: " + startPos + ", length: " + (endPos - startPos)); wordAtCaret = inputString.Substring(startPos, endPos - startPos).Trim(); - Log.Debug("wordAtCaret: [" + wordAtCaret + "]"); + _logger.LogDebug("wordAtCaret: [" + wordAtCaret + "]"); } else { wordAtCaret = String.Empty; } - Log.Debug("returning " + startPos + ", wordatCaret: " + wordAtCaret); + _logger.LogDebug("returning " + startPos + ", wordatCaret: " + wordAtCaret); return startPos; } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex.ToString()); wordAtCaret = String.Empty; return 0; } @@ -1288,12 +1289,12 @@ private static int getWordToReplace(String inputString, int caretPos, out String { int startPos = caretPos; - Log.Debug("Enter startPos: " + startPos); + _logger.LogDebug("Enter startPos: " + startPos); while (startPos >= 0) { if (!IsWordElement(inputString[startPos])) { - Log.Debug("Breaking. No word element at : " + startPos); + _logger.LogDebug("Breaking. No word element at : " + startPos); break; } @@ -1302,7 +1303,7 @@ private static int getWordToReplace(String inputString, int caretPos, out String startPos++; - Log.Debug("1 startPos: " + startPos); + _logger.LogDebug("1 startPos: " + startPos); if (startPos < 0) { @@ -1311,36 +1312,36 @@ private static int getWordToReplace(String inputString, int caretPos, out String int endPos = caretPos; - Log.Debug("endPos: " + endPos); + _logger.LogDebug("endPos: " + endPos); while (endPos < inputString.Length) { if (!IsWordElement(inputString[endPos])) { - Log.Debug("Breaking. No word element at : " + endPos); + _logger.LogDebug("Breaking. No word element at : " + endPos); break; } endPos++; } - Log.Debug("After loop endPos : " + endPos); + _logger.LogDebug("After loop endPos : " + endPos); if (endPos > inputString.Length) { endPos = inputString.Length; } - Log.Debug("getWordAt: startpos, endpos = " + startPos + ", " + endPos); + _logger.LogDebug("getWordAt: startpos, endpos = " + startPos + ", " + endPos); int count = endPos - startPos; - Log.Debug("count: " + count); - Log.Debug("Calling substring: " + startPos + ", " + (endPos - startPos)); + _logger.LogDebug("count: " + count); + _logger.LogDebug("Calling substring: " + startPos + ", " + (endPos - startPos)); wordAtCaret = (count > 0) ? inputString.Substring(startPos, endPos - startPos) : String.Empty; - Log.Debug("returning startPos : " + startPos); + _logger.LogDebug("returning startPos : " + startPos); return startPos; } diff --git a/src/Libraries/ACATCore/Utility/TimerQueue.cs b/src/Libraries/ACATCore/Utility/TimerQueue.cs index a7cce537..46dd9746 100644 --- a/src/Libraries/ACATCore/Utility/TimerQueue.cs +++ b/src/Libraries/ACATCore/Utility/TimerQueue.cs @@ -5,6 +5,7 @@ // //////////////////////////////////////////////////////////////////////////// +using Microsoft.Extensions.Logging; using System; using System.Runtime.InteropServices; @@ -18,6 +19,8 @@ namespace ACAT.Core.Utility /// public class TimerQueue : IDisposable { + private static ILogger _logger => LogManager.GetLogger(); + /// /// Windows constant /// @@ -133,7 +136,7 @@ public bool Start(IntPtr param) if (_isRunning == true) { // already running - Log.Debug("Timer is already running. returning"); + _logger?.LogDebug("Timer is already running. returning"); return true; } @@ -153,7 +156,7 @@ public bool Start(IntPtr param) else { getLastError = Marshal.GetLastWin32Error(); - Log.Debug("Error while starting timer. getLastError=" + getLastError); + _logger?.LogDebug("Error while starting timer. getLastError={GetLastError}", getLastError); } return retVal; @@ -166,7 +169,7 @@ public bool Stop() { if (_isRunning == false) { - Log.Debug("Not running. returning"); + _logger?.LogDebug("Not running. returning"); return true; } diff --git a/src/Libraries/ACATCore/Utility/TypeLoader/TypeLoader.cs b/src/Libraries/ACATCore/Utility/TypeLoader/TypeLoader.cs index 3ef5533d..11d611f4 100644 --- a/src/Libraries/ACATCore/Utility/TypeLoader/TypeLoader.cs +++ b/src/Libraries/ACATCore/Utility/TypeLoader/TypeLoader.cs @@ -10,7 +10,7 @@ namespace ACAT.Core.Utility.TypeLoader public class TypeLoader : ITypeLoader where TInterface : class, IPluginExtension { - private readonly ILogger> _logger; + private readonly ILogger> _logger = LogManager.GetLogger>(); private readonly Dictionary _typeCache = new(); public IReadOnlyDictionary LoadedTypes => _typeCache; diff --git a/src/Libraries/ACATCore/Utility/VerifyDigitalSignature.cs b/src/Libraries/ACATCore/Utility/VerifyDigitalSignature.cs index 6b856930..cbed93a5 100644 --- a/src/Libraries/ACATCore/Utility/VerifyDigitalSignature.cs +++ b/src/Libraries/ACATCore/Utility/VerifyDigitalSignature.cs @@ -9,11 +9,13 @@ using System.ComponentModel; using System.Runtime.InteropServices; using System.Security.Cryptography.Pkcs; +using Microsoft.Extensions.Logging; namespace ACAT.Core.Utility { public class VerifyDigitalSignature { + private static ILogger _logger => LogManager.GetLogger(); #if ENABLE_DIGITAL_VERIFICATION private static string[] _dllFiles = { @@ -77,7 +79,7 @@ public static void Verify(String fileName) int formatType = 0; const int ErrCertExpired = -2146762495; - Log.Debug("Verify digital signature for " + fileName); + _logger?.LogDebug("Verify digital signature for {FileName}", fileName); if (!CryptoInterop.CryptQueryObject( CryptoInterop.CERT_QUERY_OBJECT_FILE, @@ -93,14 +95,14 @@ public static void Verify(String fileName) ref context )) { - Log.Debug((new Win32Exception(Marshal.GetLastWin32Error())).Message); + _logger?.LogDebug("Crypto query failed: {Message}", (new Win32Exception(Marshal.GetLastWin32Error())).Message); throw new Win32Exception(Marshal.GetLastWin32Error()); } int data = 0; if (!CryptoInterop.CryptMsgGetParam(msgHandle, CryptoInterop.CMSG_ENCODED_MESSAGE, 0, null, ref data)) { - Log.Debug((new Win32Exception(Marshal.GetLastWin32Error())).Message); + _logger?.LogDebug("CryptMsgGetParam failed: {Message}", (new Win32Exception(Marshal.GetLastWin32Error())).Message); throw new Win32Exception(Marshal.GetLastWin32Error()); } @@ -111,13 +113,13 @@ ref context try { signedCms.CheckSignature(false); - Log.Debug("Signature check passed"); + _logger?.LogDebug("Signature check passed"); } catch (Exception e) { if (e.HResult != ErrCertExpired) { - Log.Exception(e); + _logger?.LogError(e, "Signature check failed"); throw (e); } } diff --git a/src/Libraries/ACATCore/Utility/WebSearch.cs b/src/Libraries/ACATCore/Utility/WebSearch.cs index 846dada9..4c26932c 100644 --- a/src/Libraries/ACATCore/Utility/WebSearch.cs +++ b/src/Libraries/ACATCore/Utility/WebSearch.cs @@ -5,6 +5,7 @@ // //////////////////////////////////////////////////////////////////////////// +using Microsoft.Extensions.Logging; using System; using System.Diagnostics; using System.Security.Permissions; @@ -20,6 +21,7 @@ namespace ACAT.Core.Utility /// public class WebSearch { + private static readonly ILogger _logger = LoggingConfiguration.CreateLogger(); /// /// URL to do a google search with "I'm feeling lucky" /// @@ -131,7 +133,7 @@ private Process launchURL(String url) } catch (Exception ex) { - Log.Exception("Could not launch URL using preferred browser. Trying Internet Explorer. " + ex); + _logger.LogError(ex, "Could not launch URL using preferred browser. Trying Internet Explorer"); try { @@ -139,7 +141,7 @@ private Process launchURL(String url) } catch (Exception ex1) { - Log.Exception("Could not launch URL using IE. " + ex1); + _logger.LogError(ex1, "Could not launch URL using IE"); } } diff --git a/src/Libraries/ACATCore/Utility/WindowActivityMonitor.cs b/src/Libraries/ACATCore/Utility/WindowActivityMonitor.cs index 74b3442d..2945bd80 100644 --- a/src/Libraries/ACATCore/Utility/WindowActivityMonitor.cs +++ b/src/Libraries/ACATCore/Utility/WindowActivityMonitor.cs @@ -46,6 +46,8 @@ public static bool Start() _form = new Form { Visible = false }; _form.Show(); _form.Visible = false; + // Force handle creation to ensure Invoke/BeginInvoke can be called + var handle = _form.Handle; } if (_forgroundHook == IntPtr.Zero) @@ -76,12 +78,21 @@ public static bool Start() if (_heartbeatTimer == null) { - _form.Invoke(new MethodInvoker(() => + if (_form.InvokeRequired && _form.IsHandleCreated) + { + _form.Invoke(new MethodInvoker(() => + { + _heartbeatTimer = new Timer { Interval = HeartbeatInterval }; + _heartbeatTimer.Tick += HeartbeatTick; + _heartbeatTimer.Start(); + })); + } + else { _heartbeatTimer = new Timer { Interval = HeartbeatInterval }; _heartbeatTimer.Tick += HeartbeatTick; _heartbeatTimer.Start(); - })); + } } Automation.AddAutomationFocusChangedEventHandler(OnAutomationFocusChanged); @@ -224,11 +235,14 @@ private static void HandleFocusOrWindowChange(WindowActivityMonitorInfo info) info.IsNewWindow = isNewWindow; info.IsNewFocusedElement = isNewElement; - // Marshal to UI thread - _form.BeginInvoke((MethodInvoker)(() => + // Marshal to UI thread - ensure form handle is created + if (_form != null && _form.IsHandleCreated) { - EvtFocusChanged?.Invoke(info); - })); + _form.BeginInvoke((MethodInvoker)(() => + { + EvtFocusChanged?.Invoke(info); + })); + } _currentHwnd = info.FgHwnd; _currentFocusedElement = info.FocusedElement; diff --git a/src/Libraries/ACATCore/Utility/Windows.cs b/src/Libraries/ACATCore/Utility/Windows.cs index 5140a476..7ee8ec5e 100644 --- a/src/Libraries/ACATCore/Utility/Windows.cs +++ b/src/Libraries/ACATCore/Utility/Windows.cs @@ -27,7 +27,7 @@ namespace ACAT.Core.Utility /// public class Windows { - private static ILogger _logger; + private static ILogger _logger => LogManager.GetLogger(); private const int GCL_HICON = -14; private const int GCL_HICONSM = -34; @@ -1672,14 +1672,14 @@ public static void SetWindowSizePercent(IntPtr handle, WindowPosition scannerPos } else { - _logger?.LogDebug(\"fgWnd is zero in SetWindowSizePercent\"); + _logger?.LogDebug("fgWnd is zero in SetWindowSizePercent"); } } /// /// Shows the child window, assigns parent as the owner /// This is just a helper function that takes care of - /// cross-thread invokations that would result in .NET + /// cross-thread invocations that would result in .NET /// exceptions. /// /// diff --git a/src/Libraries/ACATCore/Utility/XmlUtils.cs b/src/Libraries/ACATCore/Utility/XmlUtils.cs index 8a8c96ea..36d7879f 100644 --- a/src/Libraries/ACATCore/Utility/XmlUtils.cs +++ b/src/Libraries/ACATCore/Utility/XmlUtils.cs @@ -20,7 +20,7 @@ namespace ACAT.Core.Utility /// public class XmlUtils { - private static ILogger _logger; + private static ILogger _logger => LogManager.GetLogger(); private static readonly object _lock = new(); /// diff --git a/src/Libraries/ACATCore/WidgetManagement/Layout/LayoutAttribute.cs b/src/Libraries/ACATCore/WidgetManagement/Layout/LayoutAttribute.cs index c3257c4b..ad821085 100644 --- a/src/Libraries/ACATCore/WidgetManagement/Layout/LayoutAttribute.cs +++ b/src/Libraries/ACATCore/WidgetManagement/Layout/LayoutAttribute.cs @@ -5,8 +5,10 @@ // //////////////////////////////////////////////////////////////////////////// +using ACAT.Core.PanelManagement; using ACAT.Core.ThemeManagement; using ACAT.Core.Utility; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using System; using System.Collections; @@ -120,15 +122,32 @@ public Widget CreateWidget(Type classType, string widgetName) { _logger?.LogDebug("creating widget with name {WidgetName}", widgetName); - widget = (Widget)Activator.CreateInstance(classType, widgetName); + // Try to create instance using DI container first (if available) + if (Context.ServiceProvider != null) + { + try + { + widget = ActivatorUtilities.CreateInstance(Context.ServiceProvider, classType, widgetName) as Widget; + _logger?.LogDebug("Widget created with DI: {IsNull}", widget != null ? "Not Null" : "Null"); + } + catch + { + // DI creation failed, will try parameterless constructor + } + } - _logger?.LogDebug("Widget created: {IsNull}", widget != null ? "Not Null" : "Null"); + // Fall back to standard constructor + if (widget == null) + { + widget = (Widget)Activator.CreateInstance(classType, widgetName); + _logger?.LogDebug("Widget created (standard constructor): {IsNull}", widget != null ? "Not Null" : "Null"); + } widget?.SetLayout(this); } catch (Exception ex) { - _logger?.LogError(ex, ex.Message); + _logger?.LogError(ex, "Constructor on type '{ClassType}' not found.", classType.FullName); } return widget; @@ -148,15 +167,32 @@ public Widget CreateWidget(Type classType, Control uiControl) { _logger?.LogDebug("creating widget {ClassType}", classType); - widget = (Widget)Activator.CreateInstance(classType, uiControl); + // Try to create instance using DI container first (if available) + if (Context.ServiceProvider != null) + { + try + { + widget = ActivatorUtilities.CreateInstance(Context.ServiceProvider, classType, uiControl) as Widget; + _logger?.LogDebug("Widget created with DI: {IsNull}", widget != null ? "Not Null" : "Null"); + } + catch + { + // DI creation failed, will try standard constructor + } + } - _logger?.LogDebug("Widget created: {IsNull}", widget != null ? "Not Null" : "Null"); + // Fall back to standard constructor + if (widget == null) + { + widget = (Widget)Activator.CreateInstance(classType, uiControl); + _logger?.LogDebug("Widget created (standard constructor): {IsNull}", widget != null ? "Not Null" : "Null"); + } widget?.SetLayout(layout: this); } catch (Exception ex) { - _logger?.LogError(ex, ex.Message); + _logger?.LogError(ex, "Constructor on type '{ClassType}' not found.", classType.FullName); } return widget; @@ -277,7 +313,7 @@ private Widget createWidget(XmlNode node) } catch (Exception ex) { - Log.Exception(ex); + _logger?.LogError(ex, "Failed to instantiate widget: {WidgetName}, class: {WidgetClass}", widgetName, widgetClass); widget = null; } diff --git a/src/Libraries/ACATCore/WidgetManagement/Widget.cs b/src/Libraries/ACATCore/WidgetManagement/Widget.cs index c3ec6df9..54a2d4b0 100644 --- a/src/Libraries/ACATCore/WidgetManagement/Widget.cs +++ b/src/Libraries/ACATCore/WidgetManagement/Widget.cs @@ -786,7 +786,7 @@ public virtual void Actuate(bool repeatActuate = false) /// The .NET UI Control public void AddChild(Control control) { - AddChild(new Widget(control)); + AddChild(new Widget(control, _logger) { }); } /// @@ -851,7 +851,7 @@ public virtual bool CanAddForAnimation() } } } - //Log.Debug("WidgetName: " + Name + ", retVal : " + retVal); + _logger?.LogTrace("CanAddForAnimation: WidgetName={Name}, result={Result}", Name, retVal); return retVal; } @@ -1178,7 +1178,7 @@ protected virtual void Dispose(bool disposing) // Check to see if Dispose has already been called. if (!_disposed) { - _logger.LogTrace(""); + _logger?.LogTrace(""); if (disposing) { diff --git a/src/Libraries/ACATCore/WidgetManagement/WidgetManager.cs b/src/Libraries/ACATCore/WidgetManagement/WidgetManager.cs index 73966f9c..bc69c799 100644 --- a/src/Libraries/ACATCore/WidgetManagement/WidgetManager.cs +++ b/src/Libraries/ACATCore/WidgetManagement/WidgetManager.cs @@ -32,6 +32,7 @@ namespace ACAT.Core.WidgetManagement public class WidgetManager : IDisposable { private readonly ILogger _logger; + private static readonly ILogger _staticLogger = LoggingConfiguration.CreateLogger(); /// /// Holds the types of all classes in the executing assembly that @@ -68,8 +69,8 @@ public WidgetManager(Control control, ILogger logger) { _logger = logger; - _widgetAttributes = new WidgetAttributes(logger); - _layout = new LayoutAttribute(logger); + _widgetAttributes = new WidgetAttributes(LoggingConfiguration.CreateLogger()); + _layout = new LayoutAttribute(LoggingConfiguration.CreateLogger()); _rootWidget = new Widget(control, null); _logger.LogDebug("control name is {Name}", control.Name); @@ -130,7 +131,7 @@ public static Type GetWidgetType(String widgetTypeName) } catch (Exception ex) { - _logger.LogError(ex, "Could not find widgettype {WidgetTypeName}", widgetTypeName); + _staticLogger.LogError(ex, "Could not find widgettype {WidgetTypeName}", widgetTypeName); } return retVal; @@ -265,7 +266,7 @@ private static bool loadTypesFromAssembly(Assembly assembly) } catch (Exception ex) { - _logger.LogError(ex, ex.Message); + _staticLogger.LogError(ex, ex.Message); retVal = false; } @@ -304,7 +305,7 @@ private static void loadWidgetTypeCollection(IEnumerable extensionDirs) } else { - Log.Error("Extension directory does not exist: " + extensionDir); + _staticLogger.LogError("Extension directory does not exist: {ExtensionDir}", extensionDir); } } @@ -338,19 +339,19 @@ private static void onDllFound(String dllName) { try { - Log.Debug("Found dll " + dllName); + _staticLogger.LogDebug("Found dll {DllName}", dllName); loadTypesFromAssembly(Assembly.LoadFile(dllName)); } catch (Exception ex) { - Log.Exception("Could get types from assembly " + dllName + ". Exception : " + ex); + _staticLogger.LogError(ex, "Could get types from assembly {DllName}", dllName); if (ex is ReflectionTypeLoadException) { var typeLoadException = (ReflectionTypeLoadException)ex; var exceptions = typeLoadException.LoaderExceptions; foreach (var e in exceptions) { - Log.Debug("Loader exception: " + e); + _staticLogger.LogDebug("Loader exception: {Exception}", e); } } } diff --git a/src/Libraries/ACATCore/Widgets/BoxWidget.cs b/src/Libraries/ACATCore/Widgets/BoxWidget.cs index 0e4b6029..222f4ba5 100644 --- a/src/Libraries/ACATCore/Widgets/BoxWidget.cs +++ b/src/Libraries/ACATCore/Widgets/BoxWidget.cs @@ -5,6 +5,7 @@ // //////////////////////////////////////////////////////////////////////////// +using ACAT.Core.Utility; using ACAT.Core.WidgetManagement; using ACAT.Core.WidgetManagement.Interfaces; using System.Windows.Forms; @@ -21,7 +22,7 @@ public class BoxWidget : Widget, IBoxWidget /// /// the inner .NET Control for the widget public BoxWidget(Control uiControl) - : base(uiControl) + : base(uiControl, LoggingConfiguration.CreateLogger()) { } } diff --git a/src/Libraries/ACATCore/Widgets/CheckBoxWidget.cs b/src/Libraries/ACATCore/Widgets/CheckBoxWidget.cs index 9a0a3a7c..d74d1b77 100644 --- a/src/Libraries/ACATCore/Widgets/CheckBoxWidget.cs +++ b/src/Libraries/ACATCore/Widgets/CheckBoxWidget.cs @@ -81,9 +81,9 @@ public class CheckBoxWidget : LabelWidget /// /// the inner .NET Control for the widget public CheckBoxWidget(Control uiControl, ILogger logger = null) - : base(uiControl) + : base(uiControl, logger ?? LoggingConfiguration.CreateLogger()) { - _logger = logger ?? LoggerFactory.Create(builder => builder.AddConsole()).CreateLogger(); + _logger = logger ?? LoggingConfiguration.CreateLogger(); EvtActuated += CheckBoxWidget_EvtActuated; SetToggleState(_toggleState); } diff --git a/src/Libraries/ACATCore/Widgets/ContextMenuIcon.cs b/src/Libraries/ACATCore/Widgets/ContextMenuIcon.cs index 52f4f504..5ed59165 100644 --- a/src/Libraries/ACATCore/Widgets/ContextMenuIcon.cs +++ b/src/Libraries/ACATCore/Widgets/ContextMenuIcon.cs @@ -6,6 +6,7 @@ //////////////////////////////////////////////////////////////////////////// using ACAT.Core.ThemeManagement; +using ACAT.Core.Utility; using System.Windows.Forms; namespace ACAT.Core.Widgets @@ -20,7 +21,7 @@ public class ContextMenuIcon : ScannerButtonBase /// /// the inner .NET Control for the widget public ContextMenuIcon(Control uiControl) - : base(uiControl) + : base(uiControl, LoggingConfiguration.CreateLogger()) { Colors = ThemeManager.Instance.ActiveTheme.Colors.GetColorScheme(ColorSchemes.ContextMenuIconSchemeName); DisabledButtonColors = ThemeManager.Instance.ActiveTheme.Colors.GetColorScheme(ColorSchemes.DisabledContextMenuIconSchemeName); diff --git a/src/Libraries/ACATCore/Widgets/ContextMenuText.cs b/src/Libraries/ACATCore/Widgets/ContextMenuText.cs index 7b1d3006..78ccf596 100644 --- a/src/Libraries/ACATCore/Widgets/ContextMenuText.cs +++ b/src/Libraries/ACATCore/Widgets/ContextMenuText.cs @@ -6,6 +6,7 @@ //////////////////////////////////////////////////////////////////////////// using ACAT.Core.ThemeManagement; +using ACAT.Core.Utility; using System.Windows.Forms; namespace ACAT.Core.Widgets @@ -20,7 +21,7 @@ public class ContextMenuText : ScannerButtonBase /// /// the inner .NET Control for the widget public ContextMenuText(Control uiControl) - : base(uiControl) + : base(uiControl, LoggingConfiguration.CreateLogger()) { Colors = ThemeManager.Instance.ActiveTheme.Colors.GetColorScheme(ColorSchemes.ContextMenuTextSchemeName); DisabledButtonColors = ThemeManager.Instance.ActiveTheme.Colors.GetColorScheme(ColorSchemes.DisabledContextMenuTextSchemeName); diff --git a/src/Libraries/ACATCore/Widgets/LetterListItemWidget.cs b/src/Libraries/ACATCore/Widgets/LetterListItemWidget.cs index f8776e5b..53a3590c 100644 --- a/src/Libraries/ACATCore/Widgets/LetterListItemWidget.cs +++ b/src/Libraries/ACATCore/Widgets/LetterListItemWidget.cs @@ -26,9 +26,9 @@ public class LetterListItemWidget : ScannerButtonBase /// /// the inner .NET Control for the widget public LetterListItemWidget(Control control, ILogger logger = null) - : base(control) + : base(control, logger ?? LoggingConfiguration.CreateLogger()) { - _logger = logger ?? LoggerFactory.Create(builder => builder.AddConsole()).CreateLogger(); + _logger = logger ?? LoggingConfiguration.CreateLogger(); if (button != null) { button.AutoEllipsis = true; diff --git a/src/Libraries/ACATCore/Widgets/LetterListWidget.cs b/src/Libraries/ACATCore/Widgets/LetterListWidget.cs index 81840582..85052482 100644 --- a/src/Libraries/ACATCore/Widgets/LetterListWidget.cs +++ b/src/Libraries/ACATCore/Widgets/LetterListWidget.cs @@ -5,6 +5,7 @@ // //////////////////////////////////////////////////////////////////////////// +using ACAT.Core.Utility; using ACAT.Core.WidgetManagement; using System; using System.Windows.Forms; @@ -24,7 +25,7 @@ public class LetterListWidget : Widget /// /// the inner .NET Control for the widget public LetterListWidget(Control control) - : base(control) + : base(control, LoggingConfiguration.CreateLogger()) { AddForAnimation = false; } diff --git a/src/Libraries/ACATCore/Widgets/RowWidget.cs b/src/Libraries/ACATCore/Widgets/RowWidget.cs index 88222332..4af07487 100644 --- a/src/Libraries/ACATCore/Widgets/RowWidget.cs +++ b/src/Libraries/ACATCore/Widgets/RowWidget.cs @@ -24,7 +24,7 @@ public class RowWidget : Widget, IRowWidget /// /// the inner .NET Control for the widget public RowWidget(Control control) - : base(control) + : base(control, LoggingConfiguration.CreateLogger()) { } diff --git a/src/Libraries/ACATCore/Widgets/ScannerButton.cs b/src/Libraries/ACATCore/Widgets/ScannerButton.cs index 21d397d0..a9300456 100644 --- a/src/Libraries/ACATCore/Widgets/ScannerButton.cs +++ b/src/Libraries/ACATCore/Widgets/ScannerButton.cs @@ -21,7 +21,7 @@ public class ScannerButton : ScannerButtonBase /// /// the inner .NET Control for the widget public ScannerButton(Control uiControl) - : base(uiControl) + : base(uiControl, LoggingConfiguration.CreateLogger()) { if (ThemeManager.Instance.ActiveTheme.Colors.Exists("ScannerButton")) { diff --git a/src/Libraries/ACATCore/Widgets/ScannerButtonSpaced.cs b/src/Libraries/ACATCore/Widgets/ScannerButtonSpaced.cs index 975a2eb8..8ed59bd1 100644 --- a/src/Libraries/ACATCore/Widgets/ScannerButtonSpaced.cs +++ b/src/Libraries/ACATCore/Widgets/ScannerButtonSpaced.cs @@ -5,6 +5,7 @@ // //////////////////////////////////////////////////////////////////////////// +using ACAT.Core.Utility; using System.Windows.Forms; namespace ACAT.Core.Widgets @@ -19,7 +20,7 @@ public class ScannerButtonSpaced : ScannerButtonBase /// /// the inner .NET Control for the widget public ScannerButtonSpaced(Control uiControl) - : base(uiControl) + : base(uiControl, LoggingConfiguration.CreateLogger()) { } } diff --git a/src/Libraries/ACATCore/Widgets/ScannerButtonToggle.cs b/src/Libraries/ACATCore/Widgets/ScannerButtonToggle.cs index 603fa6e3..125a5333 100644 --- a/src/Libraries/ACATCore/Widgets/ScannerButtonToggle.cs +++ b/src/Libraries/ACATCore/Widgets/ScannerButtonToggle.cs @@ -33,7 +33,7 @@ public class ScannerButtonToggle : ScannerButtonBase, IToggleButtonWidget /// /// the inner .NET Control for the widget public ScannerButtonToggle(Control uiControl) - : base(uiControl) + : base(uiControl, LoggingConfiguration.CreateLogger()) { if (ThemeManager.Instance.ActiveTheme.Colors.Exists("ScannerButton")) { diff --git a/src/Libraries/ACATCore/Widgets/SentenceListWidget.cs b/src/Libraries/ACATCore/Widgets/SentenceListWidget.cs index 40512daa..4215e9c3 100644 --- a/src/Libraries/ACATCore/Widgets/SentenceListWidget.cs +++ b/src/Libraries/ACATCore/Widgets/SentenceListWidget.cs @@ -5,6 +5,7 @@ // //////////////////////////////////////////////////////////////////////////// +using ACAT.Core.Utility; using ACAT.Core.WidgetManagement; using System; using System.Windows.Forms; @@ -24,7 +25,7 @@ public class SentenceListWidget : Widget /// /// the inner .NET Control for the widget public SentenceListWidget(Control control) - : base(control) + : base(control, LoggingConfiguration.CreateLogger()) { AddForAnimation = false; } diff --git a/src/Libraries/ACATCore/Widgets/WinControlWidget.cs b/src/Libraries/ACATCore/Widgets/WinControlWidget.cs index ef8b8c14..118a7752 100644 --- a/src/Libraries/ACATCore/Widgets/WinControlWidget.cs +++ b/src/Libraries/ACATCore/Widgets/WinControlWidget.cs @@ -5,6 +5,7 @@ // //////////////////////////////////////////////////////////////////////////// +using ACAT.Core.Utility; using ACAT.Core.WidgetManagement; using System; using System.Windows.Forms; @@ -18,7 +19,7 @@ namespace ACAT.Core.Widgets public class WinControlWidget : Widget { public WinControlWidget(Control uiControl) - : base(uiControl) + : base(uiControl, LoggingConfiguration.CreateLogger()) { } diff --git a/src/Libraries/ACATCore/Widgets/WordListWidget.cs b/src/Libraries/ACATCore/Widgets/WordListWidget.cs index 08d9d4fb..ef918e3a 100644 --- a/src/Libraries/ACATCore/Widgets/WordListWidget.cs +++ b/src/Libraries/ACATCore/Widgets/WordListWidget.cs @@ -5,6 +5,7 @@ // //////////////////////////////////////////////////////////////////////////// +using ACAT.Core.Utility; using ACAT.Core.WidgetManagement; using System; using System.Windows.Forms; @@ -24,7 +25,7 @@ public class WordListWidget : Widget /// /// the inner .NET Control for the widget public WordListWidget(Control control) - : base(control) + : base(control, LoggingConfiguration.CreateLogger()) { AddForAnimation = false; } diff --git a/src/Libraries/ACATCore/WordPredictorManagement/WordPredictionManager.cs b/src/Libraries/ACATCore/WordPredictorManagement/WordPredictionManager.cs index 261a7f4b..5be156e0 100644 --- a/src/Libraries/ACATCore/WordPredictorManagement/WordPredictionManager.cs +++ b/src/Libraries/ACATCore/WordPredictorManagement/WordPredictionManager.cs @@ -11,6 +11,7 @@ using ACAT.Core.PreferencesManagement; using ACAT.Core.Utility; using ACAT.Core.WordPredictorManagement.Interfaces; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; @@ -37,9 +38,15 @@ public class WordPredictionManager : IDisposable public static string WordPredictorsRootName = ""; /// - /// Word prediction manager instance + /// Word prediction manager instance - lazy initialized to get logger from DI container /// - private static readonly WordPredictionManager _instance = new(); + private static readonly Lazy _instance = new Lazy(() => + { + // Get logger from DI container if available, otherwise use LogManager + ILogger logger = Context.ServiceProvider?.GetService(typeof(ILogger)) as ILogger + ?? LogManager.GetLogger(); + return new WordPredictionManager(logger); + }); /// /// Current User's current profile directory @@ -70,9 +77,9 @@ public class WordPredictionManager : IDisposable /// Initializes and instance of the WordPredictionManager class. /// /// Logger instance - private WordPredictionManager(ILogger logger = null) + private WordPredictionManager(ILogger logger) { - _logger = logger; + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); AppDomain currentDomain = AppDomain.CurrentDomain; @@ -90,7 +97,7 @@ private WordPredictionManager(ILogger logger = null) /// public static WordPredictionManager Instance { - get { return _instance; } + get { return _instance.Value; } } public IEnumerable WordPredictorsList @@ -270,7 +277,7 @@ public bool LoadExtensions(IEnumerable extensionDirs) if (_wordPredictors == null) { - _wordPredictors = new WordPredictors(); + _wordPredictors = new WordPredictors(LoggingConfiguration.CreateLogger()); retVal = _wordPredictors.Load(extensionDirs); } @@ -391,7 +398,7 @@ protected virtual void Dispose(bool disposing) // Check to see if Dispose has already been called. if (!_disposed) { - _logger?.LogTrace(""); + _logger.LogTrace(""); Context.EvtCultureChanged -= Context_EvtCultureChanged; @@ -433,7 +440,15 @@ private bool createAndSetActiveWordPredictor(Type type, CultureInfo ci) try { - var wordPredictor = (IWordPredictor)Activator.CreateInstance(type); + // Use ExtensionInstantiator to create instance with proper dependency injection + var wordPredictor = ExtensionInstantiator.CreateExtensionInstance(Context.ServiceProvider, type, _logger) as IWordPredictor; + + if (wordPredictor == null) + { + _logger.LogError("Failed to create WordPredictor instance for type {Type}", type); + return false; + } + retVal = wordPredictor.Init(ci); if (retVal) { @@ -442,7 +457,7 @@ private bool createAndSetActiveWordPredictor(Type type, CultureInfo ci) } catch (Exception ex) { - _logger?.LogError(ex, "Unable to load WordPredictor {Type}, assembly: {Assembly}", type, type.Assembly.FullName); + _logger.LogError(ex, "Unable to load WordPredictor {Type}, assembly: {Assembly}", type, type.Assembly.FullName); retVal = false; } diff --git a/src/Libraries/ACATExtension/AppAgents/ACATApp/ACATAgentBase.cs b/src/Libraries/ACATExtension/AppAgents/ACATApp/ACATAgentBase.cs index d7ed14af..74de4a6c 100644 --- a/src/Libraries/ACATExtension/AppAgents/ACATApp/ACATAgentBase.cs +++ b/src/Libraries/ACATExtension/AppAgents/ACATApp/ACATAgentBase.cs @@ -19,8 +19,6 @@ namespace ACAT.Extension.AppAgents.ACATApp /// public class ACATAgentBase : AgentBase { - private readonly ILogger _logger; - /// /// Name of the executing assembly /// @@ -29,9 +27,8 @@ public class ACATAgentBase : AgentBase /// /// Initializes a new instance of the class. /// - public ACATAgentBase(ILogger logger) + public ACATAgentBase(ILogger logger) : base(logger) { - _logger = logger; _currentProcessName = Process.GetCurrentProcess().ProcessName.ToLower(); } @@ -58,8 +55,6 @@ public override void OnContextMenuRequest(WindowActivityMonitorInfo monitorInfo) /// set to true if handled public override void OnFocusChanged(WindowActivityMonitorInfo monitorInfo, ref bool handled) { - _logger.LogTrace(); - handled = true; } } diff --git a/src/Libraries/ACATExtension/AppAgents/DialogControlAgent/DialogControlAgentBase.cs b/src/Libraries/ACATExtension/AppAgents/DialogControlAgent/DialogControlAgentBase.cs index 66088c72..d368f2f5 100644 --- a/src/Libraries/ACATExtension/AppAgents/DialogControlAgent/DialogControlAgentBase.cs +++ b/src/Libraries/ACATExtension/AppAgents/DialogControlAgent/DialogControlAgentBase.cs @@ -22,10 +22,8 @@ namespace ACAT.Extension.AppAgents.DialogControlAgent /// public class DialogControlAgentBase : GenericAppAgentBase { - private readonly ILogger _logger; - /// - /// If set to true, the agent will autoswitch the + /// If set to true, the agent will auto switch the /// scanners depending on which element has focus. /// Eg: Alphabet scanner if an edit text window has focus, /// the contextual menu if the main document has focus @@ -37,9 +35,8 @@ public class DialogControlAgentBase : GenericAppAgentBase /// private IntPtr _prevHwnd = IntPtr.Zero; - public DialogControlAgentBase(ILogger logger) + public DialogControlAgentBase() { - _logger = logger; } /// diff --git a/src/Libraries/ACATExtension/AppAgents/Outlook/OutlookAgentBase.cs b/src/Libraries/ACATExtension/AppAgents/Outlook/OutlookAgentBase.cs index 17f44885..78816722 100644 --- a/src/Libraries/ACATExtension/AppAgents/Outlook/OutlookAgentBase.cs +++ b/src/Libraries/ACATExtension/AppAgents/Outlook/OutlookAgentBase.cs @@ -89,8 +89,6 @@ public enum OutlookWindowTypes /// public class OutlookAgentBase : GenericAppAgentBase { - private readonly ILogger _logger; - /// /// The window element (eg button, edit box) that has focus /// @@ -142,9 +140,8 @@ public class OutlookAgentBase : GenericAppAgentBase /// /// Initializes an instance of hte class /// - public OutlookAgentBase(ILogger logger) + public OutlookAgentBase() { - _logger = logger; outlookInspector = createOutlookInspector(); } diff --git a/src/Libraries/ACATExtension/AppAgents/WindowsExplorer/WindowsExplorerAgentBase.cs b/src/Libraries/ACATExtension/AppAgents/WindowsExplorer/WindowsExplorerAgentBase.cs index 440d0f2d..327ff1c0 100644 --- a/src/Libraries/ACATExtension/AppAgents/WindowsExplorer/WindowsExplorerAgentBase.cs +++ b/src/Libraries/ACATExtension/AppAgents/WindowsExplorer/WindowsExplorerAgentBase.cs @@ -39,10 +39,8 @@ namespace ACAT.Extension.AppAgents.WindowsExplorer /// public class WindowsExplorerAgentBase : GenericAppAgentBase { - private readonly ILogger _logger; - /// - /// If set to true, the agent will autoswitch the + /// If set to true, the agent will auto switch the /// scanners depending on which element has focus. /// Eg: Alphabet scanner if an edit text window has focus, /// the contextual menu if the main document has focus @@ -87,9 +85,8 @@ public override IEnumerable ProcessesSupported get { return new[] { new AgentProcessInfo(ExplorerProcessName) }; } } - public WindowsExplorerAgentBase(ILogger logger) + public WindowsExplorerAgentBase() { - _logger = logger; _logger.LogDebug("WindowsExplorerAgentBase Constructed"); //AgentName = "Windows Explorer Agent"; //AutoSwitchScanners = true; diff --git a/src/Libraries/ACATExtension/CommandHandlers/AppWindowManagementHandler.cs b/src/Libraries/ACATExtension/CommandHandlers/AppWindowManagementHandler.cs index 5c1e66fb..2cef3a4e 100644 --- a/src/Libraries/ACATExtension/CommandHandlers/AppWindowManagementHandler.cs +++ b/src/Libraries/ACATExtension/CommandHandlers/AppWindowManagementHandler.cs @@ -35,10 +35,10 @@ public class AppWindowManagementHandler : RunCommandHandler /// /// The command to be executed /// Logger instance - public AppWindowManagementHandler(String cmd, ILogger logger) + public AppWindowManagementHandler(String cmd, ILogger logger = null) : base(cmd) { - _logger = logger; + _logger = logger ?? LoggingConfiguration.CreateLogger(); } /// diff --git a/src/Libraries/ACATExtension/CommandHandlers/DocumentEditingHandler.cs b/src/Libraries/ACATExtension/CommandHandlers/DocumentEditingHandler.cs index 60132204..2a9ddbb6 100644 --- a/src/Libraries/ACATExtension/CommandHandlers/DocumentEditingHandler.cs +++ b/src/Libraries/ACATExtension/CommandHandlers/DocumentEditingHandler.cs @@ -29,10 +29,10 @@ public class DocumentEditingHandler : RunCommandHandler /// /// The command to be executed /// Logger instance - public DocumentEditingHandler(String cmd, ILogger logger) + public DocumentEditingHandler(String cmd, ILogger logger = null) : base(cmd) { - _logger = logger; + _logger = logger ?? LoggingConfiguration.CreateLogger(); } /// diff --git a/src/Libraries/ACATExtension/CommandHandlers/FunctionKeyHandler.cs b/src/Libraries/ACATExtension/CommandHandlers/FunctionKeyHandler.cs index cfccf524..a94212c5 100644 --- a/src/Libraries/ACATExtension/CommandHandlers/FunctionKeyHandler.cs +++ b/src/Libraries/ACATExtension/CommandHandlers/FunctionKeyHandler.cs @@ -29,10 +29,10 @@ public class FunctionKeyHandler : RunCommandHandler /// /// The command to be executed /// Logger instance - public FunctionKeyHandler(String cmd, ILogger logger) + public FunctionKeyHandler(String cmd, ILogger logger = null) : base(cmd) { - _logger = logger; + _logger = logger ?? LoggingConfiguration.CreateLogger(); } /// diff --git a/src/Libraries/ACATExtension/CommandHandlers/GoBackHandler.cs b/src/Libraries/ACATExtension/CommandHandlers/GoBackHandler.cs index 60c17b41..90dc9499 100644 --- a/src/Libraries/ACATExtension/CommandHandlers/GoBackHandler.cs +++ b/src/Libraries/ACATExtension/CommandHandlers/GoBackHandler.cs @@ -31,10 +31,10 @@ public class GoBackHandler : RunCommandHandler /// /// The command to be executed /// Logger instance - public GoBackHandler(String cmd, ILogger logger) + public GoBackHandler(String cmd, ILogger logger = null) : base(cmd) { - _logger = logger; + _logger = logger ?? LoggingConfiguration.CreateLogger(); } /// diff --git a/src/Libraries/ACATExtension/CommandHandlers/NavigationHandler.cs b/src/Libraries/ACATExtension/CommandHandlers/NavigationHandler.cs index 220a39e1..5a76e38c 100644 --- a/src/Libraries/ACATExtension/CommandHandlers/NavigationHandler.cs +++ b/src/Libraries/ACATExtension/CommandHandlers/NavigationHandler.cs @@ -28,10 +28,10 @@ public class NavigationHandler : RunCommandHandler /// /// The command to be executed /// Logger instance - public NavigationHandler(String cmd, ILogger logger) + public NavigationHandler(String cmd, ILogger logger = null) : base(cmd) { - _logger = logger; + _logger = logger ?? LoggingConfiguration.CreateLogger(); } /// diff --git a/src/Libraries/ACATExtension/CommandHandlers/ShowDialogsHandler.cs b/src/Libraries/ACATExtension/CommandHandlers/ShowDialogsHandler.cs index db1239f4..6ec37961 100644 --- a/src/Libraries/ACATExtension/CommandHandlers/ShowDialogsHandler.cs +++ b/src/Libraries/ACATExtension/CommandHandlers/ShowDialogsHandler.cs @@ -32,10 +32,10 @@ public class ShowDialogsHandler : RunCommandHandler /// /// The command to be executed /// Logger instance - public ShowDialogsHandler(String cmd, ILogger logger) + public ShowDialogsHandler(String cmd, ILogger logger = null) : base(cmd) { - _logger = logger; + _logger = logger ?? LoggingConfiguration.CreateLogger(); } /// diff --git a/src/Libraries/ACATExtension/CommandHandlers/SwitchAppsHandler.cs b/src/Libraries/ACATExtension/CommandHandlers/SwitchAppsHandler.cs index 65d938cf..051e3193 100644 --- a/src/Libraries/ACATExtension/CommandHandlers/SwitchAppsHandler.cs +++ b/src/Libraries/ACATExtension/CommandHandlers/SwitchAppsHandler.cs @@ -50,7 +50,7 @@ public override bool Execute(ref bool handled) //DialogUtils.ShowTaskSwitcher(); throw new NotImplementedException(); - return true; + //return true; } } } \ No newline at end of file diff --git a/src/Libraries/ACATExtension/Common.cs b/src/Libraries/ACATExtension/Common.cs index 65e7779a..8de8b670 100644 --- a/src/Libraries/ACATExtension/Common.cs +++ b/src/Libraries/ACATExtension/Common.cs @@ -9,6 +9,7 @@ using ACAT.Core.PanelManagement.Utils; using ACAT.Core.UserControlManagement; using ACAT.Core.Utility; +using Microsoft.Extensions.Logging; using System; using System.Reflection; @@ -20,6 +21,8 @@ namespace ACAT.Extension /// public static class Common { + private static readonly ILogger _logger = LoggingConfiguration.CreateLogger("ACAT.Extension.Common"); + /// /// System-wide ACAT preference settings /// @@ -33,7 +36,7 @@ public static void Init() AppPreferences.DefaultScanTimingsConfigurePanelName = "ScanTimeAdjustScanner"; AppPreferences.DefaultTryoutPanelName = "DefaultTryoutScanner"; var assembly = Assembly.GetExecutingAssembly(); - Log.Debug("Assembly name: " + assembly.FullName); + _logger.LogDebug("Assembly name: {AssemblyName}", assembly.FullName); } /// diff --git a/src/Libraries/ACATExtension/UI/AlphabetScannerCommon.cs b/src/Libraries/ACATExtension/UI/AlphabetScannerCommon.cs index e591ebf6..045bfc93 100644 --- a/src/Libraries/ACATExtension/UI/AlphabetScannerCommon.cs +++ b/src/Libraries/ACATExtension/UI/AlphabetScannerCommon.cs @@ -266,8 +266,6 @@ public void OnClientSizeChanged() /// public void OnClosing(object sender, FormClosingEventArgs e) { - _logger.LogTrace(); - KeyStateTracker.EvtKeyStateChanged -= KeyStateTracker_EvtKeyStateChanged; _scannerCommon.OnClosing(); @@ -339,8 +337,6 @@ public void OnLoad(object sender, EventArgs e) /// public void OnPause() { - _logger.LogTrace(); - _scannerCommon.OnPause(); } @@ -350,8 +346,6 @@ public void OnPause() /// public void OnResume() { - _logger.LogTrace(); - _scannerCommon.OnResume(); refreshWordPredictionsAndSetCurrentWord(); @@ -377,7 +371,7 @@ public virtual void OnWidgetActuated(WidgetActuatedEventArgs e, ref bool handled CoreGlobals.Stopwatch1.Stop(); - Log.Debug("TimeElapsed 3 : " + CoreGlobals.Stopwatch1.ElapsedMilliseconds); + _logger.LogDebug("TimeElapsed 3 : {ElapsedMs}", CoreGlobals.Stopwatch1.ElapsedMilliseconds); handled = true; } @@ -397,7 +391,7 @@ public virtual void OnWidgetActuated(WidgetActuatedEventArgs e, ref bool handled CoreGlobals.Stopwatch1.Stop(); - Log.Debug("TimeElapsed 3 : " + CoreGlobals.Stopwatch1.ElapsedMilliseconds); + _logger.LogDebug("TimeElapsed 3 : {ElapsedMs}", CoreGlobals.Stopwatch1.ElapsedMilliseconds); handled = true; } @@ -496,8 +490,6 @@ protected virtual void Dispose(bool disposing) // Check to see if Dispose has already been called. if (!_disposed) { - _logger.LogTrace(); - if (disposing) { // dispose all managed resources. @@ -518,7 +510,6 @@ protected virtual void Dispose(bool disposing) /// event args private void AppAgent_EvtTextChanged(object sender, EventArgs e) { - _logger.LogTrace(); try { if (_form.Visible) @@ -599,7 +590,7 @@ private void refreshWordPredictionsAndSetCurrentWord() if (!tryRefreshWordPredictionsAndSetCurrentWord()) { - Log.Debug("AgentContextException. Retrying refreshing word prediction"); + _logger.LogDebug("AgentContextException. Retrying refreshing word prediction"); tryRefreshWordPredictionsAndSetCurrentWord(); } diff --git a/src/Libraries/ACATExtension/UI/DialogUtils.cs b/src/Libraries/ACATExtension/UI/DialogUtils.cs index b5415bcb..ffc8bb29 100644 --- a/src/Libraries/ACATExtension/UI/DialogUtils.cs +++ b/src/Libraries/ACATExtension/UI/DialogUtils.cs @@ -28,7 +28,7 @@ public class DialogUtils static DialogUtils() { - _logger = LoggerFactory.Create(builder => builder.AddConsole()).CreateLogger(); + _logger = LoggingConfiguration.CreateLogger(); } /// @@ -197,7 +197,7 @@ public static async void ShowAppLauncher() } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger.LogError(ex, "Error launching app"); } } diff --git a/src/Libraries/ACATExtension/UI/HorizontalStripScanner.cs b/src/Libraries/ACATExtension/UI/HorizontalStripScanner.cs index f407211f..dc111e5f 100644 --- a/src/Libraries/ACATExtension/UI/HorizontalStripScanner.cs +++ b/src/Libraries/ACATExtension/UI/HorizontalStripScanner.cs @@ -41,9 +41,10 @@ public partial class HorizontalStripScanner : HorizontalStripScannerBase /// The panel class of the contextual menu /// title of the contextual /// Logger instance - public HorizontalStripScanner(String panelClass, String panelTitle, ILogger logger) + public HorizontalStripScanner(String panelClass, String panelTitle, ILogger logger = null) : base(panelClass, panelTitle) { + _logger = logger ?? LogManager.GetLogger(); commandDispatcher = new Dispatcher(this); } diff --git a/src/Libraries/ACATExtension/UI/ScannerForms/GenericScannerForm.cs b/src/Libraries/ACATExtension/UI/ScannerForms/GenericScannerForm.cs index fe49e68c..3019d0d0 100644 --- a/src/Libraries/ACATExtension/UI/ScannerForms/GenericScannerForm.cs +++ b/src/Libraries/ACATExtension/UI/ScannerForms/GenericScannerForm.cs @@ -56,9 +56,9 @@ public ScannerCommon ScannerCommon protected string _panelClass; protected ScannerHelper _scannerHelper; private Label label1; - public GenericScannerForm(ILogger logger) + public GenericScannerForm(ILogger logger = null) { - _logger = logger; + _logger = logger ?? LoggingConfiguration.CreateLogger(); InitializeComponent(); SubscribeToEvents(); diff --git a/src/Libraries/ACATExtension/UI/ScannerHelper.cs b/src/Libraries/ACATExtension/UI/ScannerHelper.cs index 55b5736f..15a217c0 100644 --- a/src/Libraries/ACATExtension/UI/ScannerHelper.cs +++ b/src/Libraries/ACATExtension/UI/ScannerHelper.cs @@ -30,8 +30,8 @@ public class ScannerHelper /// the scanner object /// initialization arguments /// Logger instance - public ScannerHelper(IScannerPanel panel, StartupArg startupArg, ILogger logger) - { _logger = logger; DialogMode = startupArg.DialogMode; + public ScannerHelper(IScannerPanel panel, StartupArg startupArg, ILogger logger = null) + { _logger = logger ?? LoggingConfiguration.CreateLogger(); DialogMode = startupArg.DialogMode; AppDomain currentDomain = AppDomain.CurrentDomain; currentDomain.AssemblyResolve += currentDomain_AssemblyResolve; diff --git a/src/Libraries/ACATExtension/UI/UserControlWordPredictionCommon.cs b/src/Libraries/ACATExtension/UI/UserControlWordPredictionCommon.cs index 753c8f12..3f6a10ab 100644 --- a/src/Libraries/ACATExtension/UI/UserControlWordPredictionCommon.cs +++ b/src/Libraries/ACATExtension/UI/UserControlWordPredictionCommon.cs @@ -78,7 +78,14 @@ public class UserControlWordPredictionCommon : IDisposable /// public UserControlWordPredictionCommon(IUserControl userControl, TextController textController, IScannerPanel scannerPanel, PredictionTypes[] predictionTypes, ILogger logger) { - _logger = logger; + if (logger == null) + { + _logger = LoggingConfiguration.CreateLogger(); + } + else + { + _logger = logger; + } _form = scannerPanel.Form; _textController = textController; _predictionTypes = predictionTypes; @@ -141,7 +148,6 @@ public bool Initialize(Widget rootWidget) /// public void OnClosing(object sender, FormClosingEventArgs e) { - _logger.LogTrace(); } /// @@ -186,23 +192,12 @@ public void OnLoad() refreshWordPredictionsAndSetCurrentWord(); } - /// - /// Pause the application. Call this in the OnPause - /// function in the Alphabet scanner. - /// - public void OnPause() - { - _logger.LogTrace(); - } - /// /// Resumes the application. Call this in the OnResume /// function in the Alphabet scanner. /// public void OnResume() { - _logger.LogTrace(); - refreshWordPredictionsAndSetCurrentWord(); } @@ -226,7 +221,7 @@ public virtual void OnWidgetActuated(WidgetActuatedEventArgs e, ref bool handled CoreGlobals.Stopwatch1.Stop(); - Log.Debug("TimeElapsed 3 : " + CoreGlobals.Stopwatch1.ElapsedMilliseconds); + _logger?.LogDebug("TimeElapsed 3 : {ElapsedMs}ms", CoreGlobals.Stopwatch1.ElapsedMilliseconds); handled = true; } @@ -246,7 +241,7 @@ public virtual void OnWidgetActuated(WidgetActuatedEventArgs e, ref bool handled CoreGlobals.Stopwatch1.Stop(); - Log.Debug("TimeElapsed 3 : " + CoreGlobals.Stopwatch1.ElapsedMilliseconds); + _logger?.LogDebug("TimeElapsed 3 : {ElapsedMs}ms", CoreGlobals.Stopwatch1.ElapsedMilliseconds); handled = true; } @@ -266,7 +261,7 @@ public virtual void OnWidgetActuated(WidgetActuatedEventArgs e, ref bool handled CoreGlobals.Stopwatch1.Stop(); - Log.Debug("TimeElapsed 3 : " + CoreGlobals.Stopwatch1.ElapsedMilliseconds); + _logger?.LogDebug("TimeElapsed 3 : {ElapsedMs}ms", CoreGlobals.Stopwatch1.ElapsedMilliseconds); handled = true; } @@ -285,8 +280,6 @@ protected virtual void Dispose(bool disposing) // Check to see if Dispose has already been called. if (!_disposed) { - _logger.LogTrace(); - if (disposing) { // dispose all managed resources. @@ -325,7 +318,6 @@ private void ActiveWordPredictor_EvtWordPredictionAsyncResponse(WordPredictionRe /// event args private void AppAgent_EvtTextChanged(object sender, EventArgs e) { - _logger.LogTrace(); try { if (_form.Visible) @@ -526,20 +518,20 @@ private void processWordPredictionResponse(WordPredictionResponse response) } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger?.LogError(ex, "Exception processing word prediction"); } predictedWordList = predictedWordsList1; predictedLettersList = predictedLettersList1; } catch (Exception ex) { - Log.Exception(ex.ToString()); + _logger?.LogError(ex, "Exception processing word prediction"); } - Log.Debug("predictedWordList count: " + predictedWordList.Count()); + _logger?.LogDebug("predictedWordList count: {Count}", predictedWordList.Count()); // check if the current word is a possessive word. If not, we need to create // a possessive version of the word and add it as the last word - // in the predicton list. + // in the prediction list. var possessiveWord = string.Empty; var wordAtCaret = response.Request.CurrentWord; // check if it is the same @@ -550,11 +542,15 @@ private void processWordPredictionResponse(WordPredictionResponse response) try { agentContext.TextAgent().GetCharAtCaret(out charAtCaret); - _logger.LogDebug("charAtCaret: [" + charAtCaret + "]"); - } - catch (InvalidAgentContextException ex) - { - _logger.LogError(ex, ex.Message); + _logger.LogDebug("charAtCaret: [" + charAtCaret + "]"); + } + catch (InvalidAgentContextException ex) + { + _logger?.LogError(ex, ex.Message); + } + } + + if (string.IsNullOrEmpty(wordAtCaret) || (charAtCaret == '\0' || charAtCaret == 0x0D || charAtCaret == 0x0A || TextUtils.IsPunctuationOrWhiteSpace(charAtCaret) || TextUtils.IsTerminatorOrWhiteSpace(charAtCaret))) diff --git a/src/temp_acattalk.txt b/src/temp_acattalk.txt new file mode 100644 index 00000000..9aa8a71e --- /dev/null +++ b/src/temp_acattalk.txt @@ -0,0 +1,254 @@ +//////////////////////////////////////////////////////////////////////////// +// +// Copyright 2013-2019; 2023 Intel Corporation +// SPDX-License-Identifier: Apache-2.0 +// +// +// Program.cs +// +// Main entry point into the program. Does onboarding, initializes all +// the extensions and displays the main UI +// +//////////////////////////////////////////////////////////////////////////// + +using ACAT.Applications; +using ACAT.Core.AgentManagement.Interfaces; +using ACAT.Core.Audit; +using ACAT.Core.PanelManagement; +using ACAT.Core.PanelManagement.Common; +using ACAT.Core.PanelManagement.Interfaces; +using ACAT.Core.UserManagement; +using ACAT.Core.Utility; +using ACAT.Extension; +using ACAT.Extension.CommandHandlers; +using ACATResources; +using Microsoft.Extensions.Logging; +using System; +using System.Windows.Forms; + +namespace ACATTalk +{ + /// + /// ACAT Talk is an application customized for conversations. + /// + internal static class Program + { + private static Splash splash = null; + private static ILogger _logger; + + /// + /// The main entry point for the application. + /// + [STAThread] + public static void Main(string[] args) + { + if (AppCommon.OtherInstancesRunning()) + { + return; + } + + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + + //if (!AppCommon.CheckFontsInstalled()) + //{ + // return; + //} + + CoreGlobals.AppId = "ACATTalk"; + CoreGlobals.ACATUserGuideFileName = "ACAT User Guide.pdf"; + FatalErrorHandler.EvtFatalError += CoreGlobals_EvtFatalError; + + FileUtils.LogAssemblyInfo(); + + AppCommon.LoadGlobalSettings(); + + AppCommon.SetUserName(); + AppCommon.SetProfileName(); + + bool freshInstallForUser = !UserManager.UserExists(UserManager.CurrentUser); + + if (!AppCommon.CreateUserAndProfile()) + { + return; + } + + if (!AppCommon.LoadUserPreferences()) + { + return; + } + if (!AppCommon.SetCulture()) + { + return; + } + + User32Interop.SetProcessDPIAware(); + + AppCommon.CheckDisplayScalingAndResolution(); + + Common.AppPreferences.AppName = "ACAT Talk"; + + // Initialize legacy logging system + Log.SetupListeners(); + + // Initialize modern logging infrastructure (ticket #3) + var modernLoggingFactory = LoggingConfiguration.CreateLoggerFactory(); + _logger = modernLoggingFactory.CreateLogger(typeof(Program)); + + _logger.LogDebug("ACAT Talk Application Launch"); + + AuditLog.Audit(new AuditEvent("Application", "start")); + + CommandDescriptors.Init(); + + Common.AppPreferences.PreferredPanelConfigNames = string.Empty; + + if (!AppCommon.DoOnboarding()) + { + return; + } + + splash = new Splash(2000); + splash.Show(StringResources.StartingACAT); + + Context.PreInit(); + Common.PreInit(); + Context.AppAgentMgr.EnableAppAgentContextSwitch = false; + + if (!Context.Init(Context.StartupFlags.Minimal | + Context.StartupFlags.TextToSpeech | + Context.StartupFlags.WordPrediction | + Context.StartupFlags.AgentManager | + Context.StartupFlags.SpellChecker | + Context.StartupFlags.WindowsActivityMonitor | + Context.StartupFlags.Abbreviations)) + { + splash.Close(); + + splash = null; + + ConfirmBoxOneOption.ShowDialog(Context.GetInitCompletionStatus(), "", StringResources.OK); + if (Context.IsInitFatal()) + { + return; + } + } + + Context.ShowTalkWindowOnStartup = false; + Context.AppAgentMgr.EnableContextualMenusForDialogs = false; + Context.AppAgentMgr.EnableContextualMenusForMenus = false; + Context.AppAgentMgr.DefaultAgentForContextSwitchDisable = Context.AppAgentMgr.NullAgent; + + splash?.Close(); + splash = null; + + if (!Context.PostInit()) + { + Context.Dispose(); + return; + } + + Common.Init(); + + Context.AppWindowPosition = Windows.WindowPosition.CenterScreen; + + AuditLog.Audit(new AuditEvent("Application", "Initialiation complete")); + + try + { + Context.AppActuatorManager.ShowTryoutDialog(true); + + showTalkInterfaceDescription(); + + var startupArg = new StartupArg("TalkApplicationScanner") + { + QuitAppOnFormClose = false + }; + + var form = PanelManager.Instance.CreatePanel("TalkApplicationScanner", startupArg); + if (form != null) + { + // Add ad-hoc agent that will handle the form + IApplicationAgent agent = Context.AppAgentMgr.GetAgentByName("Talk Application Agent"); + if (agent == null) + { + MessageBox.Show("Could not find application agent for this application."); + return; + } + + Context.AppAgentMgr.AddAgent(form.Handle, agent); + Context.AppPanelManager.ShowDialog(form as IPanel); + } + else + { + MessageBox.Show(string.Format(StringResources.InvalidFormName, "TalkApplicationScanner")); + return; + } + + splash = new Splash(); + splash.Show(StringResources.ExitingACAT); + AuditLog.Audit(new AuditEvent("Application", "stop")); + + Context.Dispose(); + + Common.Uninit(); + + + splash?.Close(); + splash = null; + + _logger.LogDebug("ACATTalk Application shutdown"); + + Log.Close(); + modernLoggingFactory?.Dispose(); + } + catch (Exception ex) + { + MessageBox.Show(ex.ToString()); + modernLoggingFactory?.Dispose(); + } + + AppCommon.OnExit(); + } + + /// + /// A fatal error has occurred. Try and gracefully exit ACAT + /// + /// + private static void CoreGlobals_EvtFatalError(string reason) + { + splash?.Close(); + + + if (Context.AppPanelManager != null && Context.AppPanelManager.GetCurrentForm() != null && + Context.AppPanelManager.GetCurrentForm().PanelCommon != null && Context.AppPanelManager.GetCurrentForm().PanelCommon.RootWidget != null) + { + Context.AppPanelManager.GetCurrentForm().OnPause(); + var form = Context.AppPanelManager.GetCurrentForm().PanelCommon.RootWidget.UIControl as Form; + ConfirmBoxLargeSingleOption.ShowDialog(reason, "OK", form); + } + else + { + ConfirmBoxLargeSingleOption.ShowDialog(reason, "OK"); + } + + Application.ExitThread(); + + Environment.FailFast(reason); + } + + private static void showTalkInterfaceDescription() + { + if (!Common.AppPreferences.ShowTalkInterfaceDescOnStartup) + { + return; + } + + var form = PanelManager.Instance.CreatePanel("DefaultInterfaceScanner", "ACAT Talk Description"); + if (form != null) + { + Context.AppPanelManager.ShowDialog(form as IPanel); + } + } + } +} \ No newline at end of file