Pergunta

tentando depurar PHP usando seu atual linha-somente mensagens de erro padrão é horrível. Como posso obter PHP para produzir um backtrace (rastreamento de pilha) quando os erros são produzidos?

Foi útil?

Solução

Xdebug imprime uma tabela backtrace em erros, e você não tem que escrever qualquer código PHP para implementá-lo.

desvantagem é que você tem que instalá-lo como uma extensão do PHP.

Outras dicas

O meu script para instalar um manipulador de erro que produz um registo de chamadas:

<?php
function process_error_backtrace($errno, $errstr, $errfile, $errline, $errcontext) {
    if(!(error_reporting() & $errno))
        return;
    switch($errno) {
    case E_WARNING      :
    case E_USER_WARNING :
    case E_STRICT       :
    case E_NOTICE       :
    case E_USER_NOTICE  :
        $type = 'warning';
        $fatal = false;
        break;
    default             :
        $type = 'fatal error';
        $fatal = true;
        break;
    }
    $trace = array_reverse(debug_backtrace());
    array_pop($trace);
    if(php_sapi_name() == 'cli') {
        echo 'Backtrace from ' . $type . ' \'' . $errstr . '\' at ' . $errfile . ' ' . $errline . ':' . "\n";
        foreach($trace as $item)
            echo '  ' . (isset($item['file']) ? $item['file'] : '<unknown file>') . ' ' . (isset($item['line']) ? $item['line'] : '<unknown line>') . ' calling ' . $item['function'] . '()' . "\n";
    } else {
        echo '<p class="error_backtrace">' . "\n";
        echo '  Backtrace from ' . $type . ' \'' . $errstr . '\' at ' . $errfile . ' ' . $errline . ':' . "\n";
        echo '  <ol>' . "\n";
        foreach($trace as $item)
            echo '    <li>' . (isset($item['file']) ? $item['file'] : '<unknown file>') . ' ' . (isset($item['line']) ? $item['line'] : '<unknown line>') . ' calling ' . $item['function'] . '()</li>' . "\n";
        echo '  </ol>' . "\n";
        echo '</p>' . "\n";
    }
    if(ini_get('log_errors')) {
        $items = array();
        foreach($trace as $item)
            $items[] = (isset($item['file']) ? $item['file'] : '<unknown file>') . ' ' . (isset($item['line']) ? $item['line'] : '<unknown line>') . ' calling ' . $item['function'] . '()';
        $message = 'Backtrace from ' . $type . ' \'' . $errstr . '\' at ' . $errfile . ' ' . $errline . ': ' . join(' | ', $items);
        error_log($message);
    }
    if($fatal)
        exit(1);
}

set_error_handler('process_error_backtrace');
?>

Advertência: é impotente para afetar vários 'PHP Erros fatais' , desde Zend em sua decidida sabedoria que estes seriam ignorar set_error_handler(). Então você ainda obter inúteis final,-only-localização erros com aqueles.

PHP Erro

Isto é melhor do relatório de erros para PHP escrito em PHP. Sem extensões extras são necessários!

É trivial para uso onde todos os erros são exibidos no navegador para normal, solicitações AJAXy (em estado de pausa). Em seguida, todos os erros fornece um contexto backtrace e código em todo o rastreamento de pilha, incluindo argumentos de função, variáveis ??de servidor.

Tudo que você precisa fazer é incluir um único arquivo e chamar a função (no início do seu código), por exemplo.

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

Veja as imagens:

PHP Erro | melhorar Relatório de erros para PHP - screenshot do registo de chamadas Erro PHP | melhorar Relatório de erros para PHP - screenshot do registo de chamadas Erro PHP | melhorar Relatório de erros para PHP - screenshot do registo de chamadas

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

O meu fork (com correções extras): https://github.com/kenorb-contrib / PHP-Error

Debug PHP classe

A classe completa depurador PHP, com suporte para Exception, erros, alertas (de usuário), linhas de código e bandeiras de destaque.

Exemplo de utilização:

 <?php
        include( dirname(dirname(__FILE__))  . '/src/Debug.php' );
        //Catch all
        Debug::register();

        //Generate an errors
        if( this_function_does_not_exists( ) )
        {
            return false;
        }
    ?>

Tratamento de erros no PHP

O exemplo abaixo demonstra a manipulação das excepções internos, desencadeando os erros e a sua manipulação com uma função definida pelo utilizador:

caminho mais curto (PHP):

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

caminho mais longo (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;
}

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

Nota: Você só pode ter uma exceção de erro de cada vez. Quando você chamar a função set_error_handler () irá retornar o nome do manipulador de erro de idade. Você pode armazenar isso e chamá-lo de si mesmo a partir de seu manipulador de erro -. Permitindo-lhe ter vários manipuladores de erro


XDebug

Para a solução mais avançada, você pode usar XDebug extensão para PHP.

Por padrão, quando XDebug é carregado, ele deve mostrar-lhe automaticamente o registo de chamadas em caso de qualquer erro fatal. Ou você rastrear em arquivo (xdebug.auto_trace) para ter um grande registo de chamadas de todo o pedido ou fazer o profiling (xdebug.profiler_enable) ou outras configurações . Se o arquivo de rastreamento é muito grande, você pode usar xdebug_start_trace () e xdebug_stop_trace () para despejar o traço parcial.

Instalação

Usando PECL:

pecl install xdebug

No Linux:

sudo apt-get install php5-xdebug

No Mac (com Homebrew):

brew tap josegonzalez/php
brew search xdebug
php53-xdebug

Exemplo de configuração mina:

[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

Com Devel ativado:

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

função acima irá registrar os backtraces em cada erro no arquivo temporário (/tmp/drupal_debug.txt por padrão).

Ou localize o arquivo via:. drush eval "echo file_directory_temp() . '/drupal_debug.txt'

Sem Devel habilitado, use abordagem velha escola: var_dump(debug_backtrace()); vez de dd()

.

Eu apenas tentei definindo uma variável de sessão que contém o conteúdo de debug_backtrace () na linha de ofender, então imprimi-lo usando register_shutdown_function (). Trabalhou como um encanto.

Você pode usar debug_backtrace

Como extensões php depuração, há Xdebug e PHP DBG . Cada um tem suas vantagens e desvantagens.

Isto é como fazê-lo:

set_error_handler(function($errorType){
    if(error_reporting() & $errorType){
        ?><pre><?
        debug_print_backtrace();
        ?></pre><?
    }
}) ;

Ele requer PHP 5.3+ uma vez que utiliza um fecho. Se você precisa diminuir o suporte PHP apenas converter o fechamento de uma função normal.

$backtrace = debug_backtrace();

i escreveu um pequeno artigo sobre backtracing um tempo atrás

set_error_handler() + debug_backtrace() + debug_print_backtrace() em PHP5

Se você não pode instalar um depurador, em seguida, usar essa função sorrounding o erro fatal para obter o "pilha fatal". Verifique o código e exemplo abaixo que explica melhor como usá-lo:

// 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;
    }
}

Aqui está um exemplo de como usá-lo:

// 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
}

Finalmente, para ler o conteúdo do log ...

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

Espero que ajude!

PHP depurador também faz um traço semelhante de volta para PHP Erro com mais opções.
Se você quiser, pode facilmente fazer o seu próprio com set_error_handler e 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
    }
}

Além disso, note que para pilhas internas no backtrace algumas das teclas não será definido. Certifique-se de verificar se a exist chave antes de fazer alguma coisa com isso, se você tem todos os erros em:)

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top