将旧内容读入$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;
}
答案 0 :(得分:2)
对于日志记录,您应该使用:
file_put_contents($filename, $content, FILE_APPEND|LOCK_EX);
这不仅减少了代码,而且还负责锁定文件(没有并发访问和覆盖附加内容)。
答案 1 :(得分:0)
怎么样:
$contents = file_get_contents($file);
$contents = $string . $contents;
... fwrite();
答案 2 :(得分:0)
尝试替换此代码
$this->fp = fopen($this->filename, "w+");
这一个:
$this->fp = fopen($this->filename, "a+");