I have a PHP application that can generate quite a lot of log information. I'd like to use logrotate
to make sure these logs don't get out of hand over time.
However, I'm concerned about race conditions. Could there be a loss of log messages if PHP is in the middle of writing to a log when logrotate
determines it needs to rotate that log, as in the sequence of events below? If not, why?
- PHP opens log file for writing.
- PHP writes a line.
logrotate
decides the log file should be rotated.- PHP writes another line.
- PHP closes file resource.
Would using PHP's file_put_contents
, for example, make any difference? What about, more generally, output that is piped to a log file?
Environment Specifics:
I'm using php5-fpm
(Version: 5.5.9+dfsg-1ubuntu4.6
) behind an nginx server on a different machine.
My proposed logrotate config (I haven't set anything up yet) would be something like this (in /etc/logrotate.d/my-app
):
/var/my-app-data/logs/*.log {
missingok
notifempty
weekly
size 20M
rotate 4
}
A couple of examples of my PHP logging code:
$res = file_put_contents('/var/my-app-data/logs/general.log', date('[d/m/Y H:i:s]') . ' Something noteworthy has happened!' . "\n", FILE_APPEND);
It's possible we may want to use something like the code below in the future:
$fp = fopen('/var/my-app-data/logs/general.log', 'a');
fwrite($fp, date('[d/m/Y H:i:s]') . ' Starting process...' . "\n");
// ...
fwrite($fp, date('[d/m/Y H:i:s]') . ' Something happened!' . "\n");
// ...
fwrite($fp, date('[d/m/Y H:i:s]') . ' Something happened!' . "\n");
// ...
fwrite($fp, date('[d/m/Y H:i:s]') . ' End of process.' . "\n");
fclose($fp);