Pregunta

I have code that runs once daily and fputs() appends a daily log entry to a flat file in the format:

yyyy-mm-dd|log entry

This file is then displayed by a web page that fgets() and displays all records from oldest to newest.

What I need to do is change this write/read process so that:

A. Only the x most recent records are kept in the log file.

B. The output order is reversed with the most recent log entry displayed first.

If the order of the log file can be reversed with the write operation, then the read operation can remain unchanged.

If there is a better way to do this other than fputs and fgets, I am open to it.

Thanks

¿Fue útil?

Solución

The best way to do this, I think (although it is not the most memory efficient way) is this:

function writeLogEntry ($filePath, $str, $maxRecords) {
  $fileData = file($filePath); // Get file contents as array
  array_unshift($fileData, $str); // Add the log entry to the beginning
  if (count($fileData) > $maxRecords) { // Strip old records off
    $file = array_slice($fileData, 0, $maxRecords);
  }
  file_put_contents($filePath, $fileData); // Write file again
}

$logEntry = "yyyy-mm-dd|Something happened\n";

writeLogEntry('/path/to/file', $logEntry, 1000);

Using this approach, the file is kept in the order that you want it (newest first). However, if this file might be written to by more than one process at a time, you would need to implement some form of locking to avoid losing data.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top