Skip to content

Commit

Permalink
Retry failed log file writes up to 10 times
Browse files Browse the repository at this point in the history
  • Loading branch information
n00mkrad committed Nov 28, 2024
1 parent defff4f commit 075dd06
Showing 1 changed file with 27 additions and 17 deletions.
44 changes: 27 additions & 17 deletions CodeLegacy/IO/Logger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ public static void ShowNext()
Show(entry);
}

public static void Show(LogEntry entry)
public static void Show(LogEntry entry, bool logToFile = true)
{
if (string.IsNullOrWhiteSpace(entry.logMessage))
return;
Expand Down Expand Up @@ -87,20 +87,25 @@ public static void Show(LogEntry entry)
msg = msg.Replace("\n", Environment.NewLine);

if (!entry.hidden && textbox != null)
textbox.AppendText((textbox.Text.Length > 1 ? Environment.NewLine : "") + msg);
textbox.Invoke(() => textbox.AppendText((textbox.Text.Length > 1 ? Environment.NewLine : "") + msg));

if (entry.replaceLastLine)
{
textbox.Resume();
msg = "[REPL] " + msg;
msg = "[^] " + msg;
}

if (!entry.hidden)
msg = "[UI] " + msg;

LogToFile(msg, false, entry.filename);
if (logToFile)
{
LogToFile(msg, false, entry.filename);
}
}

private const int _maxLogFileWriteAttempts = 10;

public static void LogToFile(string logStr, bool noLineBreak, string filename)
{
if (string.IsNullOrWhiteSpace(filename))
Expand All @@ -113,20 +118,25 @@ public static void LogToFile(string logStr, bool noLineBreak, string filename)
logStr = logStr.Replace(Environment.NewLine, " ").TrimWhitespaces();
string time = DateTime.Now.ToString("MM-dd-yyyy HH:mm:ss");

try
{
string appendStr = noLineBreak ? $" {logStr}" : $"{Environment.NewLine}[{id.ToString().PadLeft(8, '0')}] [{time}]: {logStr}";
List<string> sessionLog = sessionLogs.ContainsKey(filename) ? sessionLogs[filename] : new List<string>();
sessionLog.Add(appendStr);
if (sessionLog.Count > maxLogSize)
sessionLog.RemoveAt(0);
sessionLogs[filename] = sessionLog;
File.AppendAllText(file, appendStr);
id++;
}
catch
string appendStr = noLineBreak ? $" {logStr}" : $"{Environment.NewLine}[{id.ToString().PadLeft(8, '0')}] [{time}]: {logStr}";
List<string> sessionLog = sessionLogs.ContainsKey(filename) ? sessionLogs[filename] : new List<string>();
sessionLog.Add(appendStr);
if (sessionLog.Count > maxLogSize)
sessionLog.RemoveAt(0);
sessionLogs[filename] = sessionLog;

for(int attempt = 0; attempt < _maxLogFileWriteAttempts; attempt++)
{
// this if fine, i forgot why
try
{
File.AppendAllText(file, appendStr);
id++;
break;
}
catch
{
Console.WriteLine($"Failed to write to log file (attempt {attempt+1}/{_maxLogFileWriteAttempts})");
}
}
}

Expand Down

0 comments on commit 075dd06

Please sign in to comment.