Files
AiQ_GUI/Logging.cs

56 lines
2.2 KiB
C#
Raw Normal View History

2025-12-02 12:59:40 +00:00
using System.Diagnostics;
2025-12-09 09:00:16 +00:00
using System.Security.Principal;
2025-12-02 12:59:40 +00:00
namespace AiQ_GUI
2025-09-02 15:32:24 +01:00
{
internal class Logging
{
public const string LogFileName = "AiQ_GUI_Log.log"; // Log file name
public const int maxFileSizeMB = 6 * 1024 * 1024; // 6mb max storage
public const int keepLines = 60000;
// Logs error message to the log file
public static async Task LogErrorMessage(string message, string? FileName = LogFileName)
{
await LogMessage("[ERROR] " + message, FileName);
}
// Logs warning message to the log file
public static async Task LogWarningMessage(string message, string? FileName = LogFileName)
{
await LogMessage("[WARNING] " + message, FileName);
}
// Method to log messages, defaults to main log file
public static async Task LogMessage(string message, string? FileName = LogFileName)
{
try
{
2025-12-09 09:00:16 +00:00
WindowsPrincipal wp = new(WindowsIdentity.GetCurrent()); // Log in a seperate file when admin
if (wp.IsInRole(WindowsBuiltInRole.Administrator))
FileName = FileName.Replace(".log", "_ADMIN.log");
2025-09-02 15:32:24 +01:00
string logFilePath = LDS.MAVPath + FileName;
FileInfo fi = new(logFilePath);
if (fi.Exists && fi.Length > maxFileSizeMB) // Check file size is under 2mb
{
List<string> allLines = (await File.ReadAllLinesAsync(logFilePath)).TakeLast(keepLines).ToList();
await File.WriteAllLinesAsync(logFilePath, allLines);
}
// If the message ends with a newline character, remove it
string trimmedMessage = message.EndsWith("\r\n") ? message[..^2] : (message.EndsWith('\n') ? message[..^1] : message);
// Append the new message to log
using StreamWriter writer = new(logFilePath, append: true);
await writer.WriteLineAsync($"{DateTime.Now}: {trimmedMessage}");
}
catch (Exception ex)
{
2025-12-02 11:02:24 +00:00
MessageBox.Show($"Error logging message: {ex.Message}");
2025-09-02 15:32:24 +01:00
}
}
}
}