分析nginx日志统计接口情况

一、背景

近来打算对后端接口进行优化,所以要先对现有接口的情况进行统计。因为相关业务接口是index.php?action=XXX的形式,所以公司运维的管理平台并不能满足需求,所以要自行处理nginx日志获取接口的情况了。

二、处理思路

1.nginx日志中不止包含相关接口的日志,所以先要根据关键字段将需要的日志过滤出来。

2.分析nginx.conf中的日志格式,方便提取相关的字段

3.使用正则表达式将日志数据提取出来

4.处理数据,形成统计数据

(统计数据主要包括:接口action、调用总次数、2s以上的次数、慢数量占比、最大耗时、平均耗时)

三、脚本代码

因为这个脚本基本上算是一次性的,所以在细节地方可能考虑不全
 
复制代码
<?php
//这里是对应的nginx.conf中的配置
$configData = '[$time_local] [$request] [$status] [$http_referer] [$request_time] [$upstream_response_time]';
$regex = '/\[([^\]]*)\]/ism';
preg_match_all($regex, $configData, $config);
$config = array_flip($config[1]);
//需要的字段
$keyList = array('$request_time', '$upstream_response_time');
$fp = fopen('nginx.log', 'r');
$result = array();
//逐行读取日志(一开始想用file_get_contents然后在explode生成数组,后因为文件比较大所以就弃用了)
while (!feof($fp)) {
    $logValue = fgets($fp);
    //处理日志数据
    preg_match_all($regex, trim($logValue), $log);
    $logList = $log[1];
    //提取需要的数据
    foreach ($keyList as $key) {
    $tmp[$key] = $logList[$config[$key]];
    }
    //从请求头中提取action
    $actionRegex = '/(?<=action=)[^&]*/';
    preg_match($actionRegex, $tmp['$request'], $action);
    $action = $action[0];
    //处理数据
if (isset($result[$action])) {
    $result[$action]['count']++;
    $result[$action]['allRequest'] += $tmp['$request_time'];
    if ($tmp['$request_time'] > $result[$action]['maxRequest']) {
    $result[$action]['maxRequest'] = $tmp['$request_time'];
    }
    if ($tmp['$request_time'] > 2) {
    $result[$action]['slowCount']++;
    }
    $result[$action]['averageRequest'] = $result[$action]['allRequest'] / $result[$action]['count'];
} else {
    $result[$action] = array(
    'count' => '1',
    'slowCount' => '0',
    'allRequest' => $tmp['$request_time'],
    'maxRequest' => $tmp['$request_time'],
    'averageRequest' => $tmp['$request_time'],
);
}
}
file_put_contents('result.log', json_encode($result));

四、正则表达式详解

 
复制代码
$regex = '/\[([^\]]*)\]/ism';

\[  \] 是指以 "["开始及以"]"结束
() 是标记子表达式,并且可以提取出来使用
[^\]] 是中括号表达式,可以匹配任何字符除了"]"
* 是重复之前的中括号表达式零次或者多次

$actionRegex = '/(?<=action=)[^&]*/';
(?<=action=) 是反向肯定预查,从"action="处开始匹配查找字符串
[^&] 是中括号表达式,可以匹配任何字符除了"&"

五、统计结果

从nginx日志中获取了几天数据进行分析,截取了部分数据,之后就可以结合代码进行优化了!

 

六、心得

正则表达式每次用的时候还是不太稳,还是要多实践实践!


作者:caohaoyu
链接:https://juejin.cn/post/6844903655024361479
来源:稀土掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
posted @ 2024-03-26 21:21  GaoYanbing  阅读(97)  评论(0编辑  收藏  举报