Example #1
0
        public async Task SetNewLogFile_PurgesOldLogFiles()
        {
            DirectoryInfo directory = new DirectoryInfo(_logFilePath);

            directory.Create();

            // below test expects the retention days to be set to 1
            Assert.Equal(1, FileTraceWriter.LastModifiedCutoffDays);

            // create some log files
            List <FileInfo> logFiles     = new List <FileInfo>();
            int             initialCount = 5;

            for (int i = 0; i < initialCount; i++)
            {
                string fileName = string.Format("{0}-{1}.log", i, FileTraceWriter.GetInstanceId());
                string path     = Path.Combine(_logFilePath, fileName);
                Thread.Sleep(50);
                File.WriteAllText(path, "Test Logs");
                logFiles.Add(new FileInfo(path));
            }

            // mark some of the files as old - we expect
            // all of these to be purged
            File.SetLastWriteTime(logFiles[2].FullName, DateTime.Now.Subtract(TimeSpan.FromDays(1)));
            File.SetLastWriteTime(logFiles[1].FullName, DateTime.Now.Subtract(TimeSpan.FromDays(1)));
            File.SetLastWriteTime(logFiles[0].FullName, DateTime.Now.Subtract(TimeSpan.FromDays(2)));

            await Task.Delay(2000);

            var files = directory.GetFiles().OrderByDescending(p => p.LastWriteTime).ToArray();

            Assert.Equal(initialCount, files.Length);

            FileTraceWriter traceWriter = new FileTraceWriter(_logFilePath, TraceLevel.Verbose);

            traceWriter.SetNewLogFile();

            files = directory.GetFiles().OrderByDescending(p => p.LastWriteTime).ToArray();

            await TestHelpers.Await(() =>
            {
                files = directory.GetFiles().OrderByDescending(p => p.LastWriteTime).ToArray();
                return(files.Length == 2);
            }, timeout : 2000);

            // verify the correct log files were purged and the 2
            // most recent files were retained
            Assert.True(files[0].Name.StartsWith("4"));
            Assert.True(files[1].Name.StartsWith("3"));
        }