Skip to content

Instantly share code, notes, and snippets.

@greglamb
Created October 7, 2013 20:28
Show Gist options
  • Save greglamb/6874406 to your computer and use it in GitHub Desktop.
Save greglamb/6874406 to your computer and use it in GitHub Desktop.
When core dumps got you down: The Worst Case Scenario Debugger
<?php
declare(ticks=1);
function formatBytes($size, $precision = 2)
{
$base = log($size) / log(1024);
$suffixes = array('', 'k', 'M', 'G', 'T');
return round(pow(1024, $base - floor($base)), $precision) . $suffixes[floor($base)];
}
register_tick_function(function(){
$backtrace = debug_backtrace();
$line = $backtrace[0]['line'] - 1;
$file = $backtrace[0]['file'];
# if ($file == __FILE__) return;
static $fp, $cur, $buf;
if (!isset($fp[$file])) {
$fp[$file] = fopen($file, 'r');
$cur[$file] = 0;
}
if (isset($buf[$file][$line])) {
$code = $buf[$file][$line];
} else {
do {
$code = fgets($fp[$file]);
$buf[$file][$cur[$file]] = $code;
} while (++$cur[$file] <= $line);
}
$line++;
$log = "[".date("Y-m-d H:i:s")."] [MU:".formatBytes(memory_get_usage(),0)."] [MP:".formatBytes(memory_get_peak_usage(TRUE),0)."] [ML:".ini_get('memory_limit')."] [".basename($file).":$line] \t ".trim($code);
#error_log($log);
echo $log."\n";
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment