hacker hacker - 8 months ago 69
Vb.net Question

Truncate the beginning of a log file in .NET

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")
End Using

I thought about using the
to determine how much of the file to cut off, but by using the
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:

    <appender name="GeneralLog" type="log4net.Appender.RollingFileAppender">
        <file value="ClientTools.log"/>
        <appendToFile value="true"/>
        <maximumFileSize value="3000KB"/>
        <rollingStyle value="Size"/>
        <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%d{HH:mm:ss} [%t] %-5p %c - %m%n"/>
        <level value="DEBUG"/>
        <appender-ref ref="GeneralLog"/>
    <logger name="NHibernate" additivity="false">
        <level value="DEBUG"/>
        <appender-ref ref="GeneralLog"/>

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;

public void InitiateLogging()
    log = LogManager.GetLogger("MyApplication");

And then when you want to log something, do this:

log.Info("No resources available.");
// or
// or
log.Warn("Something bad may happen here.");

You don't have to worry about creating a stream object, closing the stream, disposing the stream, etc. And it's very DRY.