我正在寻找一种在PHP中打印调用堆栈的方法。
如果函数刷新IO缓冲区,则加分。
我正在寻找一种在PHP中打印调用堆栈的方法。
如果函数刷新IO缓冲区,则加分。
当前回答
如果你想要一个堆栈跟踪,它看起来非常类似于php的异常堆栈跟踪格式,那么可以使用我写的这个函数:
function debug_backtrace_string() {
$stack = '';
$i = 1;
$trace = debug_backtrace();
unset($trace[0]); //Remove call to this function from stack trace
foreach($trace as $node) {
$stack .= "#$i ".$node['file'] ."(" .$node['line']."): ";
if(isset($node['class'])) {
$stack .= $node['class'] . "->";
}
$stack .= $node['function'] . "()" . PHP_EOL;
$i++;
}
return $stack;
}
这将返回如下格式的堆栈跟踪:
#1 C:\Inetpub\sitename.com\modules\sponsors\class.php(306): filePathCombine()
#2 C:\Inetpub\sitename.com\modules\sponsors\class.php(294): Process->_deleteImageFile()
#3 C:\Inetpub\sitename.com\VPanel\modules\sponsors\class.php(70): Process->_deleteImage()
#4 C:\Inetpub\sitename.com\modules\sponsors\process.php(24): Process->_delete()
其他回答
记录跟踪
$e = new Exception;
error_log(var_export($e->getTraceAsString(), true));
谢谢@Tobiasz
您可能想查看debug_backtrace,或者debug_print_backtrace。
请看看这个utils类,可能会有帮助:
用法:
<?php
/* first caller */
Who::callme();
/* list the entire list of calls */
Who::followme();
源类:https://github.com/augustowebd/utils/blob/master/Who.php
我修改了上面Don Briggs的回答,使用内部错误记录而不是公开打印,这可能是您在活动服务器上工作时最关心的问题。此外,增加了一些更多的修改,如选项包括完整的文件路径,而不是基本名称(因为,可能有相同名称的文件在不同的路径),以及(对于那些需要它的人)一个完整的节点堆栈输出:
class debugUtils {
public static function callStack($stacktrace) {
error_log(str_repeat("=", 100));
$i = 1;
foreach($stacktrace as $node) {
// uncomment next line to debug entire node stack
// error_log(print_r($node, true));
error_log( $i . '.' . ' file: ' .$node['file'] . ' | ' . 'function: ' . $node['function'] . '(' . ' line: ' . $node['line'] . ')' );
$i++;
}
error_log(str_repeat("=", 100));
}
}
// call debug stack
debugUtils::callStack(debug_backtrace());
看到debug_print_backtrace。我想如果你想的话,你可以之后再喊冲水。