krona-staff/apps/KronaStaffTerminal/Services/CrashLogService.cs

61 lines
1.9 KiB
C#

namespace KronaStaffTerminal.Services;
public static class CrashLogService
{
private const long MaximumLogSize = 1_048_576;
private static readonly object Gate = new();
private static readonly string LogDirectory = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData),
"Krona",
"StaffTerminal",
"logs");
public static void Write(Exception exception)
{
try
{
lock (Gate)
{
Directory.CreateDirectory(LogDirectory);
var path = Path.Combine(LogDirectory, "crash.log");
RotateIfNeeded(path);
var entry = $"[{DateTimeOffset.Now:O}]{Environment.NewLine}{exception}{Environment.NewLine}{Environment.NewLine}";
File.AppendAllText(path, entry);
}
}
catch
{
// Logging must never replace the original application failure.
}
}
public static void WriteDiagnostic(string message)
{
try
{
lock (Gate)
{
Directory.CreateDirectory(LogDirectory);
var path = Path.Combine(LogDirectory, "diagnostic.log");
RotateIfNeeded(path);
var entry = $"[{DateTimeOffset.Now:O}] {message}{Environment.NewLine}";
File.AppendAllText(path, entry);
}
}
catch
{
// Diagnostics must never throw
}
}
private static void RotateIfNeeded(string path)
{
if (!File.Exists(path) || new FileInfo(path).Length < MaximumLogSize) return;
for (var index = 3; index >= 1; index--)
{
var source = index == 1 ? path : $"{path}.{index - 1}";
var destination = $"{path}.{index}";
if (File.Exists(source)) File.Move(source, destination, true);
}
}
}