2017-10-16 207 views
-1

我希望能夠在div窗口中顯示日誌文件的最後100行,並實時更新日誌文件,因此如果將某些內容寫入日誌,窗口會寫入新的日誌內容供用戶查看。目前我只做了一次,但它工作正常,我只需要一種方法來實時更新它每秒鐘:實時顯示日誌文件的最後100行

<?php 
$file = "logfile.log"; 
$f = fopen($file, "r"); 
while ($line = fgets($f, 100)) { 
    print $line . "<br/>"; 
} 
?> 
+2

你必須使用一個計時器+ AJAX通過JavaScript調用PHP腳本來獲得最新的線路。 – aynber

+0

[PHP - 返回文件中的最後一行?]可能的重複(https://stackoverflow.com/questions/1062716/php-returning-the-last-line-in-a-file) – cmorrissey

+0

@cmorrissey OP狀態:*「目前我只做了一次,但它工作正常,我只需要一種方法來實時更新它每秒」*。 –

回答

2

這是一個基本的解決方案。

這是你的HTML和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> 

這是你的PHP文件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); 
    } 

    ?>