【问题标题】:Display the last 100 lines of a log file in real time实时显示日志文件的最后 100 行
【发布时间】:2018-03-28 07:34:37
【问题描述】:

我希望能够在 div 窗口中显示日志文件的最后 100 行,并使其实时更新,因此如果将某些内容写入日志,窗口将写入新的日志内容用户看到。目前我只这样做了一次,但效果很好,我只需要一种每秒实时更新它的方法:

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

【问题讨论】:

  • 您必须通过 javascript 使用计时器 + ajax 来调用 PHP 脚本以获取最新行。
  • @cmorrissey OP 声明:“目前我只这样做了一次,但效果很好,我只需要一种每秒实时更新它的方法”。跨度>
  • 您可以添加标题以在特定时间间隔自动刷新页面。比ajax简单。 w3schools.com/tags/att_meta_http_equiv.asp
  • @Nic 会刷新整个页面,而不仅仅是 div。

标签: php html file logging


【解决方案1】:

这是一个基本的解决方案。

这是你的 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);
  }

  ?>

【讨论】:

    猜你喜欢
    • 2023-03-03
    • 2016-08-27
    • 1970-01-01
    • 2020-07-02
    • 1970-01-01
    • 1970-01-01
    • 2011-10-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多