PHP for rotating log files based on size


<?php

// Define the path to the log file
$log_file = '/path/to/log.txt';

// Define the maximum size of the log file (in bytes)
$max_file_size = 1000000;

// Open the log file for appending
$fp = fopen($log_file, 'a');

// Append the new log message to the file
fwrite($fp, '...');

// Close the log file
fclose($fp);

// Check the size of the log file
$file_size = filesize($log_file);

// If the log file is larger than the maximum size, rotate it
if ($file_size > $max_file_size) {
  // Get the current time
  $date = date('Y-m-d-H-i-s');

  // Create a new log file with the current time in its name
  $new_log_file = $log_file . '.' . $date;
  copy($log_file, $new_log_file);

  // Truncate the original log file
  truncate($log_file);
}

Explanation:

This code shows how to rotate log files based on size in PHP. It works by opening the log file for appending, writing the new log message to the file, and closing the log file. Then, it checks the size of the log file and if it is larger than the maximum size, it rotates the log file. To rotate the log file, it creates a new log file with the current time in its name, copies the contents of the original log file to the new log file, and truncates the original log file.

How to implement it effectively:

To implement this code effectively, you should:

  • Choose an appropriate maximum size for the log file. This will depend on the size of your logs and the frequency with which you want to rotate them.
  • Use a cron job to run the script regularly. This will ensure that the log file is rotated regularly, even if you forget to do it manually.
  • Monitor the log file size to make sure that it does not grow too large. If the log file grows too large, it can cause performance problems or even crash your application.