0

I have a logging application that works great, but I want to apply the ability to maintain the size of the log file - stop it from getting too large.

Ideally, I want to check the size of the file periodically, and if it's over the configured amount (5MB or something) delete from the beginning till it reaches some size, like 4MB.

From reading other questions I'm still unclear if I can update/delete a file without reading it's entire contents. My ideal situation would be:

if(filesize > 5MB)
{
    while(filesize > 4MB)
        Delete_First_X_Many_Lines(file);
}

Thankyou in advance for any pointers and direction.

Jonesopolis
  • 25,034
  • 12
  • 68
  • 112
  • I know you can modify parts of a file, without reading the entire file. But delete from the beginning? I fear that's not possible (though I might be wrong) – Nolonar May 29 '13 at 16:08
  • 1
    Any chance of using an existing logging framework like NLog or log4net? They already have this feature and many, many more. – Ryan May 29 '13 at 16:11
  • I think you're going to have to read it and write back what you mean to keep. However, knowing how much to write back will be an issue. Or like Ryan suggests...use a 3rd party library where someone's already done the heavy lifting. – DonBoitnott May 29 '13 at 16:11
  • related: http://stackoverflow.com/questions/706167/truncate-file-at-front – bmm6o May 30 '13 at 00:33

1 Answers1

0

I would do this:

  1. Lock the log file (prevent writes).
  2. Copy the end of the log file you want to keep to a new file.
  3. Copy the new file on top of the old log file.
  4. Unlock the log file.
Polyfun
  • 9,479
  • 4
  • 31
  • 39