gremo
gremo

Reputation: 48919

Why i can't prepend a line to my log file?

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

Upvotes: 0

Views: 308

Answers (3)

Christopher Pelayo
Christopher Pelayo

Reputation: 802

try to replace this code

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

with this one:

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

Upvotes: 0

favoretti
favoretti

Reputation: 30197

How about:

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

Upvotes: 0

mario
mario

Reputation: 145482

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).

Upvotes: 2

Related Questions