Changed LogLevel applies immediately

Configured NLog so that the loglevel
UI changes happen straight away. Also
am using NLog to generate the user
messages while it's running.
This commit is contained in:
Terry MacDonald 2021-02-20 22:03:19 +13:00
parent 2959d5f280
commit bb37dc908a
5 changed files with 129 additions and 47 deletions

View File

@ -15,6 +15,7 @@ using System.Text.RegularExpressions;
using System.Drawing;
using DesktopNotifications;
using System.Runtime.Serialization;
using NLog.Config;
namespace DisplayMagician {
@ -81,13 +82,6 @@ namespace DisplayMagician {
}
}
var logfile = new NLog.Targets.FileTarget("logfile") {
FileName = AppLogFilename,
DeleteOldFileOnStartup = true
};
//var logconsole = new NLog.Targets.ConsoleTarget("logconsole");
// Load the program settings
AppProgramSettings = ProgramSettings.LoadSettings();
@ -114,7 +108,31 @@ namespace DisplayMagician {
logLevel = NLog.LogLevel.Info;
break;
}
config.AddRule(logLevel, NLog.LogLevel.Fatal, logfile);
// Create the log file target
var logfile = new NLog.Targets.FileTarget("logfile")
{
FileName = AppLogFilename,
DeleteOldFileOnStartup = true
};
// Create a logging rule to use the log file target
var loggingRule = new LoggingRule("LogToFile");
loggingRule.EnableLoggingForLevels(logLevel, NLog.LogLevel.Fatal);
loggingRule.Targets.Add(logfile);
config.LoggingRules.Add(loggingRule);
// Create the log console target
var logconsole = new NLog.Targets.ConsoleTarget()
{
Layout = "${date:format=HH\\:MM\\:ss} ${logger} ${message}",
};
// Create a logging rule to use the log console target
loggingRule = new LoggingRule("LogToConsole");
loggingRule.EnableLoggingForLevels(NLog.LogLevel.Info, NLog.LogLevel.Fatal);
loggingRule.Targets.Add(logconsole);
config.LoggingRules.Add(loggingRule);
// Apply config
NLog.LogManager.Configuration = config;

View File

@ -1,10 +1,7 @@
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NLog;
namespace DisplayMagician
@ -17,6 +14,7 @@ namespace DisplayMagician
private static bool _programSettingsLoaded = false;
// Other constants that are useful
private static string _programSettingsStorageJsonFileName = Path.Combine(Program.AppDataPath, $"Settings_{FileVersion.ToString(2)}.json");
private static readonly NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
#endregion
#region Instance Variables
@ -112,9 +110,19 @@ namespace DisplayMagician
{
ProgramSettings programSettings = null;
logger.Debug($"ProgramSettings/LoadSettings: Attempting to load ProgramSettings");
if (File.Exists(_programSettingsStorageJsonFileName))
{
var json = File.ReadAllText(_programSettingsStorageJsonFileName, Encoding.Unicode);
string json = "";
try {
logger.Debug($"ProgramSettings/LoadSettings: Found existing ProgramSettings file at {_programSettingsStorageJsonFileName} so loading text from it");
json = File.ReadAllText(_programSettingsStorageJsonFileName, Encoding.Unicode);
}
catch (Exception ex)
{
logger.Error(ex, $"ProgramSettings/LoadSettings: Tried to read the JSON file {_programSettingsStorageJsonFileName} to memory but File.ReadAllTextthrew an exception.");
}
if (!string.IsNullOrWhiteSpace(json))
{
@ -128,18 +136,15 @@ namespace DisplayMagician
TypeNameHandling = TypeNameHandling.Auto
});
}
catch (FileNotFoundException ex)
{
Console.WriteLine($"ProgramSettings/LoadSettings exception 1: {ex.Message}: {ex.StackTrace} - {ex.InnerException}");
}
catch (Exception ex)
{
Console.WriteLine($"Unable to load Program Settings JSON file {_programSettingsStorageJsonFileName}: " + ex.Message);
logger.Error(ex,$"ProgramSettings/LoadSettings: Tried to parse the JSON in the {_programSettingsStorageJsonFileName} but the JsonConvert threw an exception.");
}
}
}
else
{
logger.Info($"ProgramSettings/LoadSettings: No ProgramSettings file found. Creating new one at {_programSettingsStorageJsonFileName}");
programSettings = new ProgramSettings();
programSettings.SaveSettings();
}
@ -154,6 +159,8 @@ namespace DisplayMagician
public bool SaveSettings()
{
logger.Debug($"ProgramSettings/SaveSettings: Attempting to save the program settings to the {_programSettingsStorageJsonFileName}.");
try
{
var json = JsonConvert.SerializeObject(this, Formatting.Indented, new JsonSerializerSettings
@ -171,13 +178,9 @@ namespace DisplayMagician
return true;
}
}
catch (FileNotFoundException ex)
{
Console.WriteLine($"ProgramSettings/SaveSettings exception 1: {ex.Message}: {ex.StackTrace} - {ex.InnerException}");
}
catch (Exception ex)
{
Console.WriteLine($"Unable to save Program Settings JSON file {_programSettingsStorageJsonFileName}: " + ex.Message);
logger.Error(ex, $"ProgramSettings/SaveSettings: Exception attempting to save the program settings to {_programSettingsStorageJsonFileName}.");
}
return false;

View File

@ -376,7 +376,15 @@ namespace DisplayMagician
if (File.Exists(_shortcutStorageJsonFileName))
{
var json = File.ReadAllText(_shortcutStorageJsonFileName, Encoding.Unicode);
string json = "";
try
{
json = File.ReadAllText(_shortcutStorageJsonFileName, Encoding.Unicode);
}
catch (Exception ex)
{
logger.Error(ex, $"ShortcutRepository/LoadShortcuts: Tried to read the JSON file {_shortcutStorageJsonFileName} to memory but File.ReadAllTextthrew an exception.");
}
if (!string.IsNullOrWhiteSpace(json))
{

View File

@ -1,11 +1,6 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WK.Libraries.BootMeUpNS;
@ -15,11 +10,14 @@ namespace DisplayMagician.UIForms
public partial class SettingsForm : Form
{
//ProgramSettings mySettings = null;
private static readonly NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
private Dictionary<string, string> logLevelText = new Dictionary<string, string>();
public SettingsForm()
{
logger.Info($"SettingsForm/SettingsForm: Creating a SettingsForm UI Form");
InitializeComponent();
// Populate the LogLevel dictionary
@ -39,15 +37,27 @@ namespace DisplayMagician.UIForms
{
// start displaymagician when computer starts
if (Program.AppProgramSettings.StartOnBootUp)
{
cb_start_on_boot.Checked = true;
logger.Info($"SettingsForm/SettingsForm_Load: AppProgramSettings StartOnBootUp set to true");
}
else
{
cb_start_on_boot.Checked = false;
logger.Info($"SettingsForm/SettingsForm_Load: AppProgramSettings StartOnBootUp set to false");
}
// setup minimise on start
if (Program.AppProgramSettings.MinimiseOnStart)
{
cb_minimise_notification_area.Checked = true;
logger.Info($"SettingsForm/SettingsForm_Load: AppProgramSettings MinimiseOnStart set to true");
}
else
{
cb_minimise_notification_area.Checked = false;
logger.Info($"SettingsForm/SettingsForm_Load: AppProgramSettings MinimiseOnStart set to false");
}
// setup loglevel on start
@ -55,24 +65,31 @@ namespace DisplayMagician.UIForms
{
case "Trace":
cmb_loglevel.SelectedIndex = cmb_loglevel.FindStringExact(logLevelText["Trace"]);
logger.Info($"SettingsForm/SettingsForm_Load: AppProgramSettings LogLevel set to Trace");
break;
case "Debug":
cmb_loglevel.SelectedIndex = cmb_loglevel.FindStringExact(logLevelText["Debug"]);
logger.Info($"SettingsForm/SettingsForm_Load: AppProgramSettings LogLevel set to Debug");
break;
case "Info":
cmb_loglevel.SelectedIndex = cmb_loglevel.FindStringExact(logLevelText["Info"]);
logger.Info($"SettingsForm/SettingsForm_Load: AppProgramSettings LogLevel set to Info");
break;
case "Warn":
cmb_loglevel.SelectedIndex = cmb_loglevel.FindStringExact(logLevelText["Warn"]);
logger.Info($"SettingsForm/SettingsForm_Load: AppProgramSettings LogLevel set to Warn");
break;
case "Error":
cmb_loglevel.SelectedIndex = cmb_loglevel.FindStringExact(logLevelText["Error"]);
logger.Info($"SettingsForm/SettingsForm_Load: AppProgramSettings LogLevel set to Error");
break;
case "Fatal":
cmb_loglevel.SelectedIndex = cmb_loglevel.FindStringExact(logLevelText["Fatal"]);
logger.Info($"SettingsForm/SettingsForm_Load: AppProgramSettings LogLevel set to Fatal");
break;
default:
cmb_loglevel.SelectedIndex = cmb_loglevel.FindStringExact(logLevelText["Warn"]);
cmb_loglevel.SelectedIndex = cmb_loglevel.FindStringExact(logLevelText["Info"]);
logger.Info($"SettingsForm/SettingsForm_Load: AppProgramSettings LogLevel set to Info");
break;
}
@ -81,6 +98,7 @@ namespace DisplayMagician.UIForms
private void SettingsForm_FormClosing(object sender, FormClosingEventArgs e)
{
logger.Info($"SettingsForm/SettingsForm_Load: AppProgramSettings LogLevel set to Trace");
var bootMeUp = new BootMeUp
{
UseAlternativeOnFail = true,
@ -94,16 +112,25 @@ namespace DisplayMagician.UIForms
Program.AppProgramSettings.StartOnBootUp = true;
bootMeUp.Enabled = true;
if (!bootMeUp.Successful)
{
logger.Error($"SettingsForm/SettingsForm_FormClosing: Failed to set up DisplayMagician to start when Windows starts");
MessageBox.Show("There was an issue setting DisplayMagician to run when the computer starts. Please try launching DisplayMagician again as Admin to see if that helps.");
}
else
logger.Info($"SettingsForm/SettingsForm_FormClosing: Successfully set DisplayMagician to start when Windows starts");
}
else
{
Program.AppProgramSettings.StartOnBootUp = false;
bootMeUp.Enabled = false;
if (!bootMeUp.Successful)
{
logger.Error($"SettingsForm/SettingsForm_FormClosing: Failed to stop DisplayMagician from starting when Windows starts");
MessageBox.Show("There was an issue stopping DisplayMagician from running when the computer starts. Please try launching DisplayMagician again as Admin to see if that helps.");
}
else
logger.Info($"SettingsForm/SettingsForm_FormClosing: Successfully stopped DisplayMagician from starting when Windows starts");
}
// save minimise on close
@ -111,22 +138,53 @@ namespace DisplayMagician.UIForms
Program.AppProgramSettings.MinimiseOnStart = true;
else
Program.AppProgramSettings.MinimiseOnStart = false;
logger.Info($"SettingsForm/SettingsForm_FormClosing: Successfully saved MinimiseOnStart as {Program.AppProgramSettings.MinimiseOnStart}");
// save loglevel on close
// and make that log level live in NLog straight away
var config = NLog.LogManager.Configuration;
if (cmb_loglevel.SelectedItem.Equals(logLevelText["Trace"]))
{
Program.AppProgramSettings.LogLevel = "Trace";
config.FindRuleByName("LogToFile").EnableLoggingForLevel(NLog.LogLevel.Trace);
}
else if (cmb_loglevel.SelectedItem.Equals(logLevelText["Debug"]))
{
Program.AppProgramSettings.LogLevel = "Debug";
config.FindRuleByName("LogToFile").EnableLoggingForLevel(NLog.LogLevel.Debug);
}
else if (cmb_loglevel.SelectedItem.Equals(logLevelText["Info"]))
{
Program.AppProgramSettings.LogLevel = "Info";
config.FindRuleByName("LogToFile").EnableLoggingForLevel(NLog.LogLevel.Info);
}
else if (cmb_loglevel.SelectedItem.Equals(logLevelText["Warn"]))
{
Program.AppProgramSettings.LogLevel = "Warn";
config.FindRuleByName("LogToFile").EnableLoggingForLevel(NLog.LogLevel.Warn);
}
else if (cmb_loglevel.SelectedItem.Equals(logLevelText["Error"]))
{
Program.AppProgramSettings.LogLevel = "Error";
config.FindRuleByName("LogToFile").EnableLoggingForLevel(NLog.LogLevel.Error);
}
else if (cmb_loglevel.SelectedItem.Equals(logLevelText["Fatal"]))
{
Program.AppProgramSettings.LogLevel = "Fatal";
config.FindRuleByName("LogToFile").EnableLoggingForLevel(NLog.LogLevel.Fatal);
}
else
Program.AppProgramSettings.LogLevel = "Warn";
{
Program.AppProgramSettings.LogLevel = "Info";
config.FindRuleByName("LogToFile").EnableLoggingForLevel(NLog.LogLevel.Info);
}
// Use the NLog configuration with the LogLevel we just changed.
NLog.LogManager.Configuration = config;
logger.Info($"SettingsForm/SettingsForm_FormClosing: Successfully saved LogLevel as {Program.AppProgramSettings.LogLevel}");
}
private void btn_back_Click(object sender, EventArgs e)

View File

@ -523,7 +523,15 @@ namespace DisplayMagicianShared
if (File.Exists(_profileStorageJsonFileName))
{
var json = File.ReadAllText(_profileStorageJsonFileName, Encoding.Unicode);
string json = "";
try
{
json = File.ReadAllText(_profileStorageJsonFileName, Encoding.Unicode);
}
catch (Exception ex)
{
SharedLogger.logger.Error(ex, $"ProfileRepository/LoadProfiles: Tried to read the JSON file {_profileStorageJsonFileName} to memory but File.ReadAllTextthrew an exception.");
}
if (!string.IsNullOrWhiteSpace(json))
{
@ -578,19 +586,6 @@ namespace DisplayMagicianShared
// So we gotta start from scratch
SharedLogger.logger.Debug($"ProfileRepository/LoadProfiles: Couldn't find the {_profileStorageJsonFileName} profile JSON file that contains the Profiles");
UpdateActiveProfile();
/* // Create a new profile based on our current display settings
ProfileItem myCurrentProfile = new ProfileItem
{
Name = "Current Display Profile",
Paths = PathInfo.GetActivePaths().Select(info => new DisplayMagicianShared.Topology.Path(info)).ToArray()
};
_currentProfile = myCurrentProfile;
// Save a profile Icon to the profile
_currentProfile.ProfileIcon = new ProfileIcon(_currentProfile);
_currentProfile.ProfileBitmap = _currentProfile.ProfileIcon.ToBitmap(256, 256);*/
}
_profilesLoaded = true;
return true;