Make a log file with multiple overflow versions in C#

This program makes a log file named log.txt. When you write entries into it, the program checks the file's size. If the size exceeds 100 bytes (you would make this larger for a real application), the program renames the file log.txt.1 and starts a new log.txt. It bumps down older versions of the log to log.txt.2, and log.txt.3. This version usese 3 backup versions but you can also change that in a real application.

The WriteToLog method does all of the work.

private void WriteToLog(string new_text, string file_name, long max_size, int num_backups)
{
// See if the file is too big.
FileInfo file_info = new FileInfo(file_name);
if (file_info.Exists && file_info.Length > max_size)
{
// Remove the oldest version if it exists.
if (File.Exists(file_name + "." + num_backups.ToString()))
{
File.Delete(file_name + "." + num_backups.ToString());
}

// Bump down earlier backups.
for (int i = num_backups - 1; i > 0; i--)
{
if (File.Exists(file_name + "." + i.ToString()))
{
// Move file i to file i + 1.
File.Move(file_name + "." + i.ToString(),
file_name + "." + (i + 1).ToString());
}
}

// Move the main log file.
File.Move(file_name, file_name + ".1");
}

// Write the text.
File.AppendAllText(file_name, new_text + '\n');
}

The code first checks whether the file exists and whether its size exceeds the maximum allowed size. If so, it moves the logs around.

First the code deletes the oldest allowed backup log if it exists. It then bumps backup logs down so, for example, log.txt.2 becomes log.txt.3. It then moves the "live" log to log.txt.1.

The method finishes by appending the new text to the "live" log file. Note that File.AppendAllText automatically creates the file if it doesn't already exist.

Download example



 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this entry.
Comments
  • No comments exist for this entry.
Leave a comment

Submitted comments will be subject to moderation before being displayed.

 Enter the above security code (required)

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.