Keep limited log file size in PHP/Laravel


We need to keep the log file size within decent limits. Last 10 MBytes should be enough for the general site health surveillance. The redundant leading part can be periodically deleted.

One option would be to use a temporary backup file as a ramp for swapping the retained content. A memory buffer would be necessary to transfer in chunks without engaging large areas of memory.

In order not to shrink upon every character added we implement a pulsing shrink algorithm, where the allowed maximum file size (the threshold) is larger than the size after the cyclic shrink operation.

Note that both files are locked for external access during the maintenance operation.

Put following function in a PHP file:

Now you can call that function periodically, e.g.:

  • in a cron job ones a day (probably the best option)
  • each time something is logged (would be too much)
  • with each http request (would be too much)
  • manually from time to time
  • etc.

Use following code with the right adaptation to your needs:

For a cron job you would need home based paths:

Let's do it properly!


Back to List