zl程序教程

您现在的位置是:首页 >  工具

当前栏目

***CI异常记录到日志:CodeIgniter中设计一个全局exception hook

日志异常 一个 设计 记录 全局 Exception CI
2023-09-27 14:24:03 时间

在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 .="\r\n Backtrace \r\n"; 
$msg .=$exception->getTraceAsString(); 

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

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


} 
?>