《PHP學習:php 自定義錯誤日志實例詳解》要點:
本文介紹了PHP學習:php 自定義錯誤日志實例詳解,希望對您有用。如果有疑問,可以聯系我們。
PHP實例php 自定義錯誤日志
PHP實例?項目中需要對定義錯誤日志及時處理, 那么就需要修改自定義錯誤日志的輸出方式(寫日志、發郵件、發短信)
PHP實例? 一. register_shutdown_function(array('phperror','shutdown_function')); //定義PHP程序執行完成后執行的函數
PHP實例 函數可實現當程序執行完成后執行的函數,其功能為可實現程序執行完成的后續操作.程序在運行的時候可能存在執行超時,或強制關閉等情況,但這種情況下默認的提示是非常不友好的,如果使用register_shutdown_function()函數捕獲異常,就能提供更加友 好的錯誤展示方式,同時可以實現一些功能的后續操作,如執行完成后的臨時數據清理,包括臨時文件等.
PHP實例 可以這樣理解調用條件:
PHP實例 1、當頁面被用戶強制停止時
2、當程序代碼運行超時時
3、當PHP代碼執行完成時,代碼執行存在異常和錯誤、警告
PHP實例? 二. set_error_handler(array('phperror','error_handler')); // 設置一個用戶定義的錯誤處理函數
PHP實例 通過 set_error_handler() 函數設置用戶自定義的錯誤處理程序,然后觸發錯誤(通過 trigger_error()):
PHP實例?三. set_exception_handler(array('phperror','appException')); //自定義異常處理
PHP實例 定義異常拋出的數據格式.
PHP實例
class phperror{
//自定義錯誤輸出方法
public static function error_handler($errno, $errstr, $errfile, $errline){
$errtype = self::parse_errortype($errno);
$ip = $_SERVER['REMOTE_ADDR'];//這里簡單的獲取客戶端IP
//錯誤提示格式自定義
$msg = date('Y-m-d H:i:s')." [$ip] [$errno] [-] [$errtype] [application] {$errstr} in {$errfile}:{$errline}";
//自定義日志文件的路徑
$logPath = 'logs/app.log';
//寫操作,注意文件大小等控制
file_put_contents($logPath, $msg, FILE_APPEND);
}
//系統運行中的錯誤輸出方法
public static function shutdown_function(){
$lasterror = error_get_last();//shutdown只能抓到最后的錯誤,trace無法獲取
$errtype = self::parse_errortype($lasterror['type']);
$ip = $_SERVER['REMOTE_ADDR'];//這里簡單的獲取客戶端IP
//錯誤提示格式自定義
$msg = date('Y-m-d H:i:s')." [$ip] [{$lasterror['type']}] [-] [$errtype] [application] {$lasterror['message']} in {$file}:{$lasterror['line']}";
//自定義日志文件的路徑
$logPath = 'logs/app.log';
//寫操作,注意文件大小等控制
file_put_contents($logPath, $msg,FILE_APPEND);
}
//自定義異常輸出
public static function appException($exception) {
echo " exception: " , $exception->getMessage(), "/n";
}
private static function parse_errortype($type){
switch($type){
case E_ERROR: // 1
return 'Fatal Error';
case E_WARNING: // 2
return 'Warning';
case E_PARSE: // 4
return 'Parse error';
case E_NOTICE: // 8
return 'Notice';
case E_CORE_ERROR: // 16
return 'Core error';
case E_CORE_WARNING: // 32
return 'Core warning';
case E_COMPILE_ERROR: // 64
return 'Compile error';
case E_COMPILE_WARNING: // 128
return 'Compile warning';
case E_USER_ERROR: // 256
return 'User error';
case E_USER_WARNING: // 512
return 'User warning';
case E_USER_NOTICE: // 1024
return 'User notice';
case E_STRICT: // 2048 //
return 'Strict Notice';
case E_RECOVERABLE_ERROR: // 4096
return 'Recoverable Error';
case E_DEPRECATED: // 8192
return 'Deprecated';
case E_USER_DEPRECATED: // 16384
return 'User deprecated';
}
return $type;
}
}
PHP實例感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
轉載請注明本頁網址:
http://www.snjht.com/jiaocheng/2812.html