Add project files.
This commit is contained in:
50
Logging.cs
Normal file
50
Logging.cs
Normal file
@@ -0,0 +1,50 @@
|
||||
using System.Diagnostics;
|
||||
|
||||
namespace AiQ_GUI
|
||||
{
|
||||
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
|
||||
{
|
||||
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)
|
||||
{
|
||||
Debug.WriteLine($"Error logging message: {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user