Explanation
I am writing the logs to a file every 15 mins using logcat. It writes to a file properly but at 30thmin(i.e if I start writing to a file at 11:30 next it will write at 11:45 and at 12:00) it will also add the duplicates to the file. Now how to clear the duplicates from the logcat so it won't write to a file?
In this method, I set the time so that it will write to a file every 15mins.
SetAlarm method
private void ScheduleLogSaverService()
{
try
{
Intent logSaverIntent = new Intent(this, typeof(LogSaverService));
logSaverIntent.PutExtra("LogPath", Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "LogFile");
if (!Utils.IsServiceAlarmSet(logSaverIntent, 2561, this))
{
PendingIntent pendingIntent = PendingIntent.GetService(this, 2561, logSaverIntent, PendingIntentFlags.UpdateCurrent);
Utils.SetAlarm(pendingIntent, AlarmManager.IntervalFifteenMinutes, this);
Log.Debug("MonoVeP", "MainActivity::ScheduleLogSaverService - alarm set");
}
else
{
Log.Debug("MonoVeP", "MainActivity::ScheduleLogSaverService - alarm already set");
}
}
catch (Exception e)
{
Log.Debug("MonoVeP", "MainActivity::ScheduleLogSaverService threw an exception: " + e);
}
}
Clearing the logcat and then writing the logs to a file
write method
private void WriteLog()
{
Java.Lang.Process process = null;
string path = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "LogFile"
File _logfile = new File(path+"log.txt");
try
{
process = Runtime.GetRuntime().Exec("logcat -c");
string[] command = { "logcat", "-d", "-v", "threadtime" };
process = Runtime.GetRuntime().Exec(command);
using (BufferedReader insr = new BufferedReader(new InputStreamReader(process.InputStream)))
using (BufferedWriter logFile = new BufferedWriter(new FileWriter(_logFile, true))) //true = append
{
string line;
while ((line = insr.ReadLine()) != null)
{
if (!line.Contains("MonoAndroid")) continue;
//builder.Append(line);
logFile.Write(line + "\r\n"); //If your goal is to see it in Notepad, change the line separator to \r\n
logFile.NewLine();
logFile.Flush();
}
}
// DeleteLogsFromCache();
}
catch (IOException ex)
{
Log.Debug("MonoVeP", "LogSaverService :: WriteLog() failed: " + ex);
process?.Destroy();
}
}
I even tried this code to clear the logcat: https://stackoverflow.com/a/26955495/8329826 and https://coderwall.com/p/s0wo3q/android-read-the-logcat-programmatically still it won't stop from writing duplicate to a file.
Question
How to clear the logcat so that it won't write the duplicates to the file? Please suggest.
Answer
In LogSaverService
class
The problem was with string path
variable i declared it globally and also inside the WriteLog()
method. When i removed the global declaration duplication got stopped, other than that there was no problem in the code.