开发者

How to keep last n number of line from log file in php

I want to delete all lines from old log files and keep fresh 开发者_Go百科50 lines which is at the bottom.

How can I do something like this and if possible can we change the orientation of these lines,

normal input

111111
2222222
3333333
44444444
5555555

output like

555555
4444444
3333333
22222
111111

To see the fresh log at top and 50 or 100 lines only.

How to join it with this one?

// set source file name and path 
$source = "toi200686.txt"; 
// read raw text as array 
$raw = file($source) or die("Cannot read file"); 
// join remaining data into string 
$data = join('', $raw); 
// replace special characters with HTML entities 
// replace line breaks with <br />  
$html = nl2br(htmlspecialchars($data)); 

It made the output as an HTML file. So how will your code run with this?


$lines = file('/path/to/file.log'); // reads the file into an array by line
$flipped = array_reverse($lines); // reverse the order of the array
$keep = array_slice($flipped,0, 50); // keep the first 50 elements of the array

from there you can dow whatever with $keep. for example if you want to spit it back out:

echo implode("\n", $keep);

or

file_put_contents('/path/to/file.log', implode("\n", $keep));


This is a bit more complex, but uses less memory as the entire file is not loaded into the array. Basically, it keeps an N length array, and pushes on new lines as they are read from the file while shifting one off. Because the newline is returned by fgets, you can simply do an implode to see your N lines, even with the padded array.

<?php
$handle = @fopen("/path/to/log.txt", "r");
$lines = array_fill(0, $n-1, '');

if ($handle) {
    while (!feof($handle)) {
        $buffer = fgets($handle);
        array_push($lines, $buffer);
        array_shift($lines);
    }
    fclose($handle);
}

print implode("",$lines);
?>

Just showing another way to do things, especially if you don't have tail at your disposal.


This would work for truncating the log file:

exec("tail -n 50 /path/to/log.txt", $log);
file_put_contents('/path/to/log.txt', implode(PHP_EOL, $log));

This will return the output from tail in $log and write it back to the log file.


Optimal form is:

<?
print `tail -50 /path/to/file.log`;
?>


this method use associative array to store only $tail number of lines each time. It does not fill the whole array with all lines

$tail=50;
$handle = fopen("file", "r");
if ($handle) {
    $i=0;
    while (!feof($handle)) {
        $buffer = fgets($handle,2048);
        $i++;
        $array[$i % $tail]=$buffer;
    }
    fclose($handle);
    for($o=$i+1;$o<$i+$tail;$o++){
        print $array[$o%$tail];
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜