public async Task SetLogFile_PurgesOldLogFiles() { var directory = new DirectoryInfo(_logFilePath); directory.Create(); // below test expects the retention days to be set to 1 Assert.Equal(1, FileWriter.LastModifiedCutoffDays); // create some log files var logFiles = new List <FileInfo>(); for (int i = 0; i < 5; i++) { string fileName = string.Format("{0}-{1}.log", i, FileWriter.GetInstanceId()); string path = Path.Combine(_logFilePath, fileName); File.WriteAllText(path, "Test Logs"); logFiles.Add(new FileInfo(path)); } // push all but the last file over size limit string maxLog = TestHelpers.NewRandomString((int)FileWriter.MaxLogFileSizeBytes + 1); File.AppendAllText(logFiles[3].FullName, maxLog); File.AppendAllText(logFiles[2].FullName, maxLog); File.AppendAllText(logFiles[1].FullName, maxLog); File.AppendAllText(logFiles[0].FullName, maxLog); // mark all the files as old to simulate the passage of time File.SetLastWriteTime(logFiles[4].FullName, DateTime.Now.Subtract(TimeSpan.FromDays(2))); File.SetLastWriteTime(logFiles[3].FullName, DateTime.Now.Subtract(TimeSpan.FromDays(2))); File.SetLastWriteTime(logFiles[2].FullName, DateTime.Now.Subtract(TimeSpan.FromDays(3))); File.SetLastWriteTime(logFiles[1].FullName, DateTime.Now.Subtract(TimeSpan.FromDays(4))); File.SetLastWriteTime(logFiles[0].FullName, DateTime.Now.Subtract(TimeSpan.FromDays(5))); var files = directory.GetFiles().OrderByDescending(p => p.LastWriteTime).ToArray(); Assert.Equal(5, files.Length); // now cause a new log file to be created by writing a huge // log pushing the current file over limit var fileWriter = new FileWriter(_logFilePath); fileWriter.AppendLine(maxLog); // wait for the new file to be created and the old files to be purged await TestHelpers.Await(() => { files = directory.GetFiles().OrderByDescending(p => p.LastWriteTime).ToArray(); return(files.Length == 2); }, timeout : 5000); // expect only 2 files to remain - the new file we just created, as well // as the oversize file we just wrote to last (it has a new timestamp now so // wasn't purged) Assert.True(files[1].Length > FileWriter.MaxLogFileSizeBytes); // expect the new file to be empty because everything was flushed // to the previous file before it was created var fileLines = File.ReadAllLines(files[0].FullName); Assert.Equal(0, fileLines.Length); // make sure the new log is written to the new file fileWriter.AppendLine("test message"); fileWriter.Flush(); fileLines = File.ReadAllLines(files[0].FullName); Assert.Equal(1, fileLines.Length); }