I’m logging to a file using FileStream.Write(). When the file reaches a maximum size, I want to delete a load of the logs from the start of the file. What’s the best way of doing this?
The best idea I’ve got so far is to create a second file. Write everything I want to keep from the original file into it. Then delete the original file, and rename the second file with the original files name.
Is there a more simple and efficient way I can do this?
Yes, and no 😉
Which is important to you: efficiency, or simplicty?
More efficient: A traditional rolling log is a fixed-sized-record. You use a random access file in read/write mode, keep track of the current record pointer, and when current record == max records set current record back to zero. Obviously, this places restrictions on what you can log… DB’s do this on “raw disk” to enable them to random-access variable record size. This also requires a custom log-reader application. Yeck!
Simpler (and still a tad more efficient than copying thousands of lines from file to file): write many but smaller log files. “Roll over” the log file periodically, or when it reaches a certain size… i.e. start a new log-file and if numLogs == maxLogs then delete the oldest one.
Cheers. Keith.