Search code examples
c#fileloggingfilesizefile-manipulation

Keeping log files under a certain size


I have an application that is running on a stand-alone panel PC in a kiosk (C#/WPF). It performs some typical logging operations to a text file. The PC has some limited amount of disk space to store these logs as they grow.

What I need to do is be able to specify the maximum size that a log file is allowed to be. If, when attempting to write to the log, the max size is exceeded, new data will be written to the end of the log and the oldest data will be purged from the beginning.

Getting the file size is no problem, but are there any typical file manipulation techniques to keep a file under a certain size?


Solution

  • One technique to handle this is to have two log files which are half the maximum size each. You simply rotate between the two as you reach the max size of each file. Rotating to a file causes it to be overwritten with a new file.

    A logging framework such as log4net has this functionality built in.