PHP日志捕获到异常


PHP log caught exception

PHP只记录未捕获的异常。我还想记录我的所有捕获的异常。

示例1

try {
    $book->getBook();
} catch( Exception $e ) {
    error_log( $e );
    $error = 'A problem occurred getting your book'
}

这很好,但我不想一直写error_log

因此,我扩展了Exception类,如下所示:

示例2

class ExceptionLog extends Exception {
    public function __construct( $message, $code = 0, Exception $previous = null ) {
        error_log( $this );
        parent::__construct($message, $code, $previous);
    }
}

然后我可以做:

try {
    $book->getBook();
} catch( ExceptionLog $e ) {
    $error = 'A problem occurred getting your book'
}

这里的一个问题是,记录的消息略有不同。在第一个示例中,日志条目为:

[01-Jan-2016 19:24:51 Europe/London] PHP Fatal error:  Uncaught exception 'Exception' with message 'Could not get book' in book.php:39

在第二个示例中,消息被省略:

[01-Jan-2016 19:24:51 Europe/London] exception 'ExceptionLog' in book.php:39

唯一的方法是访问父Exception类的属性并手动生成错误日志字符串吗?

您是否注意到您的自定义错误消息从未被使用过?

这有两个原因:在"ExceptionLog"类构造函数中,您在调用父"Exception"类构造函数之前记录错误,并且从未向"ExceptionLog"类构造函数提供自定义错误消息。

您的ExceptionLog类应该如下所示:

class ExceptionLog extends Exception {
  public function __construct($message, $code = 0, Exception $previous = null) {
    parent::__construct($message, $code, $previous);
    error_log($this);
  }
}

然后,在"Book"类中,您有一个方法"getBook()",它抛出自定义错误(注意,我明确抛出错误是为了演示):

class Book {
  public function getBook() {
    throw new ExceptionLog('A problem occurred getting your book');
  }
}

查看如何将自定义错误消息传递给"ExceptionLog"类构造函数?然后您可以创建"Book"类的实例:

$book = new Book();

并将您的尝试/捕获更改为以下内容:

try {
  $book->getBook();
} catch (ExceptionLog $e) {
  //Custom error message is already defined
  //but you can still take other actions here
}

这应该会产生一个类似于我在"php_error.log"文件中看到的错误:

[01-Jan-2016 21:45:28 Europe/Berlin] exception 'ExceptionLog' with message 'A problem occurred getting your book' in /Applications/MAMP/htdocs/php_exception_test/index.php:13