Print PHP Call Stack

前端 未结 15 1563
清歌不尽
清歌不尽 2020-11-27 09:08

I\'m looking for a way to print the call stack in PHP.

Bonus points if the function flushes the IO buffer.

相关标签:
15条回答
  • please take a look at this utils class, may be helpful:

    Usage:

    <?php
    /* first caller */
     Who::callme();
    
    /* list the entire list of calls */
    Who::followme();
    

    Source class: https://github.com/augustowebd/utils/blob/master/Who.php

    0 讨论(0)
  • debug_backtrace()

    0 讨论(0)
  • 2020-11-27 09:34

    If you want to generate a backtrace, you are looking for debug_backtrace and/or debug_print_backtrace.


    The first one will, for instance, get you an array like this one (quoting the manual) :

    array(2) {
    [0]=>
    array(4) {
        ["file"] => string(10) "/tmp/a.php"
        ["line"] => int(10)
        ["function"] => string(6) "a_test"
        ["args"]=>
        array(1) {
          [0] => &string(6) "friend"
        }
    }
    [1]=>
    array(4) {
        ["file"] => string(10) "/tmp/b.php"
        ["line"] => int(2)
        ["args"] =>
        array(1) {
          [0] => string(10) "/tmp/a.php"
        }
        ["function"] => string(12) "include_once"
      }
    }
    


    They will apparently not flush the I/O buffer, but you can do that yourself, with flush and/or ob_flush.

    (see the manual page of the first one to find out why the "and/or" ;-) )

    0 讨论(0)
  • 2020-11-27 09:36

    To log the trace

    $e = new Exception;
    error_log(var_export($e->getTraceAsString(), true));
    

    Thanks @Tobiasz

    0 讨论(0)
  • 2020-11-27 09:37

    Strange that noone posted this way:

    debug_print_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
    

    This actually prints backtrace without the garbage - just what method was called and where.

    0 讨论(0)
  • 2020-11-27 09:40

    I have adapted Don Briggs's answer above to use internal error logging instead of public printing, which may be your big concern when working on a live server. Also, added few more modifications like option to include full file path instead of basic name (because, there could be files with same name in different paths), and also (for those who require it) a complete node stack output:

    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());
    
    0 讨论(0)
提交回复
热议问题