读取和限制Apache日志文件


Reading and Limiting Apache Log File

我正试图为Apache access.log文件创建一个解析脚本,该脚本最终将以图形的形式给出输出,但现在我需要将结果限制在我所做的最后50行,但它也需要按站点进行限制(我的服务器上有很多),并且只显示不同的访问者。我主要想知道游客是从哪里来的,而不是他们一到那里就做了什么。

下面的代码是反向排序,并提取有限数量的条目。然而,它还没有受到网站或不同访问者的限制,而是在创建文件。解析部分尚未完成,因此在浏览器中运行时不会输出任何内容,但也不会出现任何错误。

<?php
$log_path = (getenv('REMOTE_ADDR') == "127.0.0.1") ? "C:/Server/Apache/logs" : "/usr/local/apache/logs";
$LogFile = "$log_path/access.log";
$TmpFile = "$log_path/logreversed.txt";
function LimitSize($path, $tmp, $line_count, $block_size) {
    $lines = array();
    $fh = fopen($path, 'r');
    fseek($fh, 0, SEEK_END);
    do {
        $can_read = $block_size;
        if( ftell($fh) < $block_size) :
            $can_read = ftell($fh);
        endif;
        fseek($fh, -$can_read, SEEK_CUR);
        $data = fread($fh, $can_read);
        fseek($fh, -$can_read, SEEK_CUR);
        $split_data = array_reverse(explode("'n", $data));
        $new_lines = array_slice($split_data, 0, -1);
        $lines = array_merge($lines, $new_lines);
    }
    while (count($lines) < $line_count && ftell($fh) != 0);
    fclose($fh);
    $output = array_slice($lines, 1, $line_count);
    $text = "";
    foreach ($output as $key => $value) :
        $text .= $key." : ".$value."'n";
    endforeach;
    $fh = fopen($tmp, "w") or die("Could not open tmp file.");
    fwrite($fh, $text) or die("Could not write file!");
    fclose($fh);
}
LimitSize($LogFile, $TmpFile, 50, 16384);
$pattern = '/^([^ ]+) ([^ ]+) ([^ ]+) ('[[^']]+']) "(.*) (.*) (.*)" ([0-9'-]+)
    ([0-9'-]+) "(.*)" "(.*)"$/';
if (is_readable($TmpFile)) :
    $fh = fopen($TmpFile,'r') or die($php_errormsg);
    $requests = array();
    $i = 1;
    while (!feof($fh)) :
        if ($s = trim(fgets($fh,16384))) :
            if (preg_match($pattern,$s,$matches)) :
                list($whole_match,$remote_host,$logname,$user,$time,
                     $method,$request,$protocol,$status,$bytes,$referer,
                     $user_agent) = $matches;
                $requests[$request]++;
            else :
                error_log("Can't parse line $i: $s");
            endif;
        endif;
    endwhile;
    fclose($fh) or die($php_errormsg);
    foreach ($requests as $request => $accesses) :
        printf("%6d   %s'n",$accesses,$request);
    endforeach;
else : 
    echo "cannot access log file!";
endif;
?>

cd/etc/logrotate.d/
echo"/var/log/httpd/*/etc/httpd/logs/*{
每日
最大值1
旋转1
尺寸1M
密辛戈克
注意
共享脚本
压缩
延迟压缩
后旋转/bin/systemctl重载httpd.service>/dev/null 2>/dev/null |true
结束脚本
}">httpd;