I am trying to get last 5 minutes logs for use to this below code. this code is given to all logs that created I only want to last 5 minute logs. how can I get anyone can please help me…
class Program
{
static void Main(string[] args)
{
WriteLogs.WriteLog("ConsoleLog", String.Format("{0} @ {1}", "Log is Created at", DateTime.Now));
Console.WriteLine("Log is Written Successfully !!!");
Console.ReadLine();
}
}
class WriteLogs
{
public static bool WriteLog(string strFileName, string strMessage)
{
try
{
FileStream objFilestream = new FileStream(string.Format("{0}\{1}", Path.GetTempPath(), strFileName), FileMode.Append, FileAccess.Write);
StreamWriter objStreamWriter = new StreamWriter((Stream)objFilestream);
objStreamWriter.WriteLine(strMessage);
objStreamWriter.Close();
objFilestream.Close();
return true;
}
catch (Exception ex)
{
return false;
}
}
}
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Assuming you are appending to the same log file with same string format, you can just read the file line by line or all lines at once. But since you need last 5 minutes logs, those logs would always be near the end of the file. So lets just use the later approach (We can also read a file line by line in reverse, but its tricky and would require lot of code and considerations).
First you need to define a function which fetches the logs from a given date as below –
public static IEnumerable<string> GetLogs(string strFileName, DateTime dateTime)
{
var path = Path.Combine(Path.GetTempPath(), strFileName);
var logs = File.ReadAllLines(path).Where(w =>
{
var date = DateTime.Parse(w.Split("@")[1]);
return date >= dateTime;
});
return logs;
}
Call the above function as below to get last 5 minutes logs –
var logs = GetLogs("ConsoleLog", DateTime.Now.AddMinutes(-5));
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0