简体   繁体   中英

calculate the percentage of failed requests along with ip address

Hi i'm trying to calculate the percentage of failed requests. assuming only 200 and 404 error codes,

So far im planning to extract the ip address and the error code and put them in an array . is there a better way to go about it than the approach i have taken

 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

An example: array( "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');

Here is what I came up with. It lets you specify the status code you want the percentage of. Your question was for the percentage, but you also mentioned storing the IP addresses, so this function stores the IP along with its status code in arrays (matched by their index number) so you can do what you want with the data stored there (determine the percentage of a status per IP, etc).

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM