How can I get PHP to produce a backtrace upon errors?

后端 未结 11 1986
無奈伤痛
無奈伤痛 2020-11-28 23:29

Trying to debug PHP using its default current-line-only error messages is horrible. How can I get PHP to produce a backtrace (stack trace) when errors are produced?

相关标签:
11条回答
  • 2020-11-29 00:20

    I just tried setting a session variable containing the contents of debug_backtrace() at the offending line, then printing it using register_shutdown_function(). Worked like a charm.

    0 讨论(0)
  • 2020-11-29 00:26

    You can use debug_backtrace

    0 讨论(0)
  • 2020-11-29 00:26

    PHP DeBugger also does a back trace similiar to PHP Error with more options.
    If you want you can easily make your own with set_error_handler and debug_backtrace

    set_error_handler ($error_handler, error_reporting);
    /**
     * @var int $errno the error number
     * @var string $errstr the error message
     * @var string $errfile the error file
     * @var int $errline the line of the error
     */
    $error_handler = function($errno, $errstr, $errfile, $errline){
        $trace = debug_backtrace();
        array_shift($backtrace);//remove the stack about this handler
        foreach($trace as $k => $v){
            //parse your backtrace
        }
    }
    

    Also note that for internal stacks in the backtrace some of the keys will not be set. Be sure to check if the key exist before you do something with it if you have all errors on :)

    0 讨论(0)
  • 2020-11-29 00:27

    PHP Error

    This is better error reporting for PHP written in PHP. No extra extensions are required!

    It is trivial to use where all errors are displayed in the browser for normal, AJAXy requests (in paused state). Then all errors provides you with a backtrace and code context across the whole stack trace, including function arguments, server variables.

    All you need to do is to include one single file and call the function (at the beginning on your code), e.g.

    require('php_error.php');
    \php_error\reportErrors();
    

    See the screenshots:

    GitHub: https://github.com/JosephLenton/PHP-Error

    My fork (with extra fixes): https://github.com/kenorb-contrib/PHP-Error

    Debug PHP class

    A complete PHP debugger class, with support for Exception, Errors, Alerts ( from user), code lines and highlight flags.

    Example usage:

     <?php
            include( dirname(dirname(__FILE__))  . '/src/Debug.php' );
            //Catch all
            Debug::register();
    
            //Generate an errors
            if( this_function_does_not_exists( ) )
            {
                return false;
            }
        ?>
    

    Error Handling in PHP

    The example below shows the handling of internal exceptions by triggering errors and handling them with a user defined function:

    Shorter way (PHP):

    <?php
    function e($number, $msg, $file, $line, $vars) {
       print_r(debug_backtrace());
       die();
    }
    set_error_handler('e');
    

    Longer way (PHP):

    // set to the user defined error handler
    $old_error_handler = set_error_handler("myErrorHandler");
    
    // error handler function
    function myErrorHandler($errno, $errstr, $errfile, $errline)
    {
        if (!(error_reporting() & $errno)) {
            // This error code is not included in error_reporting
            return;
        }
    
        switch ($errno) {
        case E_USER_ERROR:
            echo "<b>My ERROR</b> [$errno] $errstr<br />\n";
            echo "  Fatal error on line $errline in file $errfile";
            echo ", PHP " . PHP_VERSION . " (" . PHP_OS . ")<br />\n";
            echo "Aborting...<br />\n";
            var_dump(debug_backtrace());
            exit(1);
            break;
    
        case E_USER_WARNING:
            echo "<b>My WARNING</b> [$errno] $errstr<br />\n";
            break;
    
        case E_USER_NOTICE:
            echo "<b>My NOTICE</b> [$errno] $errstr<br />\n";
            break;
    
        default:
            echo "Unknown error type: [$errno] $errstr<br />\n";
            break;
        }
    
        /* Don't execute PHP internal error handler */
        return true;
    }
    

    See: http://www.php.net/manual/en/function.set-error-handler.php

    Note: You can only have one error exception at a time. When you call the set_error_handler() function it will return the name of the old error handler. You can store this and call it yourself from your error handler – thus allowing you to have multiple error handlers.


    XDebug

    For more advanced solution, you can use XDebug extension for PHP.

    By default when XDebug is loaded, it should show you automatically the backtrace in case of any fatal error. Or you trace into file (xdebug.auto_trace) to have a very big backtrace of the whole request or do the profiling (xdebug.profiler_enable) or other settings. If the trace file is too big, you can use xdebug_start_trace() and xdebug_stop_trace() to dump the partial trace.

    Installation

    Using PECL:

    pecl install xdebug
    

    On Linux:

    sudo apt-get install php5-xdebug
    

    On Mac (with Homebrew):

    brew tap josegonzalez/php
    brew search xdebug
    php53-xdebug
    

    Example of mine configuration:

    [xdebug]
    
    ; Extensions
    extension=xdebug.so
    ; zend_extension="/YOUR_PATH/php/extensions/no-debug-non-zts-20090626/xdebug.so"
    ; zend_extension="/Applications/MAMP/bin/php/php5.3.20/lib/php/extensions/no-debug-non-zts-20090626/xdebug.so" ; MAMP
    
    ; Data
    xdebug.show_exception_trace=1       ; bool: Show a stack trace whenever an exception is raised.
    xdebug.collect_vars = 1             ; bool: Gather information about which variables are used in a certain scope.
    xdebug.show_local_vars=1            ; int: Generate stack dumps in error situations.
    xdebug.collect_assignments=1        ; bool: Controls whether Xdebug should add variable assignments to function traces.
    xdebug.collect_params=4             ; int1-4: Collect the parameters passed to functions when a function call is recorded.
    xdebug.collect_return=1             ; bool: Write the return value of function calls to the trace files.
    xdebug.var_display_max_children=256 ; int: Amount of array children and object's properties are shown.
    xdebug.var_display_max_data=1024    ; int: Max string length that is shown when variables are displayed.
    xdebug.var_display_max_depth=3      ; int: How many nested levels of array/object elements are displayed.
    xdebug.show_mem_delta=0             ; int: Show the difference in memory usage between function calls.
    
    ; Trace
    xdebug.auto_trace=0                 ; bool: The tracing of function calls will be enabled just before the script is run.
    xdebug.trace_output_dir="/var/log/xdebug" ; string: Directory where the tracing files will be written to.
    xdebug.trace_output_name="%H%R-%s-%t"     ; string: Name of the file that is used to dump traces into.
    
    ; Profiler
    xdebug.profiler_enable=0            ; bool: Profiler which creates files read by KCacheGrind.
    xdebug.profiler_output_dir="/var/log/xdebug"  ; string: Directory where the profiler output will be written to.
    xdebug.profiler_output_name="%H%R-%s-%t"      ; string: Name of the file that is used to dump traces into.
    xdebug.profiler_append=0            ; bool: Files will not be overwritten when a new request would map to the same file.
    
    ; CLI
    xdebug.cli_color=1                  ; bool: Color var_dumps and stack traces output when in CLI mode.
    
    ; Remote debugging
    xdebug.remote_enable=off            ; bool: Try to contact a debug client which is listening on the host and port.
    xdebug.remote_autostart=off         ; bool: Start a remote debugging session even GET/POST/COOKIE variable is not present.
    xdebug.remote_handler=dbgp          ; select: php3/gdb/dbgp: The DBGp protocol is the only supported protocol.
    xdebug.remote_host=localhost        ; string: Host/ip where the debug client is running.
    xdebug.remote_port=9000             ; integer: The port to which Xdebug tries to connect on the remote host.
    xdebug.remote_mode=req              ; select(req,jit): Selects when a debug connection is initiated.
    xdebug.idekey="xdebug-cli"          ; string: IDE Key Xdebug which should pass on to the DBGp debugger handler.
    xdebug.remote_log="/var/log/xdebug.log" ; string: Filename to a file to which all remote debugger communications are logged.
    

    Drupal 6&7

    With Devel enabled:

    /**
     * Implements hook_watchdog().
     */
    function foo_watchdog($log_entry) {
      if ($log_entry['type'] == 'php' && $log_entry['severity'] <= WATCHDOG_WARNING) {
        function_exists('dd') && dd(debug_backtrace());
      }
    }
    

    Above function will log the backtraces on each error into temporary file (/tmp/drupal_debug.txt by default).

    Or locate the file via: drush eval "echo file_directory_temp() . '/drupal_debug.txt'.

    Without Devel enabled, use old school approach: var_dump(debug_backtrace()); instead of dd().

    0 讨论(0)
  • 2020-11-29 00:30

    If you can't install a debugger then use this function sorrounding the fatal error to get the "fatal stack". Check the code and example below that explains better how to use it:

    // Give an extra parameter to the filename
    // to save multiple log files
    function _fatalog_($extra = false)
    {
        static $last_extra;
    
        // CHANGE THIS TO: A writeable filepath in your system...
        $filepath = '/var/www/html/sites/default/files/fatal-'.($extra === false ? $last_extra : $extra).'.log';
    
        if ($extra===false) {
            unlink($filepath);
        } else {
            // we write a log file with the debug info
            file_put_contents($filepath, json_encode(debug_backtrace()));
            // saving last extra parameter for future unlink... if possible...
            $last_extra = $extra;
        }
    }
    

    Here's an example of how to use it:

    // A function which will produce a fatal error
    function fatal_example()
    {
        _fatalog_(time()); // writing the log
        $some_fatal_code = array()/3; // fatality!
        _fatalog_(); // if we get here then delete last file log
    }
    

    Finally to read the contents of the log...

    var_dump(json_decode(file_get_contents('/path/to-the-fatal.log')));
    

    Hope that helps!

    0 讨论(0)
提交回复
热议问题