public override void Flush()
{
if (_logBuffer.Count == 0)
{
return;
}
ConcurrentQueue<string> currentBuffer = null;
lock (_syncLock)
{
// Snapshot the current set of buffered logs
// and set a new queue. This ensures that any new
// logs are written to the new buffer.
// We do this snapshot in a lock since Flush might be
// called by multiple threads concurrently, and we need
// to ensure we only log each log once.
currentBuffer = _logBuffer;
_logBuffer = new ConcurrentQueue<string>();
}
if (currentBuffer.Count == 0)
{
return;
}
// concatenate all lines into one string
StringBuilder sb = new StringBuilder();
string line = null;
while (currentBuffer.TryDequeue(out line))
{
sb.AppendLine(line);
}
// write all lines in a single file operation
string contents = sb.ToString();
try
{
lock (_syncLock)
{
File.AppendAllText(_currentLogFileInfo.FullName, contents);
}
}
catch (DirectoryNotFoundException)
{
// need to handle cases where log file directories might
// have been deleted from underneath us
Directory.CreateDirectory(_logFilePath);
lock (_syncLock)
{
File.AppendAllText(_currentLogFileInfo.FullName, contents);
}
}
_currentLogFileInfo.Refresh();
if (_currentLogFileInfo.Length > MaxLogFileSizeBytes)
{
SetNewLogFile();
}
}