PHP函数error_log()是否可以安全使用? [英] Is the PHP function error_log() safe to use?

查看:121
本文介绍了PHP函数error_log()是否可以安全使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想确保没有通过使用自定义PHP错误处理程序引入任何竞争条件。为此,我想知道是否可以依靠 error_log()还是我需要依靠使用其他一些文件锁定方法来确保正确记录错误。

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.

默认的PHP错误处理程序如何工作?

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;
}

或者我可以只调用error_log吗?

or can I just call error_log?

error_log($message, 0);


推荐答案

您可以在 ext / standard / basic_functions.c 。您会发现它几乎可以调用任何已定义的记录器。如果您担心由于多个并发调用而使error_log本身进行某种数据处理,则无需这样做。或者至少,没有比大多数其他PHP代码更令人关注的了。如果您的自定义记录器正在写入文件,则需要自己实施文件锁定。并发调用error_log(跨进程)是一种很常见的情况。

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.

编辑

几乎可以肯定,使用通过 error_log 提供的内置日志记录会更好code>

You are almost certainly better off using the built in logging available via error_log.

PHP flock实现使用建议性锁定,这使得其他进程可以简单地忽略该锁定并进行写入。另外,在您自己的进程中,当进程等待获取锁时,您最终将受到 IO 的约束。通过使用 error_log ,可以配置系统日志记录。 Syslog是异步,因此避免了锁获取,它还(通常)由内核缓冲区支持,该缓冲区将允许任何syslog守护程序毫无问题地写入连续记录。

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.

已经在许多公司实现了高吞吐量日志记录,我强烈建议配置syslog或使用类似scribe的东西。我的2c。

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.

这篇关于PHP函数error_log()是否可以安全使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆