Reputation: 385
Hopefully someone here can help me out - basically I have a logging class that I'm updating (Made it ages ago), and I want to make sure it logs messages under 98-99% of circumstances. However right now it doesn't handle exit()s, it basically just writes to a file (Opening, writing, and closing) every time a message/error is sent to the logger.
What would be the best way to handle exit()s, and be efficient in terms of disk writes? Right now I'm looking at __destruct in the logger class (With fopen, fwrite, and fclose being called in it), however I'm not quite sure if this is safe, or efficient.
Edit: What about set_error_handler()? I remember reading years ago that this was very slow and not very good for custom errors/messages (Like SQL issues)
Upvotes: 3
Views: 1405
Reputation: 2912
If you wish to log something when your script ends, you should take a look at PHP's register_shutdown_function()
:
function shutdown()
{
// .. log code here.
}
register_shutdown_function('shutdown');
You should avoid using the __destruct()
method as there is no guarantee that it will be called when you expect it to be called.
You could also take a look at PHP's built in error_log()
method to write the contents to the actual PHP error log file (this is possibly more reliable than writing your own logger).
References:
http://php.net/manual/en/function.register-shutdown-function.php
http://php.net/manual/en/function.error-log.php
Upvotes: 6
Reputation: 2947
I always use some global function, e.g.
function BeforeExit () {
//do stuff like logging
exit;
}
Upvotes: 1