From 16c2b40679a57f23a9240af9f969034044e949a2 Mon Sep 17 00:00:00 2001 From: Halsafar <421822+halsafar@users.noreply.github.com> Date: Sat, 19 Feb 2022 15:03:54 -0600 Subject: [PATCH] Remove popup console logger and use log4net. Add verbose logging setting. Logs to rolling file by default, 1MB, 2 files, 2MB total. --- TaskBarAppIdAdjuster/App.config | 27 +++++++ TaskBarAppIdAdjuster/NativeConsole.cs | 72 ------------------- TaskBarAppIdAdjuster/Program.cs | 17 ++--- .../Properties/AssemblyInfo.cs | 1 + TaskBarAppIdAdjuster/Settings.cs | 3 + .../TaskBarAppIdAdjuster.csproj | 6 +- TaskBarAppIdAdjuster/TaskBarService.cs | 40 +++++++---- TaskBarAppIdAdjuster/packages.config | 1 + 8 files changed, 68 insertions(+), 99 deletions(-) delete mode 100644 TaskBarAppIdAdjuster/NativeConsole.cs diff --git a/TaskBarAppIdAdjuster/App.config b/TaskBarAppIdAdjuster/App.config index 8e15646..4333d8a 100644 --- a/TaskBarAppIdAdjuster/App.config +++ b/TaskBarAppIdAdjuster/App.config @@ -1,6 +1,33 @@  + +
+ + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/TaskBarAppIdAdjuster/NativeConsole.cs b/TaskBarAppIdAdjuster/NativeConsole.cs deleted file mode 100644 index 140d011..0000000 --- a/TaskBarAppIdAdjuster/NativeConsole.cs +++ /dev/null @@ -1,72 +0,0 @@ -using Microsoft.Win32.SafeHandles; -using System; -using System.IO; -using System.Runtime.InteropServices; -using System.Text; - -namespace TaskBarAppIdAdjuster -{ - /// - /// Handle setting up some of the native methods required to bind to an open console versus the debug-output window in VS. - /// - public class NativeConsole - { - [DllImport("kernel32.dll", - EntryPoint = "GetStdHandle", - SetLastError = true, - CharSet = CharSet.Auto, - CallingConvention = CallingConvention.StdCall)] - private static extern IntPtr GetStdHandle(int nStdHandle); - - [DllImport("kernel32.dll", - EntryPoint = "AllocConsole", - SetLastError = true, - CharSet = CharSet.Auto, - CallingConvention = CallingConvention.StdCall)] - private static extern int AllocConsole(); - - [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)] - static extern bool FreeConsole(); - - [DllImport("kernel32.dll")] - static extern IntPtr GetConsoleWindow(); - - private const int STD_OUTPUT_HANDLE = -11; - private const int MY_CODE_PAGE = 437; - - - - /// - /// Open a console window, bind stdout to it. - /// Remove the window chrome 'X' button to prevent closing. - /// - public static void OpenConsole() - { - AllocConsole(); - - IntPtr stdHandle = GetStdHandle(STD_OUTPUT_HANDLE); - SafeFileHandle safeFileHandle = new SafeFileHandle(stdHandle, true); - FileStream fileStream = new FileStream(safeFileHandle, FileAccess.Write); - Encoding encoding = System.Text.Encoding.GetEncoding(MY_CODE_PAGE); - StreamWriter standardOutput = new StreamWriter(fileStream, encoding); - standardOutput.AutoFlush = true; - Console.SetOut(standardOutput); - - // Prevent remove X in window chrome, closing the console this way closes the entire application - IntPtr consoleHwnd = GetConsoleWindow(); - var sm = NativeWindowHelpers.GetSystemMenu(consoleHwnd, false); - NativeWindowHelpers.EnableMenuItem(sm, NativeWindowHelpers.SC_CLOSE, NativeWindowHelpers.MF_BYCOMMAND | NativeWindowHelpers.MF_DISABLED); - - Console.WriteLine("Output is now redirected to the console."); - } - - /// - /// Close the console. - /// - public static void CloseConsole() - { - IntPtr consoleHwnd = GetConsoleWindow(); - NativeWindowHelpers.ShowWindow(consoleHwnd, NativeWindowHelpers.SW_HIDE); - } - } -} diff --git a/TaskBarAppIdAdjuster/Program.cs b/TaskBarAppIdAdjuster/Program.cs index 5d206ad..38170ae 100644 --- a/TaskBarAppIdAdjuster/Program.cs +++ b/TaskBarAppIdAdjuster/Program.cs @@ -1,4 +1,5 @@ using System; +using System.Diagnostics; using System.Windows.Forms; namespace TaskBarAppIdAdjuster @@ -11,6 +12,8 @@ public class TaskBarAppIdApplicationContext : ApplicationContext private Form1 _form = null; + private Process _logViewerProcess = null; + /// /// Constructor /// @@ -98,19 +101,7 @@ void OnToggleAutoStart(object sender, EventArgs e) void OnOpenLog(object sender, EventArgs e) { MenuItem item = sender as MenuItem; - if (item.Text == "Open Log") - { - NativeConsole.OpenConsole(); - - item.Text = "Close Log"; - } - else - { - NativeConsole.CloseConsole(); - - item.Text = "Open Log"; - } - + _logViewerProcess = Process.Start(@"TaskBarAppIdAdjuster.log"); } /// diff --git a/TaskBarAppIdAdjuster/Properties/AssemblyInfo.cs b/TaskBarAppIdAdjuster/Properties/AssemblyInfo.cs index 580e592..6478587 100644 --- a/TaskBarAppIdAdjuster/Properties/AssemblyInfo.cs +++ b/TaskBarAppIdAdjuster/Properties/AssemblyInfo.cs @@ -13,6 +13,7 @@ [assembly: AssemblyCopyright("Copyright © 2022")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] +[assembly: log4net.Config.XmlConfigurator(Watch = true)] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from diff --git a/TaskBarAppIdAdjuster/Settings.cs b/TaskBarAppIdAdjuster/Settings.cs index 2c26ffa..26f6132 100644 --- a/TaskBarAppIdAdjuster/Settings.cs +++ b/TaskBarAppIdAdjuster/Settings.cs @@ -44,6 +44,9 @@ public class Settings [DataMember] public bool AutoStart = false; + [DataMember] + public bool verboseLogging = false; + /// /// Constructor. /// diff --git a/TaskBarAppIdAdjuster/TaskBarAppIdAdjuster.csproj b/TaskBarAppIdAdjuster/TaskBarAppIdAdjuster.csproj index 35b2f30..4e3ec62 100644 --- a/TaskBarAppIdAdjuster/TaskBarAppIdAdjuster.csproj +++ b/TaskBarAppIdAdjuster/TaskBarAppIdAdjuster.csproj @@ -49,6 +49,9 @@ icons8-taskbar-48.ico + + packages\log4net.2.0.14\lib\net45\log4net.dll + packages\WindowsAPICodePack-Core.1.1.1\lib\Microsoft.WindowsAPICodePack.dll @@ -60,8 +63,10 @@ + + @@ -79,7 +84,6 @@ Form1.cs - diff --git a/TaskBarAppIdAdjuster/TaskBarService.cs b/TaskBarAppIdAdjuster/TaskBarService.cs index b2be38c..786211c 100644 --- a/TaskBarAppIdAdjuster/TaskBarService.cs +++ b/TaskBarAppIdAdjuster/TaskBarService.cs @@ -1,4 +1,6 @@ -using Microsoft.WindowsAPICodePack.Taskbar; +using log4net; +using log4net.Core; +using Microsoft.WindowsAPICodePack.Taskbar; using System; using System.Collections.Generic; using System.Diagnostics; @@ -29,6 +31,8 @@ public Settings Settings get { return _settings; } } + private static readonly ILog log = LogManager.GetLogger(typeof(TaskBarAppIdApplicationContext)); + /// /// Constructor /// @@ -48,6 +52,16 @@ public void RefreshConfig() { _settings = Settings.Load(); _settingLastWriteTime = File.GetLastWriteTimeUtc(Settings.ConfigPath()); + + // adjust log level + if (_settings.verboseLogging) + { + foreach (var r in LogManager.GetAllRepositories()) + { + ((log4net.Repository.Hierarchy.Hierarchy)r).Root.Level = Level.Debug; + ((log4net.Repository.Hierarchy.Hierarchy)r).RaiseConfigurationChanged(EventArgs.Empty); + } + } } else { @@ -55,7 +69,7 @@ public void RefreshConfig() long sub = (long)(curWriteTime - _settingLastWriteTime).TotalMilliseconds; if (sub > 0) { - Console.WriteLine("Detected change to settings file..."); + log.Info("Detected change to settings file..."); _settings = Settings.Load(); _settingLastWriteTime = curWriteTime; } @@ -63,7 +77,7 @@ public void RefreshConfig() } catch (Exception) { - Console.WriteLine("Failed to load config file, no actions will be taken until the file is fixed..."); + log.Error("Failed to load config file, no actions will be taken until the file is fixed..."); _settings = null; } } @@ -75,7 +89,7 @@ public void Start() { if (this._running) { - Console.WriteLine("Already running."); + log.Warn("Already running."); return; } @@ -94,7 +108,7 @@ public void Stop() { if (_thread == null || !_thread.IsAlive) { - Console.WriteLine("Thread is already stopped or was never started."); + log.Warn("Thread is already stopped or was never started."); return; } @@ -116,7 +130,7 @@ private void MainLoop() }; HandleProcesses(); - Console.WriteLine("Watching processes, press Ctrl+C to quit."); + log.Info("Starting to watch for processes to match..."); while (this._running) { RefreshConfig(); @@ -128,11 +142,11 @@ private void MainLoop() } catch (ThreadInterruptedException) { - Console.WriteLine("Sleep interrupted!"); + log.Debug("Sleep interrupted!"); } } - Console.WriteLine("Goodbye"); + log.Info("Goodbye"); } /// @@ -147,7 +161,7 @@ private void HandleProcesses() foreach (TaskSetting taskSetting in _settings.ApplicationsToRandomize) { - Console.WriteLine("Searching for any process matching the name: {0}", taskSetting.Name); + log.Debug($"Searching for any process matching the name: {taskSetting.Name}"); List processes = new List(); @@ -174,7 +188,7 @@ private void HandleProcesses() // Assume if main process has no window then the rest do not? if (process.MainWindowTitle.Length <= 0) { - Console.WriteLine("Process matched but has no Window Title, can safely assume no Window, not randomizing: " + process.ProcessName); + log.Debug($"Process matched but has no Window Title, can safely assume no Window, not randomizing: {process.ProcessName}"); continue; } @@ -193,7 +207,7 @@ private void HandleProcesses() if (_adjustedProcesses.Contains(identifier)) { - Console.WriteLine("Process {0}-{1} has already been adjusted.", taskSetting.Name, process.Id); + log.Debug($"Process {taskSetting.Name}-{process.Id} has already been adjusted."); continue; } @@ -201,13 +215,13 @@ private void HandleProcesses() if (taskSetting.Action == TaskAction.Ungroup) { Guid g = Guid.NewGuid(); - Console.WriteLine("Setting process {0} to random group {1}", process.ProcessName, g.ToString()); + log.Debug($"Setting process {process.ProcessName} to random group {g.ToString()}"); TaskbarManager.Instance.SetApplicationIdForSpecificWindow(handle, g.ToString()); } else if (taskSetting.Action == TaskAction.Group) { String groupId = "tbAdjusterGroup_" + taskSetting.Name; - Console.WriteLine("Setting process {0} to specific group {1}", process.ProcessName, groupId); + log.Debug($"Setting process {process.ProcessName} to specific group {groupId}"); TaskbarManager.Instance.SetApplicationIdForSpecificWindow(handle, groupId); } diff --git a/TaskBarAppIdAdjuster/packages.config b/TaskBarAppIdAdjuster/packages.config index 520c08b..62e4b54 100644 --- a/TaskBarAppIdAdjuster/packages.config +++ b/TaskBarAppIdAdjuster/packages.config @@ -1,5 +1,6 @@  +