***CI異常記錄到日誌:CodeIgniter中設計一個全域性exceptionhook

suboysugar發表於2015-06-23

在CodeIgniter中,當發生異常時,經常要通知系統管理員,因此有必要在全域性的高度上 
捕捉異常,因此可以寫一個hook, 
比如在config目錄的hook.php中,加入: 

$hook[`pre_controller`][] = array( 
                   `class`    => `ExceptionHook`, 
                   `function` => `SetExceptionHandler`, 
                   `filename` => `ExceptionHook.php`, 
                   `filepath` => `hooks` 
                  ); 

然後在應用的hook目錄下,編寫ExceptionHook.php 

<?php 

class ExceptionHook 
{ 
  public function SetExceptionHandler() 
  { 
    set_exception_handler(array($this, `HandleExceptions`)); 
  } 
   
  public function HandleExceptions($exception) 
  { 

  $msg =`Exception of type ``.get_class($exception).`` occurred with Message: `.$exception->getMessage().` in File `.$exception->getFile().` at Line `.$exception->getLine(); 

        $msg .="
 Backtrace 
"; 
$msg .=$exception->getTraceAsString(); 

        log_message(`error`, $msg, TRUE); 

        
mail(`dev-mail@example.com`, `An Exception Occurred`, $msg, `From: test@example.com`);    


} 
?>

 

如何聯絡我:【萬里虎】www.bravetiger.cn
【QQ】3396726884 (諮詢問題100元起,幫助解決問題500元起)
【部落格】http://www.cnblogs.com/kenshinobiy/


相關文章