using System; using System.IO; using System.Linq; using System.Text.RegularExpressions; namespace Sony.Filtr.Tasks.Tasks.Spotify.Analytics { public static class ScheduledTaskLogFileParser { private static Regex jobStartRegex = new Regex(@"^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3,5}) \|.* \| Begin processing for argument .+"); public static DateTime GetPreviousLaunchTime() { string[] logFiles = FindScheduledTaskLogFiles(); if (logFiles == null || logFiles.Any() == false) { return DateTime.MinValue; } foreach (var file in logFiles) { Nullable latestLogTime = GetFileLatestLaunchTime(file); if (latestLogTime.HasValue) { return latestLogTime.Value; } } return DateTime.MinValue; } private static Nullable GetFileLatestLaunchTime(string filePath) { var fileDateRegex = new Regex(@"^ScheduledTask-(\d{4}-\d{2}-\d{2})\.txt$"); var match = fileDateRegex.Match(Path.GetFileName(filePath)); if (match.Success == false) { return null; } var logFileDate = DateTime.Parse(match.Groups[1].Value); var sequence = File.ReadAllLines(filePath).Reverse().Where(line => jobStartRegex.IsMatch(line)); //To skip current launch log if (logFileDate == DateTime.Now.Date) { sequence = sequence.Skip(1); } var latestJobStartLog = sequence.FirstOrDefault(); if (latestJobStartLog == null) { return null; } return DateTime.Parse(jobStartRegex.Match(latestJobStartLog).Groups[1].Value); } private static string[] FindScheduledTaskLogFiles() { if (Directory.Exists("logs") == false) { return Array.Empty(); } var dir = new DirectoryInfo("logs"); var latestLogs = dir.EnumerateFiles("ScheduledTask*.txt") .OrderByDescending(f => f.LastWriteTime) .ToArray(); return latestLogs .Select(fi => fi.FullName) .ToArray(); } } }