实时显示日志文件的最后100行
问题描述:
我希望能够在div窗口中显示日志文件的最后100行,并实时更新日志文件,因此如果将某些内容写入日志,窗口会写入新的日志内容供用户查看。目前我只做了一次,但它工作正常,我只需要一种方法来实时更新它每秒钟:实时显示日志文件的最后100行
<?php
$file = "logfile.log";
$f = fopen($file, "r");
while ($line = fgets($f, 100)) {
print $line . "<br/>";
}
?>
答
这是一个基本的解决方案。
这是你的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);
}
?>
你必须使用一个计时器+ AJAX通过JavaScript调用PHP脚本来获得最新的线路。 – aynber
[PHP - 返回文件中的最后一行?]可能的重复(https://*.com/questions/1062716/php-returning-the-last-line-in-a-file) – cmorrissey
@cmorrissey OP状态:*“目前我只做了一次,但它工作正常,我只需要一种方法来实时更新它每秒”*。 –