reyy
reyy

Reputation: 69

PHP/Javascript - read only added lines in real time from huge log file

i'm searching for something like this for days and i couldn't find anything. My knowledge of Javascript is very limited so i'm here to ask you guys to help me out.

Basically i need a PHP script which read a huge log .txt file in real time (Without page refresh) which is constantly updated. But it should read only latest lines which has been written to the file since i open up my .php page. This means that if i refresh my page it must starts from the beginning to load new lines.

I got this now (catchlogs.php):

$f = fopen("test.txt", 'r');

$maxLineLength = 1000;
$linesToRead = 1;

fseek($f, -$maxLineLength*$linesToRead, SEEK_END);
$res = array();

while (($buffer = fgets($f, $maxLineLength)) !== false) {
    $res[] = $buffer;
}

$content = array_slice($res, -$linesToRead);

for($i = 0; $i < $linesToRead; $i++) {
    echo $content[$i]."<br>";
}

And this (logreader.php):

<script type="text/javascript">
var auto_refresh = setInterval(
(function () {
    $("#logreader").load("catchlogs.php");
}), 1000);
</script>
<div id="logreader"></div>

This load the latest 10 lines but slice them every second. I don't need a limited amout of lines, i need a script that starts to load lines from the last one until i refresh the page (or close it or whatever).

Thank you!

Upvotes: 0

Views: 1596

Answers (2)

Mihai Zinculescu
Mihai Zinculescu

Reputation: 389

Here is your script, tested by me.

catchlogs.php

define("LOG_FILE", "test.txt");

/* function to count lines from a file */
function count_line_numbers($file){
    $linecount = 0;
    $handle = fopen($file, "r");
    while(!feof($handle)){
      $line = fgets($handle);
      $linecount++;
    }
    fclose($handle);
    // return results
    return $linecount;
}

/* show all lines from line */
function logs_started_by_line($file, $xline = 0){
    $currline = 0;
    $handle = fopen($file, "r");
    while(!feof($handle)){
        $line = fgets($handle, 2000);
        if($xline <= $currline)
            echo $line."<br>";
        $currline++;
    }
    fclose($handle);
}



session_start();

if(isset($_GET['do'])){ $_SESSION['start'] = -1; }

if( ! isset($_SESSION['start']) || $_SESSION['start'] == -1 ){
    $_SESSION['start'] = count_line_numbers(LOG_FILE);
}

logs_started_by_line( LOG_FILE, $_SESSION['start'] );

logreader.php

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
    $("#logreader").load("catchlogs.php?do=refresh");
    var auto_refresh = setInterval(
    (function () {
        $("#logreader").load("catchlogs.php");
    }), 1000);
});

</script>
<div id="logreader"></div>

test.txt

line 1
new log
something..

Upvotes: 1

Miraage
Miraage

Reputation: 3464

The most flawless solution - use Node-Webkit and listen for tail -f /path/to/log.

Upvotes: 0

Related Questions