不废话,上来直接干
1. 先将nginx 日志格式调整如下:
http {
log_format MyFormat '$remote_addr | $remote_user | [$time_local] | $status | $request_time | $upstream_response_time | '
'$request_method | $http_host | $request_uri | '
'$request_length | $body_bytes_sent | "$http_referer" | "$http_user_agent"';
}
选用日志格式:
server {
access_log /home/wwwlogs/xxxxx.log MyFormat;
}
注意这里的MyFormat 与上面log_format指令后面的名字是一致的.
得出结果如下:
120.76.16.232 | - | [18/Jan/2019:20:19:10 +0800] | 200 | 0.193 | 0.193 | POST | xbedclean.xbed.com.cn | /admin/appOrderAction/list | 758 | 3504 | "-" | "Dalvik/2.1.0 (Linux; U; Android 7.0; MI 5s MIUI/V10.1.1.0.NAGCNFI)"
2. 通过awk 进行分组统计:
IP统计
awk -F '|' '{ g[$1]=$1 } END { for(i in g) print g[i] }' xxxxxxxx.log
注意:这里不能出现 BEGIN ,只能出现一个END才能统计
3. 请求统计
(会统计调用次数、总时间、平均耗时)
#! /bin/bash
# Usage: xx.sh {排序的列} {日志文件}
# e.g:
# xx.sh 4 xxx.log
# xx.sh 4 < xxx.log
# cat xxx.log | ./xx.sh 4
# 排序的列可选值:
# 1--url地址
# 2--请求次数
# 3--总消耗时间
# 4--平均消耗时间
#
# 本脚本用于统计url请求次数、平均消耗时间。
# 提醒: 会针对restful风格进行处理, 例如有/api/room/2000 , /api/room/1000,会当作同一个接口 /api/room
sortPos=4
if [ -n "$2" ]; then
sortPos=$2
fi
echo "url | request count | total seconds | avg seconds "
awk -F '|' ' { key=$9; pos=index(key,"?"); if(pos>0) key=substr(key,1,pos); } \
{ bef=key } \
{ gsub(/\/[0-9]+\?*$/,"",key) } \
{ gsub(/\/[0-9]+/,"",key) } \
{ af=key } \
{ keys[key]=key } \
{ _total_[key]=_total_[key]+$5 } \
{ reqCount[key]=reqCount[key]+1 } \
END \
{ for(k in keys) print keys[k],"|", reqCount[k] ,"|", _total_[k], "|" , _total_[k]/reqCount[k] }' $1 | sort -n -t '|' -k $sortPos