我正在尝试为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;
?>
答案 0 :(得分:-1)
cd /etc/logrotate.d/;
回声“ / var / log / httpd / * / etc / httpd / logs / * {
每日
最大1
旋转1
大小1M
missingok
notifempty
共享脚本
压缩
delaycompress
后旋转
/ bin / systemctl重新加载httpd.service> / dev / null 2> / dev / null ||真实
尾标
}“> httpd;