1. 程式人生 > >PHP錯誤日誌跟蹤記錄register_shutdown_function/set_error_handler/set_exception_handler

PHP錯誤日誌跟蹤記錄register_shutdown_function/set_error_handler/set_exception_handler

寫程式不可避免有錯誤,而除錯錯誤就很重要了,需要看錯誤資訊,錯誤發生的檔案、行號等,特別是對於線上的系統除錯,不能讓使用者看到錯誤資訊,這就需要把錯誤資訊記錄日誌裡。除了使用try catch,還可以使用set_error_handler

// 定義PHP程式執行完成後執行的函式
register_shutdown_function(['Debug', 'fatalError']);

// 設定一個使用者定義的錯誤處理函式
set_error_handler(["Debug", "appError"]);

//自定義異常處理。
set_exception_handler(['Debug'
, 'appException']);

下面簡單寫了一段錯誤記錄的小程式。

<?php
function myErrorHandler($errno, $errstr, $errfile, $errline){
    $f = fopen("log.txt", "a");
    fwrite($f, $errno."\n".$errstr."\n".$errfile."\n".$errline."\n");
    fwrite($f, var_export(debug_backtrace(), true));
    fclose($f);
    // error_log($errstr);
// 返回true 在前端不報錯,返回false就會在前端報錯 return true; } // 設定錯誤處理函式 set_error_handler("myErrorHandler", E_ALL); // 測試 function fe() { $a = 1/0; for($i=0;$i<10;$i++) { echo($i."<br/>"); } return 0; } fe();

參考:
http://php.net/manual/zh/book.errorfunc.php
http://php.net/manual/zh/ref.funchand.php