简体   繁体   English

PHP函数error_log()是否可以安全使用?

[英]Is the PHP function error_log() safe to use?

I want to insure that there are no race conditions introduced by using a custom PHP error handler . 我想确保使用自定义PHP错误处理程序不会引入竞争条件。 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. 为此,我想知道我是否可以依赖于error_log()或者是否需要使用其他一些文件锁定方法来确保正确记录错误。

How does the default PHP error handler work? 默认的PHP错误处理程序如何工作? 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?

error_log($message, 0);

You can find the source for the error_log implementation in ext/standard/basic_functions.c . 您可以在ext/standard/basic_functions.c找到error_log实现的源代码。 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. 如果您担心由于多个并发调用而错误地由error_log本身进行某种类型的数据,则不需要。 Or at least, no more concerned than most any other piece of PHP code. 或者至少,没有比大多数其他PHP代码更关注。 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. 并发调用error_log(跨进程)是一种非常常见的情况。

edit 编辑

You are almost certainly better off using the built in logging available via error_log . 使用error_log提供的内置日志记录几乎肯定会更好。

The PHP flock implementation uses advisory locking, which makes it possible for other processes to simply ignore the lock and write. PHP flock实现使用建议锁定,这使得其他进程可以简单地忽略锁定和写入。 Additionally, within your own processes you will end up being IO bound as the process waits to acquire the lock. 此外,在您自己的进程中,当进程等待获取锁时,您将最终成为IO绑定。 By using error_log , you can configure syslog logging. 通过使用error_log ,您可以配置syslog日志记录。 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. Syslog是异步的,因此您可以避免锁定获取,并且它也(通常)由内核缓冲区支持,这将允许任何syslog守护程序写入连续记录而不会出现问题。

Having implemented high throughput logging at a number of companies I would strongly recommend configuring either syslog or going with something like scribe. 在许多公司实施了高吞吐量日志记录之后,我强烈建议您配置syslog或使用scribe之类的东西。 My 2c. 我的2c。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM