php - PHP : How to first log an exception and then report by mail?

标签 php error-handling

我只是手工制作了一个复杂的订单流程,该流程很快就会上线。第一次,我想知道发生的任何错误,但是我也希望将它们记录下来。此answer建议先记录它们,然后再寄出它们,以确保安全,因为邮寄可能会失败。但是,当我捕获到异常时,不会将其记录下来;而当我没有捕获到异常时,我将无法发送电子邮件。

我的代码:

// convert errors to exceptions
function exception_error_handler($errno, $errstr, $errfile, $errline ) {
    throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}
set_error_handler("exception_error_handler");

try {
    // ... some code that might cause errors or throw exceptions
} catch(Exception $e) {
    log(...); // how can i make the error being logged here?
    mail(...); // afterwards i send an email
    throw $e; // i could re-throw it this way, but only after mailing it, cause it kills the process.
}

当然,我可以编写一个日志记录例程,但是我想PHP已经以一种我想使用的巧妙方式做到了。

另一个很棒的事情是拥有一些控制权,以确保每小时发出的错误电子邮件不超过x个。

总而言之,这似乎是一个非常普通的设置,但是我找不到合适的解决方案。还是这个想法有些愚蠢?

最佳答案

函数error_log()将自动将您的消息记录到Web服务器的error_log文件中。如果愿意,可以指定自定义日志文件还是默认的error_log文件。

因此,您可以像这样在error_log中记录一条简单的错误消息:

error_log("This is my error message");

或者在/var/log/web_error_log中记录异常消息:
} catch (Exception $e) {
    error_log($e->getMessage(), 3, '/var/log/web_error_log');
}

有关error_log的更多详细信息,请参见http://ca2.php.net/manual/en/function.error-log.php

关于php - PHP : How to first log an exception and then report by mail?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16465970/

相关文章:

ruby-on-rails - rails : "Permission denied -/tmp/cache/assets/development/sprockets/..."?

php - 计数表中的成员数不能超过一个

python - pyjnius 导入错误?运行 kivy 的示例 android 程序期间的问题

xcode - 在Xcode中打开unity3d项目时出现错误

c# - 在vs2013中,全局asa错误处理不再起作用了吗?

powershell - 如何创建Powershell自定义错误输出?

PHP 安全 - 清理和清理

php - 从另一个对象向 stdClass 对象添加属性

php - 如何将可变数据从数组传递到php中的fpdf

php - 对 pdo 中的非对象调用成员函数 query()