php скрипт за четене на апах лога

php скрипт за четене на апах лога

малко тулче с автоматичен рефреш на лога

За да направим малко пхп скрипче за четене на парснат лог за апаха ни е нужно първо да променим конфигурацията на апаха (може и в самият виртуален хост), добавяйки отделен ерор лог в папка, до която апах юзера има достъп и формат, който ни е удобен за четене, примерно:

    ErrorLogFormat "[%t]:::[%l]:::[%a]:::[%M]"
    ErrorLog "/srv/laravel-vue.eu/testlog/some_new.err.log"
    <Directory "/srv/laravel-vue.eu/testlog">
        Options +FollowSymLinks
        AllowOverride All
        Require ip 10
    </Directory>

    Alias "/testlog/" "/srv/laravel-vue.eu/testlog/"
Bash

След това добавяме двата пхп скрипта /srv/laravel-vue.eu/testlog/index.php:

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Read Log File</title>
<link href="./css/bootstrap.min.css" rel="stylesheet">
<script src="./js/bootstrap.bundle.min.js"></script>
</head>

<body>
<div class="container-xl mx-auto">

  <div class="form-check form-switch my-5">
    <input class="form-check-input" type="checkbox" role="switch" id="refbutt" checked>
    <label class="form-check-label" for="refbutt" id="ref_label">put</label>
  </div>

  <div class="overflow-auto">
    <table class="table table-hover" id="log">
      <thead>
        <tr>
          <th scope="col">Дата</th>
          <th scope="col">Вид</th>
          <th scope="col">IP</th>
          <th scope="col">Body</th>
        </tr>
       </thead>
      <tbody id="log"></tbody
    </table>
  </div>
</div>
<script src="./js/jquery-3.6.1.min.js"></script>

<script>
    $(function(){
      let is_ref = true
      let intervalID;
      start();
      $('#refbutt').click(function() {
        is_ref = !is_ref
        if(is_ref === true){
          start();
        } else {
          stop();
        }
      });
      function start(){
        intervalID = setInterval(startLogRotate, 5000);
        $('#refbutt').checked = true
        $('#ref_label').text('рефреш на 5 секунди')
      }
      function stop(){
        clearInterval(intervalID);
        $('#refbutt').checked = false;
        $('#ref_label').text('рефреш изключен')
      }
      function startLogRotate(){
        $.getJSON( "./getLog.php", function( data ) {
          var $log = $('#log');
          $.each( data, function( key, val ) {
            var ip = val['ip'].split(':')[0]
            $log.prepend( "<tr><td>" + val['date'] + "</td><td>" + val['type'] + "</td><td>" + ip + "</td><td>" + val['body'] + "</td></tr>" );
          });
        });
     }
  });

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

Файла /srv/laravel-vue.eu/testlog/getLog.php:

  <?php

  session_start();
  $file  = '/srv/lrclub/testlog/13.lrc.ssl.err.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 ' . ((int) $total_lines - (int) $_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 = [];

  if(isset($lines)){
    $lines_a = array_filter(preg_split('#[\r\n]+#',
      trim($lines)
    ));
    foreach($lines_a as $l){
      $l1 = explode(':::', $l);
      $lines_array[] = [
        'date' => trim(trim($l1[0],'['),']'),
        'type' => trim(trim($l1[1],'['),']'),
        'ip' => trim(trim($l1[2],'['),']'),
        'body' => trim(trim($l1[3],'['),']'),
      ];
    }
  }

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

?>
PHP

Обръщаме внимание и на изискуемите css/js файлове