Vurko Vurko - 3 months ago 19
Android Question

Maintain 3 days log - Android

I have a location service in my app. For debug purposes, i want to log (to text file) some events like "new coordinate", "service onDestroy", "service onStartCommand", "coordinate sent to backend", and so on.
But im facing with a problem. The log file gets 350+ new lines each day .. so.. in 3 days i have a file with 1000 lines.

My idea is to maintain only the 3 (or N in that case) last days and delete the content that was written 3+ days ago.


  • I don't want to check in every write if there are old lines to be removed

  • I don't want to set an alarm that fires every 3 days to erase the old data.

Can you please tell me if you know another efficient way to handle this situation?


Without a way to index into the text file, there's really no way to solve it without reading each line of the file (up to a certain point), parsing it and finding the date.

Don't keep a file. Keep a database. Have one of the columns be "created time". Then you can easily delete the rows that with a created time older than some threshold.

      "created_time < ?", 
      new String[] { System.currentTimeIllis() - Integer.toString(TimeUnit.DAYS.toMillis(3)

(Or something, please test your own SQL ...)

As a side note, a 1,000 line text file is nothing. Reading and parsing it is not significant unless you are doing it often. If you read and trimmed the file 1x per day, no problem.

Another solution would be to rotate the files (log --> log.1, log.1 --> log.2, ..., log.n-1 ---> log.n). This of course doesn't set a hard limit on the size of any particular file.