【问题标题】:PHP: How to first log an exception and then report by mail?PHP:如何先记录异常,然后通过邮件报告?
【发布时间】:2013-05-10 03:00:58
【问题描述】:

我刚刚手工制作了一个即将上线的复杂订单流程。第一次,我想知道发生的任何错误,但我也希望它们被记录下来。这个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 封。

总而言之,这似乎是一个非常常见的设置,但我找不到现成的解决方案。还是这个想法有点愚蠢?

【问题讨论】:

    标签: php error-handling


    【解决方案1】:

    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

    【讨论】:

      猜你喜欢
      • 2012-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多