为什么我无法在日志文件中添加一行?
将旧内容读取到 $content
中,然后写入 $string 。 $content
回到文件中:不起作用,新消息打印在文件末尾。
Logger
类中的相关方法:
public function __construct($filename)
{
$this->filename = $filename;
$this->fp = fopen($this->filename, "w+");
if (!$this->fp) throw new Exception("Errore nel file: " . $this->filename);
}
protected function log($severity, $message)
{
$string = sprintf("[%s] (%s): %s", $severity, date('d/m/Y H:i:s'), $message);
$content = !filesize($this->filename)? '' :
fread($this->fp, filesize($this->filename));
fwrite($this->fp, $string . $content . "\n");
return $message;
}
Read the old content into $content
, then write $string . $content
back into the file: not working, new messages are printed at the end of the file.
Relevant methods in the Logger
class:
public function __construct($filename)
{
$this->filename = $filename;
$this->fp = fopen($this->filename, "w+");
if (!$this->fp) throw new Exception("Errore nel file: " . $this->filename);
}
protected function log($severity, $message)
{
$string = sprintf("[%s] (%s): %s", $severity, date('d/m/Y H:i:s'), $message);
$content = !filesize($this->filename)? '' :
fread($this->fp, filesize($this->filename));
fwrite($this->fp, $string . $content . "\n");
return $message;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对于日志记录,您应该使用:
这不仅可以减少代码,而且还可以锁定文件(没有并发访问和覆盖附加内容)。
For logging you should use:
That's not only less code, but also takes care of locking the file (no concurrent access and overwriting of the appended content).
怎么样:
How about:
尝试
用以下代码替换此代码:
try to replace this code
with this one: