Php : Rotating Log Files


A long time ago, I was in a plane for more than 10 hours and I had to utilize that time efficiently. I decided to open my laptop and start coding. But, while being off-net for a long period of time, I had no distraction and started to think. I was creating an application that was generating a lot of logs and I thought important to keep them in an efficient way. This is why log rotation came to mind.

Let's Php

So, the requirement was simple : provide a filename, a retention and a size limit and then run the script at the desired time interval. It was 100% inspired from the Linux /var/logs file rotation mechanism (logrotate.d).

My intention was to rotate log files on a Linux-style OS so, I'm using references to the Linux OS in my code. This could be ported on Windows with less efforts. The other requirement is to have the tar package installed.

Parameters :

// Original log file you need to rotate
This will be the base name. All rotated logs will use that name and add an number at the end :


Those files will be compressed using the tar command to save some storage.

// Retention (how many logs to keep)
How many files are kept ? This is the maximum number. When a new file is created, the oldest is removed and cannot be restored.

// Maximum size before rotating (in Kb, 1 Mb = 1024 Kb). This is the actual uncompress log size
$maxSize="5120"; // 5 MB

When to initiate a rotate ? When the maximum configured size is reached.

My recommendation is to run this script every hours in a cron so, you have a tighten control on your logs files. Now, if you application is very chatty you can of course adjust to other values that suits you more. I'm only talking about a generic usage.

You can find the script here. Have fun !

I really hope this helps ;)


What's hot ?

Wallbox : Get The Most Of It (with API)

PCBWay : CNC Machining