Skip to content

Instantly share code, notes, and snippets.

@jhurliman
Created July 20, 2012 00:03
Show Gist options
  • Save jhurliman/3147770 to your computer and use it in GitHub Desktop.
Save jhurliman/3147770 to your computer and use it in GitHub Desktop.
Pretty print stack trace in PHP
function stackTrace() {
$stack = debug_backtrace();
$output = 'Stack trace:' . PHP_EOL;
$stackLen = count($stack);
for ($i = 1; $i < $stackLen; $i++) {
$entry = $stack[$i];
$func = $entry['function'] . '(';
$argsLen = count($entry['args']);
for ($j = 0; $j < $argsLen; $j++) {
$func .= $entry['args'][$j];
if ($j < $argsLen - 1) $func .= ', ';
}
$func .= ')';
$output .= '#' . ($i - 1) . ' ' . $entry['file'] . ':' . $entry['line'] . ' - ' . $func . PHP_EOL;
}
return $output;
}
@birawaich
Copy link

birawaich commented Jul 30, 2018

Thank you, just what I needed!

NOTE

If the function arguments cannot be converted to a string, you'll receive an error in line 12.
To circumvent this problem I just exported that variable:
LINE 12: $func .= var_export($entry['args'][$j],true);

@ke5vmj
Copy link

ke5vmj commented Aug 9, 2021

Thank you, just what I needed!

NOTE

If the function arguments cannot be converted to a string, you'll receive an error in line 12.
To circumvent this problem I just exported that variable:
LINE 12: $func .= var_export($entry['args'][$j],true);

If your code throws an exception at or near a database connection it's probably best to strip out and/or not print out any arguments else you may leak sensitive database credentials in your logs

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment