I have an VB.NET app that writes the status to a log file in text format. Over time, the file is getting large and I wanted to know if there is an efficient way to truncate the beginning of the file.
To make things easier, I am looking to specify a file size (say 2-3 mb) and I am writing the log using a StreamWriter:
Using strm As New IO.StreamWriter(filelocation.log, True)
strm.WriteLine("msg to write")
strm.Close()
End Using
I thought about using the strm.BaseStream.Length to determine how much of the file to cut off, but by using the .SetLength it would cut from the end – not the desired result.
I would highly suggest looking at log4net to accomplish your logging. It’s extremely powerful and flexible and has a built in way of rolling your logs based on a size you can specify. It’s not the answer you’re looking for here, but it’s definitely worth looking into. Here’s a sample config for what we do for logging during debug:
This code in the app.config file will create a log file called ClientTools.log in the application folder, write it in a specific format including the date and time, and roll the log at 3MB.
To use the logger, we do this in Init() of the web page:
public ILog log;
And then when you want to log something, do this:
You don’t have to worry about creating a stream object, closing the stream, disposing the stream, etc. And it’s very DRY.