【问题标题】:calculate the percentage of failed requests along with ip address计算失败请求的百分比以及 IP 地址
【发布时间】:2015-11-09 19:25:14
【问题描述】:

您好,我正在尝试计算失败请求的百分比。 假设只有 200 和 404 错误代码,

到目前为止,我计划提取 IP 地址和错误代码并将它们放入一个数组中。 有没有比我采取的方法更好的方法来解决它

 Sample access log content:
 <pre>
 192.168.2.20 - - [28/Jul/2006:10:27:10 -0300] "GET /try/ HTTP/1.0" 200 3395
 127.0.0.1 - - [28/Jul/2006:10:22:04 -0300] "GET / HTTP/1.0" 200 2216
 127.0.0.1 - - [28/Jul/2006:10:27:32 -0300] "GET /hidden/ HTTP/1.0" 404 7218
 </pre>

and trying to output array as below

一个例子: 大批( "127.0.0.1" => 0.5, “192.168.2.20” => 0, )

       function analyzeAccessLog($fileName)
        {
            //$fh = fopen($fileName,'r') 
            $people = file_get_contents($fileName);
            if (preg_match('/\200|404?\w/',$people,$matches)) {
            {
                  $int1=$matches[0];
                  print "$int1 \n";
              }
            }
            }
           analyzeAccessLog('log.txt');

【问题讨论】:

    标签: php text-extraction


    【解决方案1】:

    这是我想出的。它可以让你指定你想要的状态码的百分比。您的问题是关于百分比的,但您还提到了存储 IP 地址,因此此函数将 IP 及其状态代码存储在数组中(与其索引号匹配),这样您就可以对存储在那里的数据执行您想要的操作(确定每个 IP 的状态百分比等)。

    function analyzeAccessLog($fileName,$status = '404'){
        $lines = file($fileName);
        $i = 0;
        $s = 0;
        foreach ($lines as $line) {
    
            //Get the IP
            $ip = array();
            $ip = explode('-',$line);
            $data['ip'][$i] = trim($ip[0]);
    
            //Get the status code.
            $code = array();
            $code = array_map('strrev', explode(' ', strrev($line)));
            $data['code'][$i] = trim($code[1]);
            if($code[1] == $status){
                $s++;
            }
            $i++;
        }
        $percentage = round((($s/$i)*100),2).'% status code '.$status;
        return $percentage;
    }
    
    $data = analyzeAccessLog('file.txt');
    
    echo($data);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-06
      • 2023-03-09
      • 1970-01-01
      • 1970-01-01
      • 2015-08-19
      • 2018-04-12
      相关资源
      最近更新 更多