编写思路:
1、使用"grep"读取接口日志,并从中获取一分钟接口请求条目
2、使用"awk"截取时间部分(到秒)
3、使用"uniq -c"统计重复时间数量(即每秒的请求条目数量=请求并发数量(QPS))
4、使用"awk"截取每秒的请求条目数量部分,并使用"sort -nr"进行降序排序
5、最后使用"head -n 1"获取一分钟之内最大请求并发数量
日志内容:
2020-10-11 10:12:16.891 c.w.z.s.JxAuthenticationFilter [INFO] - 收到请求: FAB0D8CE52761C2090EB8743C5556795 request to http://yzapi.winsunexpo.com/expo/api/ticket/get,参数:{"token":["3xxxa677e8eb049208b9a9ab96d29f54"],"expoId":["2"],"appId":["5dxxxf8d78ace679544b15b5e2c7d1bc"],"timestamp":["1601596429898"],"device":["h5"]},,IP:47.97.115.208
脚本内容:
grep -E "^$(date +%Y-%m-%d \%H:%M).*收到请求.*" /var/log/wsexpo_server/wsexpo-zuul/wsexpo-zuul.$(date +%Y-%m-%d).log|awk -F '.' '{print $1}'|uniq -c|awk '{print $1}'|sort -nr|head -n 1
说说好处:
使用"grep"命令截取较少的日志,相比其他"sedcat"等命令其执行效率更高,执行时间更短(可以使用"time"命令测试一下),并只需要占用较少的CPU。
当配合监控工具进行获取监控值时,如果每秒都去执行获取接口并发数量,这将占用大量的CPU时间,所以我们尽量降低执行脚本的频率,以上示例获取并处理一分钟的日志,即每分钟执行一次(建议)。
其他补充:
可以通过以上方式结合Zabbix等监控工具完成对接口的并发请求数量的监控!