Using logrotate to manage logs generated by PHP

My PHP scripts generate log files and I am trying to use logrotate to manage them.

File /etc/logrotate.d/php-logs:

/srv/cache/*.log { daily notifempty size 800K rotate 5 missingok compress delaycompress
}

This is working, except for the part that sometimes the log rotation process coincides with PHP trying to append the log.

What is the best way to solve this?

2 Answers

There are some log rotate options that might help. See copytruncate in This will create a copy and truncate the original file. Therefore, the log file doesn't have to be closed and it's held open by your php script. Some log statements might get dropped between the copy and truncate operation.

Meanwhile, my solution (bandage) is done within PHP, but I realise that it may not be the most proper or elegant one.

<?php
function log_record($str, $file_name) { $n = 0; while ($n < 10) { if (is_readable($file_name)) { file_put_contents($file_name, str_pad($_SERVER["REMOTE_ADDR"], 15, ' ', STR_PAD_RIGHT).' ['.date("Y-m-d H:i:s").'] '. $str . PHP_EOL, FILE_APPEND | LOCK_EX); exit; } usleep(10000); // That's 10 ms, up to 10 times. }
}

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like