I have a winForm app in which I have a text file for logging purpose. I want to limit its size to 10 MB so that if this limit is passed and new data is written then the oldest data in text file is deleted to make space for new data. any useful suggestion ?
问题:
回答1:
Use some logging framework (I suggest NLog or log4net, both available from NuGet) which provides rolling log files feature.
E.g. with log4net you can use following configuration to limit log file size to 10Mb
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="log.txt" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="10MB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %-5level %logger - %message%newline" />
</layout>
</appender>
NLog configuration looks like
<target xsi:type="File"
name="RollingFileAppender"
layout="${verbose}"
archiveAboveSize="10000000"
maxArchiveFiles="10"
archiveFileName="${basedir}/archives/log.{#####}.txt"
archiveNumbering="Sequence"
fileName="log.txt" />
回答2:
I'd use logging library like log4net. The RollingFileAppender has exactly what you're looking for.
回答3:
Just check the file size before you write on it. Here a tuto
http://www.dotnetperls.com/fileinfo-length
If you'd like something more try NLog or log4net this as others suggested which are really helpful
回答4:
If you don't want to use a logging framework (though you probably should, really), then you can do the following:
- Look at the length of the file each time you write (or at some other regular period)
- When it exceeds the limit, perform a trimming operation - this will involve starting at the beginning of the file, and then walking through the file reading lines until you've read enough data to trim off. Having found that position, you have several ways to remove the space from the beginning of the file, though none of them are very attractive, unless you're happy to load the whole file into memory, which is not unreasonable for a 10MB file nowadays.
The KEY thing to implement though is to remove much more from the file than the minimum required to get back under the limit - for example let the file grow to 11MB and then trim it back to 10MB. Then you'll only run a trim cycle after every 1MB of logging. If you're naive about this, then you'll find yourself trimming for every single logged line, which would be absurd.
But really, the excellent logging frameworks for .NET which already exist are a much better way to do this - they'll things like async logging and key a rolling month's-worth of daily logs, for example.