I have a php script which runs on my ubunutu server. this script runs in an infinite loop running queries and gathering statistics… it is a monitor for some other services. Every 60 seconds the stats that are gathered are dumped as a json object to a .js file. The .js file is monitored elsewhere and is unimportant for the purpose of my question.
When I run my script I redirect both stdout and stderr to a log file.
For the most part there is no output either standard or error and so the log will remain empty.
Obviously though on occasion there will be output. The problem I experienced last night was the script failed for some reason and the log file ended up filling up the whole partition and messed with the stability of the server.
What I have done.. or tried to do is add in a simple check that every 60 seconds (when the stats are dumped) the script checks the size of the log file.. and if it is greater than X mb in size, basically empties the file and allow logging to continue. With the intention being that if the script does experience a problem again, the log file wont fill up the whole partition.
I can successfully detect the log file size, I can successfully clear it when it reaches my set size, but then the next time there is either a STDOUT or STDERR write, all the previous data is dumped in one go.
Any assistance with this would be greatly appreciated.
Calling script by:
php checker.php &> log
but have tried
php checker.php > log 2>&1
and also redirecting the streams at the start of the script
close(STDOUT);
fclose(STDERR);
$STDOUT = fopen($LOG_FILE_LOCATION, 'wb');
$STDERR = fopen($LOG_FILE_LOCATION, 'wb');
each way produces the same output.
Code clearing log file
function CheckLogFilesize($file)
{
global $LOG_FILE_LOCATION;
global $MAX_LOG_SIZE_MB;
$max_log_size_bytes = $MAX_LOG_SIZE_MB * 1024 * 1024;
$size = exec('stat -c %s ' . $file);
// If log file size is too large.. reset it.
if (intval($size) > $max_log_size_bytes)
{
flush();
// Clear the log
$fp = fopen($file, 'w');
fwrite($fp, '');
fclose($fp);
}
}
Thanks
EDIT
Figured it out:
Started with
Note the >> instead of >. You have to use append mode
Example output of
tail -f /tmp/log.log: