为什么我无法在日志文件中添加一行?

发布于 2024-12-19 13:55:18 字数 696 浏览 0 评论 0原文

将旧内容读取到 $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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

给我一枪 2024-12-26 13:55:18

对于日志记录,您应该使用:

file_put_contents($filename, $content, FILE_APPEND|LOCK_EX);

这不仅可以减少代码,而且还可以锁定文件(没有并发访问和覆盖附加内容)。

For logging you should use:

file_put_contents($filename, $content, FILE_APPEND|LOCK_EX);

That's not only less code, but also takes care of locking the file (no concurrent access and overwriting of the appended content).

我很OK 2024-12-26 13:55:18

怎么样:

$contents = file_get_contents($file);
$contents = $string . $contents;
... fwrite();

How about:

$contents = file_get_contents($file);
$contents = $string . $contents;
... fwrite();
天气好吗我好吗 2024-12-26 13:55:18

尝试

$this->fp = fopen($this->filename, "w+");

用以下代码替换此代码:

$this->fp = fopen($this->filename, "a+");

try to replace this code

$this->fp = fopen($this->filename, "w+");

with this one:

$this->fp = fopen($this->filename, "a+");
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文