Implement manual log file rotating and culling

This commit is contained in:
Raymond 2021-08-09 10:04:05 -04:00
parent f66e5ca08b
commit 61b5b2631f
2 changed files with 132 additions and 13 deletions

View file

@ -128,12 +128,58 @@ namespace Dalamud.Injector
levelSwitch.MinimumLevel = LogEventLevel.Information;
#endif
CullLogFile(logPath, 1 * 1024 * 1024);
Log.Logger = new LoggerConfiguration()
.WriteTo.Async(a => a.File(logPath))
.MinimumLevel.ControlledBy(levelSwitch)
.CreateLogger();
}
private static void CullLogFile(string logPath, int cullingFileSize)
{
try
{
var bufferSize = 4096;
var logFile = new FileInfo(logPath);
if (!logFile.Exists)
logFile.Create();
if (logFile.Length <= cullingFileSize)
return;
var amountToCull = logFile.Length - cullingFileSize;
if (amountToCull < bufferSize)
return;
using var reader = new BinaryReader(logFile.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite));
using var writer = new BinaryWriter(logFile.Open(FileMode.Open, FileAccess.Write, FileShare.ReadWrite));
reader.BaseStream.Seek(amountToCull, SeekOrigin.Begin);
var read = -1;
var total = 0;
var buffer = new byte[bufferSize];
while (read != 0)
{
read = reader.Read(buffer, 0, buffer.Length);
writer.Write(buffer, 0, read);
total += read;
}
writer.BaseStream.SetLength(total);
}
catch (Exception ex)
{
var caption = "XIVLauncher Error";
var message = $"Log cull threw an exception: {ex.Message}\n{ex.StackTrace ?? string.Empty}";
_ = MessageBoxW(IntPtr.Zero, message, caption, MessageBoxType.IconError | MessageBoxType.Ok);
}
}
private static Process GetProcess(string arg)
{
Process process;