我只是手工制作了一个复杂的订单流程,该流程很快就会上线。第一次,我想知道发生的任何错误,但是我也希望将它们记录下来。此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/