I want to insure that there are no race conditions introduced by using a custom PHP error handler. To that end I want to know if I can rely on error_log() or if I need to use some other file-locking method to insure errors are logged correctly.
How does the default PHP error handler work? Is it safe from race conditions?
For example, do I have to lock the file (which might cause errors to be lost in this simple version)
function log_error($message)
{
if(! $fp = @fopen('/path/to/error.log', 'a'))
{
return FALSE;
}
flock($fp, LOCK_EX);
fwrite($fp, $message);
flock($fp, LOCK_UN);
fclose($fp);
return TRUE;
}
or can I just call error_log?
error_log($message, 0);
It is entirely safe to just delete the php. log file. It will be auto-created the next time it is needed.
The location of the error log file itself can be set manually in the php. ini file. On a Windows server, in IIS, it may be something like "'error_log = C:\log_files\php_errors. log'" in Linux it may be a value of "'/var/log/php_errors.
What Does Error Log Mean? In computer science, an error log is a record of critical errors that are encountered by the application, operating system or server while in operation. Some of the common entries in an error log include table corruption and configuration corruption.
PHP error_log() Function The error_log() function sends an error message to a log, to a file, or to a mail account.
You can find the source for the error_log implementation in ext/standard/basic_functions.c
. You'll see that it pretty much just calls any defined logger. If you're concerned about some kind of data munging by error_log itself due to multiple concurrent calls, no need to be. Or at least, no more concerned than most any other piece of PHP code. If your custom logger is writing to a file, you'll need to implement file locking yourself. Concurrent calls to error_log (across processes) is a pretty common scenario.
edit
You are almost certainly better off using the built in logging available via error_log
.
The PHP flock implementation uses advisory locking, which makes it possible for other processes to simply ignore the lock and write. Additionally, within your own processes you will end up being IO
bound as the process waits to acquire the lock. By using error_log
, you can configure syslog logging. Syslog is asynchronous so you avoid the lock acquisition, and it's also backed (generally) by a kernel buffer which will allow any syslog daemon to write consecutive records without a problem.
Having implemented high throughput logging at a number of companies I would strongly recommend configuring either syslog or going with something like scribe. My 2c.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With