Saturday, 28 July 2012

PHP Memory Monitoring For All Scripts

We recently had a web server crash due to memory running so low the Linux kernel was killing off processes... Being an extremely busy server with SLA I immediately took a look and found Apache chowing away at pretty much all the memory... The problem which popped-up next was trying to find which PHP script/s were consuming so much memory (24MB memory limit per script) so I came up with this:

The script, eg. /var/www/memory.php in our case should have the similar ownership/permissions in Linux to your existing PHP scripts and should have access to write to the log file mentioned in the script:

<?

$used_bytes = memory_get_peak_usage();

function ByteSize($bytes){
 $size = $bytes / 1024;
 if($size < 1024){
  $size = number_format($size, 2);
  $size .= ' KB';
 } else {
  if ($size / 1024 < 1024){
   $size = number_format($size / 1024, 2);
   $size .= ' MB';
  } else if ($size / 1024 / 1024 < 1024){
   $size = number_format($size / 1024 / 1024, 2);
   $size .= ' GB';
  }
 }
 return $size;
}

$human_size = ByteSize($used_bytes);

$fp = @fopen("/memory_usage.log","a+"); //Change this where you want this log...
if ($fp){
 $script_uri = $_SERVER['REQUEST_URI'];
 fwrite($fp, "$human_size consumed by $script_uri\n");
 fclose($fp);
}

?>

Adding this line to php.ini calls the script:

auto_append_file = /var/www/memory.php


Restart apache and give it a try, Hopefully this helps someone else!

No comments:

Post a Comment