How to catch errors and exceptions to send to DB with PHP? [duplicate]

2

How can we capture all errors and exceptions generated at runtime in PHP, sending to the database to later make a log page organized?

Currently I redirect every request to index.php, treating the URLs in a friendly way with an MVC template, so in that case it would be possible to register some function / callback directly in index.php avoiding having to call this function / callback in all the files, classes and functions?

    
asked by anonymous 16.10.2014 / 02:22

1 answer

1

Caution: minimum PHP 5.2

 <?php


 // ========================
  // Log PHP
 // ========================


 // Chamada quando vai ter Error
 function call_fatal_handler()
 {

     // Déf.
     $err_file = "nao_sei";
     $err_str  = "shutdown";
     $err_no   = E_CORE_ERROR;
     $err_line = 0;

     // Qual e a ultima error?
     $error = error_get_last();

     // Se tem, podems ler dados
     if( $error !== NULL)
     {
         $err_no   = $error["type"];        // Tipo
         $err_file = $error["file"];    // O documento
        $err_line = $error["line"];     // a linha
        $err_str  = $error["message"];  // o mensagem de error

        // Aqui, podemos criar um email, salvar um BDD, ....
        $content = call_format_error( $err_no, $err_str, $err_file, $err_line );
        echo "<br>".$content;
   }
 }

 function call_format_error( $errno, $errstr, $errfile, $errline )
 {

   $trace = print_r( debug_backtrace( false ), true );

   $content = "<b>Error: </b>".$errstr."<br>\n";
   $content .= "<b>Errno: </b>".$errno."<br>\n";
   $content .= "<b>File: </b>".$errfile."<br>\n";
   $content .= "<b>Line: </b>".$errline."<br>\n";
   $content .= "<b>Trace: </b><pre>".$trace."</pre><br>\n";


   return $content;
 }  
 //-------------------------------------------------------------------------
 register_shutdown_function( "call_fatal_handler" );

 echo "Ola";
 //$a = strstr();
 echo "Display".$a;         // $a nao tem definiçao

 ?>

I've forgotten a VERY important point, if instead of displaying the result, you try to do an insert in a BDD, it will not work. Because as the function is called at the end of the script, at this point the connection to the database is closed. The solution is to make another "sql_open" before your INSERT.

    
17.10.2014 / 15:59