The solutions here did not work for me. I took user3902302's answer, which was again based on Bigtech's answer and wrote the full class. In addition, I DO NOT use StreamWriter, you can change one line (AppendAllText versus peer StreamWrite).
There is little error handling (for example, retrying access on failure, although blocking should catch all internal concurrent access).
This may be enough for some people who previously had to use such a large solution as log4net or nlog. (And the log4net RollingAppender is not even thread safe, it is one. :))
public class RollingLogger { readonly static string LOG_FILE = @"c:\temp\logfile.log"; readonly static int MaxRolledLogCount = 3; readonly static int MaxLogSize = 1024;
change
Since I just noticed that you asked a slightly different question: should your lines vary greatly in size, this will be a variation (which in 90% of cases will not improve compared to yours, although it can be very slightly faster, a new unhandled error was also introduced (\ n is not present)):
private static void PerformFileTrim(string filename) { var fileSize = (new System.IO.FileInfo(filename)).Length; if (fileSize > 5000000) { var text = File.ReadAllText(filename); var amountToCull = (int)(text.Length * 0.33); amountToCull = text.IndexOf('\n', amountToCull); var trimmedText = text.Substring(amountToCull + 1); File.WriteAllText(filename, trimmedText); } }
Andreas Reiff
source share