1

I want to be able to display the last 100 lines of a log file in a div window, and have it update in real time, so if something would be written to the log, the window would write the new log content for the user to see. Currently I'm doing this only once but it works fine, I just need a way to update it real time every second:

<?php
$file = "logfile.log";
$f = fopen($file, "r");
while ($line = fgets($f, 100) ) {
    print $line . "<br/>";
}
?>
j08691
  • 204,283
  • 31
  • 260
  • 272
Daniel Holler
  • 235
  • 1
  • 5
  • 14

1 Answers1

3

This is a basic solution.

Here is your html and js index.php

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Read Log File</title>

</head>

<body>
<div>
    <ul id="log">

    </ul>
</div>
<script src="./jquery-3.2.1.min.js"></script> 
<script>

    $(function(){

        setInterval(function(){
            $.getJSON( "./getLog.php", function( data ) {
              var $log = $('#log');
              $.each( data, function( key, val ) {
                $log.prepend( "<li>" + val + "</li>" );
              });
            });

        },5000);

    });

</script>
</body>
</html>

Here is your php file getLog.php

  <?php

  session_start();

  $file  = '/path/to/your/file_log';

  $total_lines = shell_exec('cat ' . escapeshellarg($file) . ' | wc -l');

  if(isset($_SESSION['current_line']) && $_SESSION['current_line'] < $total_lines){

    $lines = shell_exec('tail -n' . ($total_lines - $_SESSION['current_line']) . ' ' . escapeshellarg($file));

  } else if(!isset($_SESSION['current_line'])){

    $lines = shell_exec('tail -n100 ' . escapeshellarg($file));

  }

  $_SESSION['current_line'] = $total_lines;

  $lines_array = array_filter(preg_split('#[\r\n]+#', trim($lines)));

  if(count($lines_array)){
    echo json_encode($lines_array);
  }

  ?>
cmorrissey
  • 8,493
  • 2
  • 23
  • 27