42 lines
1.4 KiB
C#
42 lines
1.4 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.LocalApplicationData),
|
|
"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.
|
|
}
|
|
}
|
|
|
|
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);
|
|
}
|
|
}
|
|
}
|