I tried implementing the function of log rotation with PHP

Aug 27, 2020 PHP log rotation

#Introduction Due to the need, I decided to create a log rotation function in PHP. It would be nice if it could be set quickly with middleware or free tools if possible.

Since I am a PHP beginner, I will not do anything difficult. (1) Delete backup files that have exceeded the retention period. ② Make a backup of the log file. I’ve kept the two processes of writing quickly.

I will leave it as a memorandum.

#Log rotation

Result of implementation in PHP

** [As a premise] **

// Time zone specification *To avoid date function error

// Log file path *It is necessary to rewrite according to the environment.
$logPath = "C:/work/log";
$logName = "batch.log";
It's a sequel.
// Log retention days
$saveDays = "5";
It's a sequel.
// Delete the backup log that exceeds the number of log retention days.
foreach (scandir($logPath) as $file) {
if (preg_match("/" .$logName ."\./", $file)) {
$delPointDate = date('Ymd',strtotime("-". $saveDays ." day"));
$backupLogDate = substr($file, -8);
if ($backupLogDate-$delPointDate <0) {
unlink($logPath ."/" .$file);

* Rename the log file and make a backup.
* Since this is a daily backup, YYYYMMDD is added to the end of the backup file name.
* Place an empty log file after renaming.
$sysDate = date("Ymd");
if (file_exists($logPath)) {
rename($logPath ."/" .$logName, $logPath ."/" .$logName ."." .$sysDate);
touch($logPath ."/" .$logName);

Result of executing log rotation function

Process execution date * Manually operate the PC date

Before processing

After processing