public LogWriter(string FileLocation, bool Truncate = false, int TruncateLen = 2097152)
{
// Set internals
LogFile = new FileInfo(FileLocation);
LogQueue = new ConcurrentQueue<LogMessage>();
// Test that we are able to open and write to the file
using (FileStream stream = LogFile.Open(FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
{
// If the file is over 2MB, and we want to truncate big files
if (Truncate && LogFile.Length > TruncateLen)
{
stream.SetLength(0);
stream.Flush();
}
}
// Create our task
FlushTask = new Task(FlushLog);
// Start a log timer, and auto write new logs every 3 seconds
LogTimer = new Timer(3000);
LogTimer.Elapsed += (s, e) =>
{
if (LogQueue.Count > 0 && FlushTask.Status != TaskStatus.Running)
{
// Dispose old instance
if (FlushTask.Status != TaskStatus.Created)
{
// Create new
FlushTask.Dispose();
FlushTask = new Task(FlushLog);
}
// Start the task
FlushTask.Start();
}
};
LogTimer.Start();
}