Can I limit the file size(and discard "old" bytes if exceeds the limit)?

When I write a stream to a file, Can I treat it like a "FIFO"?

fn log(file: File, message: String) {
    file.write(message.as_bytes()).unwrap();
    if f.metadata().unwrap().len() > MY_LIMIT {
        //discard first some bytes(old logs) of the file
        //and make file size under MY_LIMIT
    }
}

I'm making a simple logger struct.
It receives messages and writes them to the logger file.
Every time my app starts, it logs welcome messages, logs what the users have done, and logs good bye messages when they terminate the app.
This log file aims to track the error that my app causes when serious bugs occur. I'm planning showing dialog box with the message to prompt the users to send the log file.
But the problem is, without any size limitation, it theoretically expands to the infinite size.

You cannot remove the start of a file without copying all of the data backwards.

The way this is usually done is by having multiple log files that you rotate, then delete the oldest log file when they're too large.

1 Like

Thanks.
Sounds good for me.
Do you know any good Rust example of handling logging files? :grin:

For those who come to solve same questions with the title...If I stick to do it by a single file, the best way is to create a temporary file, copying desired parts of log file to the temporary one, and overwrite log file with temporal, right?
Also, Any good example?
Thanks.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.