0

I have been searching around for a faster method to accomplish prepending a log file. Below are the current two methods I know of. I have also explored appending the file normally and then reading the file in reverse to display but (without testing) I think this would take longer once the file gets to a reasonable size. What is the quickest method to prepend a log file?

$start1 = microtime(true);
log1();
$end1 = microtime(true);
$start2 = microtime(true);
// log2();
$end2 = microtime(true);

$t1 = $end1-$start1;
$t2 = $end2-$start2;

function log1(){
    $stamp = date("Y-m-d @ h:i:sa");
    $data = ($stamp." this has been a test of 1");
    $data .= file_get_contents('./test.log');
    file_put_contents('./test.log', "\r\n\r\n".$data);
}

EDIT: updated log2()

function log2(){
    $stamp = date("Y-m-d @ h:i:sa");
    $write = $stamp.'this has been a test of 2'.PHP_EOL;
    $file = './test.log';
    $handler = fopen($file, 'r+');
    $len = strlen($write);
    $final_len = filesize($file)+$len;
    $cache_old = fread($handler, $len);
    rewind($handler);
    $i=1;
    while(ftell($handler) < $final_len){
        fwrite($handler, $write);
        $write = $cache_old;
        $cache_old = fread($handler, $len);
        fseek($handler, $i * $len);
        $i++;
    }
    fclose($handler);

}
FamousAv8er
  • 2,345
  • 2
  • 9
  • 27
  • 1
    Just being pedantic, but if you're putting it at the beginning of the file, you're prepending, not appending. – yaakov Dec 17 '19 at 19:15
  • @YaakovAinspan ya know I had just seen this on another post and made the same mistake...haha – FamousAv8er Dec 17 '19 at 19:17
  • _the second will always clear the contents of my file so it does not work_ - https://stackoverflow.com/a/3332403/296555. Does this help? – waterloomatt Dec 17 '19 at 19:17
  • @waterloomatt this did help...however the first function seems to be more efficient overall – FamousAv8er Dec 17 '19 at 19:27
  • Just append to the file, reading in reverse should not be a problem. – lbrandao Dec 17 '19 at 19:51
  • There's no efficient way to prepend to a file. No common filesystems provide operations to insert into a file, you can only overwrite or append. Prepending always requires copying the contents to open up space. – Barmar Dec 17 '19 at 20:11
  • In my experience, with log files, you don't read it often, so it shouldn't be a problem for you when you read the file in reverse. If you need to read this file often, you may ask yourself if use a database (sql or nosql) is a option. ELK stack is a good option for this. – Felippe Duarte Dec 17 '19 at 20:17
  • Can you elaborate what exactly is your aim here? Why do you want to prepend instead of append? Is it solely for the purpose of reverse display somewhere? – ArSeN Dec 17 '19 at 23:55
  • @ArSeN yes it is solely for display purposes. – FamousAv8er Dec 18 '19 at 14:50

0 Answers0