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

后端 未结 11 2141
無奈伤痛
無奈伤痛 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: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!

提交回复
热议问题