开发者

Logging fatal/parse errors in PHP5

开发者 https://www.devze.com 2022-12-29 11:29 出处:网络
I\'m writing an error logging service that will be integrated into websites running on my server, that will email me error batches, etc.

I'm writing an error logging service that will be integrated into websites running on my server, that will email me error batches, etc.

So I've been trying to find out if there's a way t开发者_开发知识库o handle fatal and parse errors, however not using the tricks to handle it in PHP code (output buffer, shutdown function). I'm quite happy to write some C code or something to handle it outside of my PHP code. I would also like to issue a redirect if possible (my sites use output buffering so there shouldn't be any headers sent).

I'm pretty sure this could be done with a PHP module, but I've never written one and have no idea where to start.


There is no way to catch a fatal or parse error in PHP. But..

In 5.2, they added error_get_last(). You can call it inside a shutdown function and perform logging. An untested 5.3 example for firing off a mail when there was a fatal error:

<?php
register_shutdown_function(function(){
    $err = error_get_last();
    if(is_array($err) && array_key_exists('type', $err) $err['type'] > 0 
      && ($err['type'] == E_ERROR || $err['type'] == E_PARSE) {
        error_log("Oh noes, a fatal: " . var_export($err, true), 1, 'fatals@example.com');
    }
});

(You'll need to use a callback if you aren't on 5.3 and can't do anonymous functions.)

Unfortunately because this is handled in a shutdown function, chances are that headers have already been emitted and you might not be able to provide anything useful to the user. This depends on the rest of the application, though, so it might work out for you. Try it and find out!


By default all errors are passed to web server error log but you can change it in php.ini by specifying path to your own file via error_log setting. So what is left to do is to write some separate script/app to parse / send data / truncate log file every day / whatever and run it as cron job.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号